/* MAG Lifestyle Development — interactive prototype
   Single root component, view-state routed. */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ----------------------------------------------------------------
   Icons (inline SVG — no external icon font)
   ---------------------------------------------------------------- */
const I = {
  arr: (p={}) => <svg width="14" height="10" viewBox="0 0 14 10" fill="none" {...p}><path d="M0 5h12M8 1l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square"/></svg>,
  arrL: (p={}) => <svg width="14" height="10" viewBox="0 0 14 10" fill="none" {...p}><path d="M14 5H2M6 1L2 5l4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square"/></svg>,
  arrLong: (p={}) => <svg width="22" height="10" viewBox="0 0 22 10" fill="none" {...p}><path d="M0 5h20M16 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/></svg>,
  close: (p={}) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.4"/></svg>,
  whatsapp: (p={}) => <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.7.9-.9 1.1-.2.1-.3.2-.6.1-.8-.4-1.6-.9-2.3-1.6-.6-.6-1.1-1.3-1.5-2.1-.1-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.2-.5.1-.2 0-.3 0-.5l-.7-1.8c-.2-.5-.4-.5-.6-.5h-.5c-.2 0-.5.1-.7.4-.7.7-1.1 1.7-1 2.7.2 1.2.6 2.4 1.4 3.4 1.4 2 3.4 3.4 5.7 4.1.7.2 1.3.3 2 .3.7 0 1.4-.2 2-.5.6-.4 1-1 1.2-1.7.1-.4.1-.8.1-1.2-.1-.2-.3-.3-.6-.4M12 0C5.4 0 0 5.4 0 12c0 2.1.6 4.2 1.6 6L0 24l6.2-1.6c1.8.9 3.8 1.4 5.8 1.4 6.6 0 12-5.4 12-12S18.6 0 12 0m0 22c-1.8 0-3.6-.5-5.1-1.4l-.4-.2-3.7 1 1-3.6-.2-.4C2 15.7 1.5 13.9 1.5 12 1.5 6.2 6.2 1.5 12 1.5 17.8 1.5 22.5 6.2 22.5 12c.1 5.8-4.6 10.5-10.4 10.5z"/></svg>,
  download: (p={}) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M7 1v9m0 0L3 6m4 4l4-4M1 13h12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square"/></svg>,
  pin: (p={}) => <svg width="14" height="16" viewBox="0 0 14 16" fill="none" {...p}><path d="M7 1a5 5 0 0 0-5 5c0 4 5 9 5 9s5-5 5-9a5 5 0 0 0-5-5z" stroke="currentColor" strokeWidth="1.4"/><circle cx="7" cy="6" r="1.5" fill="currentColor"/></svg>,
  check: (p={}) => <svg width="22" height="22" viewBox="0 0 22 22" fill="none" {...p}><path d="M4 11l5 5 9-10" stroke="currentColor" strokeWidth="2"/></svg>,
  play: (p={}) => <svg width="10" height="12" viewBox="0 0 10 12" fill="currentColor" {...p}><path d="M0 0v12l10-6z"/></svg>,
  globe: (p={}) => <svg width="12" height="12" viewBox="0 0 12 12" fill="none" {...p}><circle cx="6" cy="6" r="5" stroke="currentColor" strokeWidth="1"/><path d="M1 6h10M6 1c1.5 1.5 2.5 3 2.5 5S7.5 9.5 6 11M6 1c-1.5 1.5-2.5 3-2.5 5S4.5 9.5 6 11" stroke="currentColor" strokeWidth="1"/></svg>,
};

/* ----------------------------------------------------------------
   Helpers
   ---------------------------------------------------------------- */
const projectBySlug = (slug) => PROJECTS.find(p => p.slug === slug);
const safeImg = (p) => p.img || "media/home-og.webp";
const useScroll = () => {
  const [y, setY] = useState(0);
  useEffect(() => {
    const on = () => setY(window.scrollY);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  return y;
};

/* ----------------------------------------------------------------
   Top Nav
   ---------------------------------------------------------------- */
function TopNav({ view, locale, setLocale, go, onRegister, onBrochure }) {
  const y = useScroll();
  const onHero = view === "home" || view.startsWith("microsite:");
  const lightMode = !onHero || y > 80;
  const L = LOCALES[locale];

  return (
    <nav className={`nav ${lightMode ? "is-light" : "is-overlay-dark"}`}>
      <button className="nav-logo" onClick={() => go("home")} aria-label="MAG home">
        <span className="mark" aria-hidden>M</span>
        <span>MAG <em style={{fontStyle: "italic", opacity: 0.85}}>Lifestyle</em></span>
      </button>

      <div className="nav-links">
        <button onClick={() => go("projects:current")} className={view.startsWith("projects:current") ? "is-active" : ""}>{L.nav.current}</button>
        <button onClick={() => go("projects:keturah")} className={view.startsWith("projects:keturah") ? "is-active" : ""}>{L.nav.keturah}</button>
        <button onClick={() => go("projects:completed")} className={view.startsWith("projects:completed") ? "is-active" : ""}>{L.nav.legacy}</button>
        <button onClick={() => go("why-mag")} className={view === "why-mag" ? "is-active" : ""}>{L.nav.whyMag}</button>
        <button onClick={() => go("brokers")} className={view === "brokers" ? "is-active" : ""}>{L.nav.brokers}</button>
        <button onClick={() => go("contact")} className={view === "contact" ? "is-active" : ""}>{L.nav.contact}</button>
      </div>

      <div className="nav-right">
        <span className="locale" title="Locale">
          {I.globe({style:{opacity:0.6, marginRight:6}})}
          {Object.keys(LOCALES).map((k) => (
            <button key={k} className={k === locale ? "is-on" : ""} onClick={() => setLocale(k)}>{k.toUpperCase()}</button>
          ))}
        </span>
        <button className="btn btn-sm btn-coral" onClick={onRegister}>
          {L.cta.register} {I.arr({style:{marginLeft:4}})}
        </button>
      </div>
    </nav>
  );
}

/* ----------------------------------------------------------------
   Hero
   ---------------------------------------------------------------- */
function Hero({ locale, onRegister, onScroll, go, heroVariant, showCoords }) {
  const slides = HERO_SLIDES;
  const startIdx = useMemo(() => {
    const i = slides.findIndex(s => s.id === heroVariant);
    return i >= 0 ? i : 0;
  }, [heroVariant]);
  const [idx, setIdx] = useState(startIdx);
  useEffect(() => setIdx(startIdx), [startIdx]);
  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % slides.length), 7200);
    return () => clearInterval(id);
  }, [slides.length]);
  const L = LOCALES[locale];
  const slide = slides[idx];
  const bg = slide.img;

  return (
    <header className="hero">
      <div className="hero-bg" style={{ backgroundImage: `url(${bg})` }} />
      <div className="hero-grad" />

      <div className="hero-thumbs" aria-label="Hero scenes">
        {slides.map((s, i) => (
          <button
            key={s.id}
            className={`hero-thumb ${i === idx ? "is-on" : ""}`}
            style={{ backgroundImage: `url(${s.img})` }}
            onClick={() => setIdx(i)}
            aria-label={s.eyebrow}
          >
            <span className="ttl">{`0${i+1}`}</span>
          </button>
        ))}
      </div>

      <div className="hero-inner">
        <div>
          <div className="hero-eyebrow">
            <span className="bar" />
            <span>{slide.eyebrow}</span>
          </div>
          <h1 className="hero-h1" data-rtl={LOCALES[locale].dir === "rtl" ? "1" : "0"}>
            {locale === "en" ? (
              <>The art of <em>living</em><br /><span className="accent">well.</span></>
            ) : (
              <span>{L.hero.eyebrow ? L.hero.eyebrow : "—"}<br /><em style={{fontStyle:"italic"}}>—</em></span>
            )}
          </h1>
          {locale !== "en" && (
            <p style={{ marginTop: 24, color: "rgba(255,255,255,0.85)", maxWidth: "44ch", fontSize: 18, lineHeight: 1.5, fontWeight: 300, direction: L.dir }}>
              {L.hero.lede}
            </p>
          )}
        </div>

        <div className="hero-foot">
          <div>
            <div className="label">Statement</div>
            <div className="value">
              {locale === "en"
                ? "Property developers in Dubai building more than luxury homes — communities that can uplift you."
                : L.hero.lede}
            </div>
          </div>
          <div>
            <div className="label">Now showing</div>
            <div className="value">{slide.eyebrow}</div>
            {showCoords && (
              <div className="value-mono" style={{ marginTop: 8, opacity: 0.75 }}>
                {projectBySlug(slide.project)?.coord || "—"}
              </div>
            )}
          </div>
          <div className="hero-actions">
            <button className="btn btn-coral" onClick={onRegister}>
              {L.cta.register} {I.arr()}
            </button>
            <button className="btn btn-ghost-light" onClick={() => go(`microsite:${slide.project}`)}>
              {locale === "en" ? "View project" : L.cta.explore} {I.arr()}
            </button>
          </div>
        </div>
      </div>
    </header>
  );
}

/* ----------------------------------------------------------------
   Section: Current projects ribbon (mixed grid)
   ---------------------------------------------------------------- */
function CurrentProjectsRibbon({ go, locale }) {
  const items = PROJECTS.filter(p => p.cat === "current");
  // size pattern: 7 / 5 / 4 / 4 / 4
  const spans = ["span-7", "span-5", "span-4", "span-4", "span-4"];

  return (
    <section className="section wrap" id="current">
      <div className="section-head">
        <div className="lhs">
          <span className="kicker"><span className="sq" />{locale === "en" ? "Current Projects" : LOCALES[locale].nav.current}</span>
          <h2 className="t-display t-h2">
            Five live launches.<br/><em>One Dubai, many addresses.</em>
          </h2>
        </div>
        <div className="rhs">
          <p className="t-lede">
            MAG Lifestyle's current pipeline spans MBR City, Dubailand, and Jumeirah Lake Towers — each project programmed for its own neighborhood rhythm.
            <span className="confirm-tag">RERA/DLD to confirm per project</span>
          </p>
          <div style={{ marginTop: 24 }}>
            <button className="link-underline" onClick={() => go("projects:current")}>
              View all current projects {I.arrLong()}
            </button>
          </div>
        </div>
      </div>

      <div className="proj-grid">
        {items.map((p, i) => (
          <ProjectCard key={p.slug} p={p} idx={i + 1} className={spans[i] || "span-4"} onClick={() => go(`microsite:${p.slug}`)} />
        ))}
      </div>
    </section>
  );
}

function ProjectCard({ p, idx, className, onClick }) {
  return (
    <article className={`proj-card ${className || ""}`} onClick={onClick}>
      <div className="frame">
        <span className="num">{String(idx).padStart(2, "0")}</span>
        {p.cat === "keturah" && <span className="chip is-green">Keturah</span>}
        {p.cat === "current" && <span className="chip">Current</span>}
        {p.cat === "completed" && <span className="chip">Completed</span>}
        <img src={safeImg(p)} alt={`${p.name} render`} loading="lazy" />
      </div>
      <div className="meta">
        <div className="sub">{p.location || "Dubai, UAE"}</div>
        <div className="ttl">{p.name}</div>
        {p.tagline && <div className="t-body" style={{ color: "var(--muted)", marginTop: 4 }}>{p.tagline}</div>}
        <span className="read">Read more {I.arr()}</span>
      </div>
    </article>
  );
}

/* ----------------------------------------------------------------
   Keturah spotlight
   ---------------------------------------------------------------- */
function KeturahSpotlight({ go }) {
  return (
    <section className="keturah section" id="keturah">
      <div className="wrap wrap-in">
        <div className="col-images">
          <div className="img-wide">
            <img src="media/project-keturah-reserve-residences-render-3.webp" alt="Keturah Reserve render" loading="lazy"/>
          </div>
          <div className="img-tall">
            <img src="media/project-keturah-resort-render-1.webp" alt="Keturah Resort render" loading="lazy"/>
          </div>
          <div className="img-tall">
            <img src="media/project-keturah-reserve-townhouses-render-2.webp" alt="Keturah Reserve Townhouses render" loading="lazy"/>
          </div>
        </div>

        <div className="col-copy">
          <span className="seal">Keturah · Bio Living</span>
          <h2 className="t-display t-h2">A wellness brand,<br/><em>not a wellness amenity.</em></h2>
          <p className="t-lede" style={{ color: "#D9D2C0" }}>
            Keturah is MAG's flagship lifestyle brand — designed around the proposition that buildings can support how you breathe, move, and sleep. Reserve, Resort, the Ritz-Carlton-branded Creekside residences, and Keturah Tower form the family.
          </p>

          <div className="stats">
            <div className="stat">
              <div className="v">7 + 12</div>
              <div className="k">Buildings · Mansions <span className="footnote">(Creekside)</span></div>
            </div>
            <div className="stat">
              <div className="v">D7</div>
              <div className="k">MBR City Reserve district</div>
            </div>
            <div className="stat">
              <div className="v">AED 3bn<span style={{ fontSize: 12, marginLeft: 6, opacity: 0.7 }}>*</span></div>
              <div className="k">Reserve scale <span className="footnote">*press-attributed</span></div>
            </div>
          </div>

          <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 8 }}>
            <button className="btn btn-coral" onClick={() => go("microsite:keturah-reserve")}>
              Explore Keturah Reserve {I.arr()}
            </button>
            <button className="btn btn-ghost-light" onClick={() => go("microsite:ritz-carlton-creekside")}>
              Ritz-Carlton Creekside {I.arr()}
            </button>
          </div>

          <div className="footnote" style={{ marginTop: 8 }}>
            "Bio Living" attributed to Keturah. Ritz-Carlton and Marriott are third-party brands — licensing and render rights to be confirmed before launch.
          </div>
        </div>
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------
   Why MAG block
   ---------------------------------------------------------------- */
function WhyMag() {
  const pillars = [
    { n: "01", h: "Real-estate arm of MAG Group", b: "Founded in 1978 as a multi-sector group; the real-estate arm is commonly described as established in 2003.", attrib: "Press / company profile" },
    { n: "02", h: "Scale, attributed", b: "Profiles cite over $5bn portfolio value, 14 completed projects, and 7 in pipeline.", attrib: "Press-attributed — not independently audited" },
    { n: "03", h: "Lifestyle, not floorplate", b: "From MBR City to the Creek, projects are programmed around how residents actually live — light, air, water, walkability." },
    { n: "04", h: "Investor-credible", b: "Branded residences, transparent CRM-routed lead capture, and bilingual (EN/AR) campaign pages today — RU/ZH on the roadmap." },
  ];
  return (
    <section className="section wrap" id="why">
      <div className="section-head">
        <div className="lhs">
          <span className="kicker is-green"><span className="sq" />Why MAG</span>
          <h2 className="t-display t-h2">Forty-eight years of group legacy.<br/><em>Twenty-three of building Dubai.</em></h2>
        </div>
        <div className="rhs">
          <p className="t-lede">
            The published figures here are press- and company-attributed. We carry the attribution through to every page so you always know the source.
          </p>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", gap: 24 }}>
        {pillars.map(p => (
          <div key={p.n} className="bro-card">
            <div className="t-mono" style={{ color: "var(--secondary)" }}>{p.n}</div>
            <div className="ttl">{p.h}</div>
            <div className="sub">{p.b}</div>
            {p.attrib && <div className="attrib" style={{ marginTop: 8 }}>{p.attrib}</div>}
          </div>
        ))}
      </div>

      <div className="awards" style={{ marginTop: 56 }}>
        <span className="t-mono" style={{ marginRight: 16 }}>Recognition</span>
        <span className="award-slot">IPA — to confirm</span>
        <span className="award-slot">Luxury Lifestyle Awards — to confirm</span>
        <span className="award-slot">WELL claim — to confirm</span>
        <span className="award-slot">Issuer + year — to confirm</span>
      </div>
      <p className="t-small" style={{ marginTop: 12, textAlign: "center", maxWidth: "62ch", marginInline: "auto" }}>
        Awards / certifications shown as placeholders only. We will not publish logos, issuers, or year claims until rights and dates are client-confirmed.
      </p>
    </section>
  );
}

/* ----------------------------------------------------------------
   Legacy / Completed strip
   ---------------------------------------------------------------- */
function LegacyStrip({ go, locale }) {
  const items = PROJECTS.filter(p => p.cat === "completed");
  return (
    <section className="legacy section wrap" id="legacy">
      <div className="section-head">
        <div className="lhs">
          <span className="kicker"><span className="sq" />{LOCALES[locale].nav.legacy}</span>
          <h2 className="t-display t-h2">Built before, still standing.</h2>
        </div>
        <div className="rhs">
          <p className="t-lede">
            Completed and legacy assets are clearly separated from current launches across every locale of the site — never collapsed into one "active" list.
          </p>
          <div style={{ marginTop: 24 }}>
            <button className="link-underline" onClick={() => go("projects:completed")}>
              All completed projects {I.arrLong()}
            </button>
          </div>
        </div>
      </div>

      <div className="legacy-list">
        {items.slice(0, 8).map((p, i) => (
          <button key={p.slug} className="legacy-item" onClick={() => p.img ? go(`microsite:${p.slug}`) : null}>
            <span className="n">{String(i+1).padStart(2,"0")} / {String(items.length).padStart(2,"0")}</span>
            <span className="ttl">{p.name}</span>
            <span className="sub">{p.location}</span>
          </button>
        ))}
      </div>
    </section>
  );
}

/* ----------------------------------------------------------------
   Contact + Footer
   ---------------------------------------------------------------- */
function ContactSection({ onRegister, onViewing }) {
  return (
    <section className="section wrap" id="contact">
      <div className="section-head">
        <div className="lhs">
          <span className="kicker"><span className="sq" />Contact</span>
          <h2 className="t-display t-h2">Verified channels,<br/><em>investor-grade response.</em></h2>
        </div>
        <div className="rhs">
          <p className="t-lede">
            Every published contact below is verified against mag.global. Items marked <span className="confirm-tag">CONFIRM</span> still require client sign-off before publishing.
          </p>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }}>
        <div className="bro-card">
          <div className="t-mono">Head office <span className="verified" style={{ marginLeft: 8 }}><span className="d"/>Verified</span></div>
          <div className="ttl">Emirates Financial Towers</div>
          <div className="sub">27th Floor, South Tower, DIFC, Dubai, UAE</div>
          <div className="t-small" style={{ marginTop: 8 }}>
            PO Box & map coordinates <span className="confirm-tag">CONFIRM</span><br/>
            Opening hours <span className="confirm-tag">CONFIRM</span>
          </div>
        </div>
        <div className="bro-card">
          <div className="t-mono">Telephone <span className="verified" style={{ marginLeft: 8 }}><span className="d"/>Verified</span></div>
          <div className="ttl">+971 4 355 5580</div>
          <div className="sub">Toll-free 800 624 (800 MAG)</div>
          <div className="t-small" style={{ marginTop: 8 }}>
            Sales-specific line <span className="confirm-tag">CONFIRM</span>
          </div>
        </div>
        <div className="bro-card">
          <div className="t-mono">Email <span className="verified" style={{ marginLeft: 8 }}><span className="d"/>Verified</span></div>
          <div className="ttl">info@mag.global</div>
          <div className="sub">marketing@mag.global</div>
          <div className="t-small" style={{ marginTop: 8 }}>
            Dedicated sales/leads inbox <span className="confirm-tag">CONFIRM</span>
          </div>
        </div>
      </div>

      <div style={{ marginTop: 48, display: "flex", gap: 12, flexWrap: "wrap", justifyContent: "center" }}>
        <button className="btn btn-primary btn-lg" onClick={onRegister}>Register interest {I.arr()}</button>
        <button className="btn btn-ghost btn-lg" onClick={onViewing}>Book private viewing {I.arr()}</button>
      </div>
    </section>
  );
}

function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <div className="footer-mark">MAG <em>Lifestyle</em></div>
          <p style={{ maxWidth: "32ch" }}>
            Real-estate development arm of MAG Group. Communities designed around the art of living well.
          </p>
          <p className="t-mono" style={{ color: "rgba(255,255,255,0.45)", marginTop: 16 }}>
            Distinct from MAG Group Holding, MAG of Life, and Keturah.
          </p>
        </div>
        <div>
          <h4>Current</h4>
          <ul>
            <li><a onClick={() => go("microsite:mag-d11")}>MAG D11</a></li>
            <li><a onClick={() => go("microsite:mag-777")}>MAG 777</a></li>
            <li><a onClick={() => go("microsite:mag-330")}>MAG 330</a></li>
            <li><a onClick={() => go("microsite:mag-22")}>MAG 22</a></li>
            <li><a onClick={() => go("microsite:mbl-royal")}>MBL Royal</a></li>
          </ul>
        </div>
        <div>
          <h4>Keturah</h4>
          <ul>
            <li><a onClick={() => go("microsite:keturah-reserve")}>Keturah Reserve</a></li>
            <li><a onClick={() => go("microsite:keturah-resort")}>Keturah Resort</a></li>
            <li><a onClick={() => go("microsite:ritz-carlton-creekside")}>Ritz-Carlton Creekside</a></li>
            <li><a onClick={() => go("microsite:keturah-tower")}>Keturah Tower</a></li>
          </ul>
        </div>
        <div>
          <h4>Visit / contact</h4>
          <ul>
            <li>+971 4 355 5580</li>
            <li>800 624</li>
            <li>info@mag.global</li>
            <li>27th Floor, South Tower<br/>Emirates Financial Towers<br/>DIFC, Dubai</li>
          </ul>
        </div>
      </div>
      <div className="footer-meta">
        <span>© 2026 MAG Lifestyle Development · Demo prototype</span>
        <span>EN · AR · RU · ZH</span>
        <span>Prices, sizes, dates, RERA/DLD facts are never published without client confirmation</span>
      </div>
    </footer>
  );
}

/* ----------------------------------------------------------------
   Projects index view
   ---------------------------------------------------------------- */
function ProjectsView({ go, initialFilter }) {
  const [filter, setFilter] = useState(initialFilter || "all");
  useEffect(() => { setFilter(initialFilter || "all"); }, [initialFilter]);
  const filters = [
    { id: "all", label: "All projects" },
    { id: "current", label: "Current" },
    { id: "keturah", label: "Keturah" },
    { id: "completed", label: "Completed / Legacy" },
  ];
  const items = filter === "all" ? PROJECTS : PROJECTS.filter(p => p.cat === filter);
  const counts = {
    all: PROJECTS.length,
    current: PROJECTS.filter(p=>p.cat==="current").length,
    keturah: PROJECTS.filter(p=>p.cat==="keturah").length,
    completed: PROJECTS.filter(p=>p.cat==="completed").length,
  };

  return (
    <div className="page-enter" style={{ paddingTop: 100 }}>
      <section className="section wrap" style={{ paddingBottom: 32 }}>
        <div className="section-head">
          <div className="lhs">
            <span className="kicker"><span className="sq" />Portfolio · 2026</span>
            <h1 className="t-display t-h1" style={{ fontSize: "clamp(56px, 8vw, 120px)" }}>
              Projects.<br/><em>Honestly categorised.</em>
            </h1>
          </div>
          <div className="rhs">
            <p className="t-lede">
              The official MAG site mixes current launches, Keturah, and completed/legacy assets under one nav. Here, each is filterable. Marriott Residences retained as an asset but kept off the current-launch list until the public status is confirmed.
            </p>
          </div>
        </div>

        <div className="filter-bar" style={{ marginBottom: 56 }}>
          {filters.map(f => (
            <button key={f.id} className={`filter-pill ${filter === f.id ? "is-on" : ""}`} onClick={() => setFilter(f.id)}>
              {f.label} <span className="ct">{String(counts[f.id]).padStart(2,"0")}</span>
            </button>
          ))}
        </div>

        <div className="proj-grid">
          {items.map((p, i) => {
            // Vary spans for visual rhythm
            let span = "span-4";
            if (filter !== "completed") {
              if (i % 7 === 0) span = "span-7";
              else if (i % 7 === 1) span = "span-5";
              else if (i % 5 === 0) span = "span-6";
            }
            if (p.cat === "completed" && !p.img) {
              // text-only legacy card
              return (
                <div key={p.slug} className="span-4" style={{ display: "flex", flexDirection: "column", gap: 12, padding: "32px 24px", border: "1px solid var(--border)", background: "var(--bg-deep)", minHeight: 240 }}>
                  <div className="t-mono">{String(i+1).padStart(2,"0")} · Completed</div>
                  <div className="t-display" style={{ fontSize: 26 }}>{p.name}</div>
                  <div className="t-small">{p.location}</div>
                  <div className="t-mono" style={{ marginTop: "auto", color: "var(--muted-2)" }}>Render not in pack</div>
                </div>
              );
            }
            return <ProjectCard key={p.slug} p={p} idx={i+1} className={span} onClick={() => go(`microsite:${p.slug}`)} />;
          })}
        </div>
      </section>
    </div>
  );
}

/* ----------------------------------------------------------------
   Microsite view
   ---------------------------------------------------------------- */
function Microsite({ slug, go, onRegister, onBrochure, onViewing, showCoords }) {
  const p = projectBySlug(slug);
  const [activeSection, setActiveSection] = useState("story");
  const [galleryIdx, setGalleryIdx] = useState(0);
  const trackRef = useRef(null);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "auto" });
    setGalleryIdx(0);
  }, [slug]);

  if (!p) {
    return (
      <div style={{ paddingTop: 200, textAlign: "center" }}>
        <h2 className="t-display t-h2">Project not found</h2>
        <button className="btn btn-ghost" onClick={() => go("home")}>Return home {I.arr()}</button>
      </div>
    );
  }

  const isKeturah = p.cat === "keturah";
  const gallery = (p.gallery && p.gallery.length ? p.gallery : [safeImg(p)]);

  const scrollGallery = (dir) => {
    setGalleryIdx(i => Math.max(0, Math.min(gallery.length - 1, i + dir)));
  };

  return (
    <div className="page-enter">
      {/* HERO */}
      <section className="ms-hero" style={{ backgroundImage: `url(${safeImg(p)})` }}>
        <div className="ms-hero-inner">
          <div>
            <div className="crumb">
              <button onClick={() => go("home")} style={{ color: "inherit", opacity: 0.8 }}>MAG</button> /{" "}
              <button onClick={() => go(`projects:${p.cat}`)} style={{ color: "inherit", opacity: 0.8 }}>
                {p.cat === "keturah" ? "Keturah" : p.cat === "current" ? "Current" : "Completed"}
              </button>{" "}/ <span style={{ opacity: 0.6 }}>{p.name}</span>
            </div>
            <h1>
              {p.name.includes("Ritz-Carlton") ? (
                <>The Ritz-Carlton<br /><em>Residences, Creekside.</em></>
              ) : p.name.startsWith("Keturah") ? (
                <>{p.name.split(" ")[0]} <em>{p.name.split(" ").slice(1).join(" ")}</em></>
              ) : (
                <>{p.name}</>
              )}
            </h1>
            <p className="sub">{p.summary || p.tagline}</p>
            {p.rights && (
              <p className="t-mono" style={{ color: "rgba(255,255,255,0.7)", maxWidth: "62ch" }}>
                ⚠ {p.rights}
              </p>
            )}
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 24 }}>
              <button className="btn btn-coral" onClick={onRegister}>Register interest {I.arr()}</button>
              <button className="btn btn-ghost-light" onClick={onBrochure}>Download brochure {I.download({style:{marginLeft:4}})}</button>
              <button className="btn btn-ghost-light" onClick={onViewing}>Book private viewing {I.arr()}</button>
            </div>
          </div>

          <div>
            <div className="facts">
              {(p.facts || []).slice(0, 4).map((f, i) => (
                <div key={i}>
                  <div className="k">{f.k}</div>
                  <div className="v">
                    {f.v}
                    {f.confirm && <span className="confirm">CONFIRM</span>}
                  </div>
                </div>
              ))}
            </div>
            {showCoords && (
              <div style={{ marginTop: 20, fontFamily: "var(--font-mono)", fontSize: 11, color: "rgba(255,255,255,0.7)", letterSpacing: "0.08em" }}>
                {p.coord || "—"} · {p.location || "Dubai"}
              </div>
            )}
          </div>
        </div>
      </section>

      {/* SUBNAV */}
      <nav className="ms-subnav">
        <div className="items">
          {MS_SECTIONS.map(s => (
            <button
              key={s.id}
              className={s.id === activeSection ? "is-on" : ""}
              onClick={() => {
                setActiveSection(s.id);
                document.getElementById(`ms-${s.id}`)?.scrollIntoView({ block: "start", behavior: "smooth" });
              }}
            >
              {s.label}
            </button>
          ))}
        </div>
        <button className="btn btn-sm btn-coral" onClick={onRegister}>
          Enquire {I.arr()}
        </button>
      </nav>

      {/* STORY */}
      <section className="section wrap" id="ms-story">
        <div className="story">
          <div className="img-col">
            <img src={gallery[1] || gallery[0]} alt={`${p.name} interior render`} loading="lazy" />
          </div>
          <div className="copy-col">
            <span className="kicker"><span className="sq" />01 / Story</span>
            <h2 className="t-display t-h2" style={{ maxWidth: "16ch" }}>
              {isKeturah ? <>Bio Living,<br/><em>practiced daily.</em></> : <>A neighborhood,<br/><em>not a tower.</em></>}
            </h2>
            <p className="t-lede">{p.summary}</p>

            <div className="pillars">
              {(p.pillars || [
                { n: "01", h: "Architecture led by light", b: "Floor plates and orientations tuned for daylight and cross-ventilation, not just plan efficiency." },
                { n: "02", h: "Public realm first", b: "Landscape, water, and walking circuits programmed before the building footprint is fixed." },
                { n: "03", h: "Resident-grade specification", b: "Material specifications tuned for the long stay — not the photoshoot." },
              ]).map(pl => (
                <div key={pl.n} className="pillar">
                  <div className="n">{pl.n}</div>
                  <div>
                    <div className="h">{pl.h}</div>
                    <div className="b">{pl.b}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* LOCATION */}
      <section className="section wrap" id="ms-location" style={{ background: "var(--bg-deep)", marginInline: `calc(-1 * var(--pad-x))`, paddingInline: "var(--pad-x)" }}>
        <div className="section-head">
          <div className="lhs">
            <span className="kicker"><span className="sq" />02 / Location</span>
            <h2 className="t-display t-h2"><em>Where</em> it is.</h2>
          </div>
          <div className="rhs">
            <p className="t-lede">
              {p.location}.{showCoords && <span className="t-mono" style={{ marginLeft: 10, fontSize: 12 }}>{p.coord}</span>}
            </p>
          </div>
        </div>
        <div className="loc">
          <div className="loc-map">
            <svg viewBox="0 0 500 400" preserveAspectRatio="none">
              <defs>
                <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                  <path d="M 40 0 L 0 0 0 40" fill="none" stroke="rgba(23,20,18,0.06)" strokeWidth="1"/>
                </pattern>
              </defs>
              <rect width="500" height="400" fill="url(#grid)" />
              {/* abstract roads */}
              <path d="M0 280 Q150 200 320 240 T 500 200" stroke="rgba(23,20,18,0.18)" strokeWidth="2" fill="none"/>
              <path d="M120 0 Q160 150 200 220 T 280 400" stroke="rgba(23,20,18,0.15)" strokeWidth="1.5" fill="none"/>
              <path d="M0 80 L 500 120" stroke="rgba(23,20,18,0.12)" strokeWidth="1" fill="none"/>
              {/* water */}
              <path d="M340 360 Q400 320 480 360 L 500 400 L 320 400 Z" fill="rgba(35,58,74,0.18)"/>
              <text x="420" y="385" fontFamily="var(--font-mono)" fontSize="10" fill="rgba(23,20,18,0.4)" letterSpacing="2">CREEK</text>
            </svg>
            <div className="loc-pin" style={{ left: "58%", top: "44%" }}>
              <span className="lbl">{p.name}</span>
            </div>
          </div>
          <div className="loc-list">
            {LOC_CONTEXT.map((c, i) => (
              <div className="row" key={i}>
                <span className="k">{c.k}</span>
                <span className="v">{c.v} {c.confirm && <span className="confirm-tag">CONFIRM</span>}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* RESIDENCES / CONCEPTS */}
      <section className="section wrap" id="ms-residences">
        <div className="section-head">
          <div className="lhs">
            <span className="kicker"><span className="sq" />03 / Residences</span>
            <h2 className="t-display t-h2">Residence concepts.</h2>
          </div>
          <div className="rhs">
            <p className="t-lede">
              Floor plans, sizes, and unit counts are intentionally not displayed here — they require client and RERA-confirmed source files. Concepts below describe the programme.
              <span className="confirm-tag">PLANS NOT PUBLISHED</span>
            </p>
          </div>
        </div>
        <div className="unit-grid">
          {(isKeturah ? [
            { ix: "Type · 01", ttl: "Reserve residence", desc: "Bio-living apartment formats with private gardens and shaded outdoor rooms.", k: "Configuration", v: "Programme TBC" },
            { ix: "Type · 02", ttl: "Townhouse", desc: "Stacked plot-based townhouses with a private courtyard and roof terrace per home.", k: "Configuration", v: "Programme TBC" },
            { ix: "Type · 03", ttl: "Villa plot", desc: "Plot purchases with bio-living masterplan guidelines and architectural reviewers.", k: "Configuration", v: "Programme TBC" },
          ] : [
            { ix: "Type · 01", ttl: "Studio / 1 bed", desc: "Compact residence formats tuned for solo and couple residents.", k: "Configuration", v: "Plans on enquiry" },
            { ix: "Type · 02", ttl: "2 bed", desc: "Family-scale floor plans with separated living and sleeping wings.", k: "Configuration", v: "Plans on enquiry" },
            { ix: "Type · 03", ttl: "3 bed / penthouse", desc: "Upper-floor formats with extended balconies and city-facing exposures.", k: "Configuration", v: "Plans on enquiry" },
          ]).map((u, i) => (
            <div key={i} className="unit-card">
              <div className="ix">{u.ix}</div>
              <div className="ttl">{u.ttl}</div>
              <div className="desc">{u.desc}</div>
              <div className="meta-row">
                <div>
                  <div className="k">{u.k}</div>
                  <div className="v">{u.v}<span className="conf-mini">CONFIRM</span></div>
                </div>
                <div>
                  <div className="k">Pricing</div>
                  <div className="v">On application</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* AMENITIES */}
      <section className="section wrap" id="ms-amenities">
        <div className="section-head">
          <div className="lhs">
            <span className="kicker"><span className="sq" />04 / Amenities</span>
            <h2 className="t-display t-h2">{isKeturah ? <>Wellness, <em>scripted in.</em></> : <>Amenities <em>specified.</em></>}</h2>
          </div>
          <div className="rhs">
            <p className="t-lede">
              Amenity programmes are listed from confirmed sources only. Specifics like spa operator, restaurant brand, and certification partners remain to be confirmed per project.
            </p>
          </div>
        </div>
        <div className="amenity-grid">
          {KETURAH_AMENITIES.map((a, i) => (
            <div className="amenity" key={i}>
              <span className="n">{String(i+1).padStart(2,"0")}</span>
              <div>
                <div className="ttl">{a.ttl}</div>
                <div className="sub">{a.sub}</div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* GALLERY */}
      <section id="ms-gallery">
        <div className="gallery">
          <div className="gallery-controls">
            <div>
              <div className="kicker is-light"><span className="sq" />05 / Gallery</div>
              <div className="t-mono" style={{ color: "rgba(255,255,255,0.5)", marginTop: 6 }}>
                Renders are official MAG assets; status to be confirmed per render.
              </div>
            </div>
            <div className="row" style={{ gap: 16 }}>
              <span className="gallery-counter">{String(galleryIdx+1).padStart(2,"0")} / {String(gallery.length).padStart(2,"0")}</span>
              <button className="gallery-btn" onClick={() => scrollGallery(-1)} disabled={galleryIdx === 0} aria-label="Previous">{I.arrL()}</button>
              <button className="gallery-btn" onClick={() => scrollGallery(1)} disabled={galleryIdx === gallery.length - 1} aria-label="Next">{I.arr()}</button>
            </div>
          </div>
          <div className="gallery-track" ref={trackRef} style={{ transform: `translateX(calc(${-galleryIdx} * (min(72vw, 880px) + 16px)))` }}>
            {gallery.map((g, i) => (
              <div className="gallery-slide" key={i}>
                <img src={g} alt={`${p.name} render ${i+1}`} loading="lazy" />
                <span className="caption">{p.name} · 0{i+1}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ENQUIRE CTA */}
      <section id="ms-enquire" className="cta-block" style={{ "--cta-bg": `url(${safeImg(p)})` }}>
        <div className="cta-inner">
          <div>
            <span className="kicker is-light"><span className="sq" />06 / Enquire</span>
            <h2 className="t-display t-h2" style={{ marginTop: 16 }}>
              Make {p.name}<br/><em>the next address.</em>
            </h2>
            <p className="t-lede" style={{ color: "rgba(255,255,255,0.8)", marginTop: 16, maxWidth: "48ch" }}>
              Register your interest, gate a brochure, or book a private viewing.  Every form is project-scoped — leads route to the correct CRM segment with project + locale + source attached.
            </p>
          </div>
          <div className="cta-actions">
            <button className="btn btn-coral btn-lg" onClick={onRegister}>Register interest {I.arr()}</button>
            <button className="btn btn-ghost-light btn-lg" onClick={onBrochure}>Brochure {I.download({style:{marginLeft:6}})}</button>
            <button className="btn btn-ghost-light btn-lg" onClick={onViewing}>Private viewing {I.arr()}</button>
            <a className="btn btn-ghost-light btn-lg" href="https://api.whatsapp.com/send?phone=97143555580" target="_blank" rel="noreferrer">WhatsApp {I.whatsapp({style:{marginLeft:6}})}</a>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ----------------------------------------------------------------
   Modals
   ---------------------------------------------------------------- */
function Modal({ children, onClose }) {
  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);
  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <button className="sheet-close" onClick={onClose} aria-label="Close">{I.close()}</button>
        {children}
      </div>
    </div>
  );
}

function useForm(initial) {
  const [v, setV] = useState(initial);
  const [errs, setErrs] = useState({});
  const update = (k) => (e) => setV({ ...v, [k]: e.target.value });
  return { v, setV, errs, setErrs, update };
}

function RegisterInterestModal({ onClose, project }) {
  const { v, errs, setErrs, update } = useForm({ name: "", email: "", phone: "", project: project || "", market: "UAE", note: "" });
  const [sent, setSent] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!v.name.trim()) er.name = "Please share your name.";
    if (!v.email.match(/^\S+@\S+\.\S+$/)) er.email = "Enter a valid email.";
    if (!v.phone.trim()) er.phone = "Phone or WhatsApp helps us route faster.";
    setErrs(er);
    if (Object.keys(er).length) return;
    setSent(true);
  };
  if (sent) {
    return (
      <Modal onClose={onClose}>
        <div className="success-state">
          <div className="check">{I.check()}</div>
          <h4>Registered. Thank you.</h4>
          <p>Our investor relations team will reach out within one business day. A confirmation has been sent to <strong>{v.email}</strong>.</p>
          <div className="t-mono" style={{ color: "var(--muted-2)" }}>CRM event: register_interest · project={v.project || "general"} · market={v.market}</div>
          <button className="btn btn-ghost" onClick={onClose} style={{ marginTop: 8 }}>Close</button>
        </div>
      </Modal>
    );
  }
  return (
    <Modal onClose={onClose}>
      <div className="sheet-head">
        <div className="eyebrow">CRM · register_interest</div>
        <h3>Register interest</h3>
        <p>Get project briefs, payment-plan summaries, and a personal introduction to our investor relations desk.</p>
      </div>
      <form className="sheet-body" onSubmit={submit}>
        <div className="field-row">
          <div className="field">
            <label>Full name</label>
            <input value={v.name} onChange={update("name")} placeholder="—" />
            {errs.name && <span className="err">{errs.name}</span>}
          </div>
          <div className="field">
            <label>Email</label>
            <input type="email" value={v.email} onChange={update("email")} placeholder="—" />
            {errs.email && <span className="err">{errs.email}</span>}
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label>Phone / WhatsApp</label>
            <input value={v.phone} onChange={update("phone")} placeholder="+971 …" />
            {errs.phone && <span className="err">{errs.phone}</span>}
          </div>
          <div className="field">
            <label>Investor market</label>
            <select value={v.market} onChange={update("market")}>
              <option>UAE</option><option>GCC</option><option>India</option><option>UK / EU</option>
              <option>Russia / CIS</option><option>China / SEA</option><option>Other</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label>Project of interest</label>
          <select value={v.project} onChange={update("project")}>
            <option value="">— Any project / portfolio overview</option>
            {PROJECTS.filter(p=>p.cat!=="completed").map(p => (
              <option key={p.slug} value={p.slug}>{p.name}</option>
            ))}
          </select>
        </div>
        <div className="field">
          <label>Note (optional)</label>
          <textarea rows="3" value={v.note} onChange={update("note")} placeholder="Bedrooms, view, payment-plan preferences…"></textarea>
        </div>
        <div className="checkbox-row">
          <input type="checkbox" defaultChecked id="optin" />
          <label htmlFor="optin">I'd like updates from MAG and Keturah. We never share contact details with third parties.</label>
        </div>
        <input type="text" tabIndex="-1" autoComplete="off" style={{ display: "none" }} aria-hidden /> {/* honeypot */}
        <div className="sheet-foot" style={{ padding: 0, marginTop: 16 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" type="submit">Submit {I.arr()}</button>
        </div>
      </form>
    </Modal>
  );
}

function BrochureGateModal({ onClose, project }) {
  const p = projectBySlug(project) || PROJECTS[0];
  const { v, errs, setErrs, update } = useForm({ name: "", email: "", phone: "" });
  const [sent, setSent] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!v.name.trim()) er.name = "Required.";
    if (!v.email.match(/^\S+@\S+\.\S+$/)) er.email = "Valid email required.";
    setErrs(er);
    if (Object.keys(er).length) return;
    setSent(true);
  };
  if (sent) {
    return (
      <Modal onClose={onClose}>
        <div className="success-state">
          <div className="check">{I.check()}</div>
          <h4>Brochure on its way.</h4>
          <p>{p.name} brochure sent to <strong>{v.email}</strong>. Investor relations is copied.</p>
          <div className="t-mono" style={{ color: "var(--muted-2)" }}>CRM event: brochure_gate · project={p.slug}</div>
          <button className="btn btn-ghost" onClick={onClose} style={{ marginTop: 8 }}>Close</button>
        </div>
      </Modal>
    );
  }
  return (
    <Modal onClose={onClose}>
      <div className="sheet-head">
        <div className="eyebrow">CRM · brochure_gate</div>
        <h3>Download the brochure</h3>
        <p>Gated PDFs are sent on request. Final brochure assets are still client-supplied.</p>
      </div>
      <div style={{ padding: "0 40px" }}>
        <div className="brochure-card">
          <div className="preview" style={{ backgroundImage: `url(${safeImg(p)})` }} />
          <div className="info">
            <div className="meta">{p.cat === "keturah" ? "Keturah" : p.cat === "current" ? "Current" : "Completed"}</div>
            <div className="ttl">{p.name}</div>
            <div className="desc">{p.tagline || p.summary}</div>
            <div className="t-mono" style={{ marginTop: 6, color: "var(--accent)" }}>PDF — client-supplied <span className="confirm-tag">CONFIRM</span></div>
          </div>
        </div>
      </div>
      <form className="sheet-body" onSubmit={submit}>
        <div className="field-row">
          <div className="field">
            <label>Full name</label>
            <input value={v.name} onChange={update("name")} />
            {errs.name && <span className="err">{errs.name}</span>}
          </div>
          <div className="field">
            <label>Email</label>
            <input type="email" value={v.email} onChange={update("email")} />
            {errs.email && <span className="err">{errs.email}</span>}
          </div>
        </div>
        <div className="field">
          <label>Phone / WhatsApp (optional)</label>
          <input value={v.phone} onChange={update("phone")} placeholder="+971 …" />
        </div>
        <div className="sheet-foot" style={{ padding: 0, marginTop: 8 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
          <button type="submit" className="btn btn-primary">Send brochure {I.download({style:{marginLeft:6}})}</button>
        </div>
      </form>
    </Modal>
  );
}

function PrivateViewingModal({ onClose }) {
  const { v, errs, setErrs, update } = useForm({ name: "", email: "", phone: "", project: "", date: "", time: "morning", channel: "in-person" });
  const [sent, setSent] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!v.name.trim()) er.name = "Required.";
    if (!v.email.match(/^\S+@\S+\.\S+$/)) er.email = "Valid email required.";
    if (!v.phone.trim()) er.phone = "Required for confirmation.";
    if (!v.date) er.date = "Pick a preferred date.";
    setErrs(er);
    if (Object.keys(er).length) return;
    setSent(true);
  };
  if (sent) {
    return (
      <Modal onClose={onClose}>
        <div className="success-state">
          <div className="check">{I.check()}</div>
          <h4>Viewing requested.</h4>
          <p>A relationship manager will confirm <strong>{v.date}</strong> ({v.time}) via {v.channel === "in-person" ? "in-person" : v.channel} within one business day.</p>
          <div className="t-mono" style={{ color: "var(--muted-2)" }}>CRM event: private_viewing · {v.project || "general"}</div>
          <button className="btn btn-ghost" onClick={onClose} style={{ marginTop: 8 }}>Close</button>
        </div>
      </Modal>
    );
  }
  return (
    <Modal onClose={onClose}>
      <div className="sheet-head">
        <div className="eyebrow">CRM · private_viewing</div>
        <h3>Book a private viewing</h3>
        <p>In-person at the sales gallery, on-site at the development, or virtual via private video call.</p>
      </div>
      <form className="sheet-body" onSubmit={submit}>
        <div className="field-row">
          <div className="field">
            <label>Full name</label>
            <input value={v.name} onChange={update("name")} />
            {errs.name && <span className="err">{errs.name}</span>}
          </div>
          <div className="field">
            <label>Email</label>
            <input type="email" value={v.email} onChange={update("email")} />
            {errs.email && <span className="err">{errs.email}</span>}
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label>Phone / WhatsApp</label>
            <input value={v.phone} onChange={update("phone")} placeholder="+971 …" />
            {errs.phone && <span className="err">{errs.phone}</span>}
          </div>
          <div className="field">
            <label>Project</label>
            <select value={v.project} onChange={update("project")}>
              <option value="">— Any current launch</option>
              {PROJECTS.filter(p=>p.cat!=="completed").map(p => (
                <option key={p.slug} value={p.slug}>{p.name}</option>
              ))}
            </select>
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label>Preferred date</label>
            <input type="date" value={v.date} onChange={update("date")} />
            {errs.date && <span className="err">{errs.date}</span>}
          </div>
          <div className="field">
            <label>Time</label>
            <select value={v.time} onChange={update("time")}>
              <option value="morning">Morning</option>
              <option value="afternoon">Afternoon</option>
              <option value="evening">Evening</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label>Channel</label>
          <select value={v.channel} onChange={update("channel")}>
            <option value="in-person">In-person — DIFC sales gallery</option>
            <option value="on-site">On-site at development</option>
            <option value="virtual">Virtual — private video call</option>
          </select>
        </div>
        <div className="sheet-foot" style={{ padding: 0, marginTop: 8 }}>
          <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
          <button type="submit" className="btn btn-primary">Request viewing {I.arr()}</button>
        </div>
      </form>
    </Modal>
  );
}

/* ----------------------------------------------------------------
   Why MAG dedicated view + Brokers + Contact full pages
   ---------------------------------------------------------------- */
function WhyMagView({ go }) {
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section wrap">
        <div className="section-head">
          <div className="lhs">
            <span className="kicker"><span className="sq" />Why MAG</span>
            <h1 className="t-display t-h1" style={{ fontSize: "clamp(56px, 8vw, 120px)" }}>
              Forty-eight years <br/><em>of group legacy.</em>
            </h1>
          </div>
          <div className="rhs">
            <p className="t-lede">
              MAG Group originated in 1978. The real-estate arm — MAG Lifestyle Development — is commonly described as established in 2003. Treat group legacy and the arm's founding as distinct. <span className="confirm-tag">company-attributed</span>
            </p>
          </div>
        </div>
      </section>
      <WhyMag />
    </div>
  );
}

function BrokersView({ onRegister }) {
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <section className="section wrap">
        <div className="section-head">
          <div className="lhs">
            <span className="kicker"><span className="sq" />Brokers</span>
            <h1 className="t-display t-h1" style={{ fontSize: "clamp(56px, 8vw, 120px)" }}>
              For agents,<br/><em>not against them.</em>
            </h1>
          </div>
          <div className="rhs">
            <p className="t-lede">
              MAG works with a registered broker network across the UAE and internationally. The official site exposes a brokers channel today; we propose deeper agent enablement: gated factsheets, co-branded materials, commission tracking, and event invites.
            </p>
          </div>
        </div>

        <div className="grid" style={{ gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }}>
          {[
            { ttl: "Gated broker portal", d: "Factsheets, floor plates (where confirmed), and brochures behind a single login." },
            { ttl: "Co-branded marketing", d: "Approved imagery, brand-safe co-branded templates, and right-of-use timelines." },
            { ttl: "Commission tracking", d: "Lead deduplication, deal pipeline, and commission status visible to your agency." },
          ].map((c, i) => (
            <div key={i} className="bro-card">
              <div className="t-mono" style={{ color: "var(--secondary)" }}>{String(i+1).padStart(2,"0")}</div>
              <div className="ttl">{c.ttl}</div>
              <div className="sub">{c.d}</div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 56, padding: 32, border: "1px solid var(--border)", background: "var(--surface)" }}>
          <div className="row-between">
            <div>
              <div className="t-mono" style={{ color: "var(--muted)" }}>Broker enquiry</div>
              <div className="t-display" style={{ fontSize: 28, marginTop: 6, fontWeight: 400 }}>Apply for the broker channel</div>
            </div>
            <button className="btn btn-primary" onClick={onRegister}>Broker enquiry {I.arr()}</button>
          </div>
        </div>
      </section>
    </div>
  );
}

function ContactView({ onRegister, onViewing }) {
  return (
    <div className="page-enter" style={{ paddingTop: 120 }}>
      <ContactSection onRegister={onRegister} onViewing={onViewing} />
    </div>
  );
}

/* ----------------------------------------------------------------
   Home view
   ---------------------------------------------------------------- */
function HomeView({ go, locale, onRegister, onBrochure, onViewing, heroVariant, showCoords }) {
  return (
    <>
      <Hero locale={locale} go={go} onRegister={onRegister} heroVariant={heroVariant} showCoords={showCoords} />
      <CurrentProjectsRibbon go={go} locale={locale} />
      <KeturahSpotlight go={go} />
      <WhyMag />
      <LegacyStrip go={go} locale={locale} />
      <ContactSection onRegister={onRegister} onViewing={onViewing} />
    </>
  );
}

/* ----------------------------------------------------------------
   WhatsApp FAB
   ---------------------------------------------------------------- */
function WhatsAppFab() {
  return (
    <a className="fab" href="https://api.whatsapp.com/send?phone=97143555580" target="_blank" rel="noreferrer" aria-label="WhatsApp">
      <span className="wa">{I.whatsapp()}</span>
      <span>WhatsApp</span>
    </a>
  );
}

/* ----------------------------------------------------------------
   App root
   ---------------------------------------------------------------- */
function App() {
  const [view, setView] = useState("home");
  const [locale, setLocale] = useState("en");
  const [modal, setModal] = useState(null); // { kind, project }
  const [tweaks, setTweak] = useTweaks(window.__MAG_TWEAK_DEFAULTS__);

  // Apply tweaks to <html>/<body>
  useEffect(() => {
    document.documentElement.setAttribute("data-palette", tweaks.palette || "biophilic");
    document.documentElement.setAttribute("data-display", tweaks.displayFont || "cormorant");
    document.documentElement.setAttribute("data-density", tweaks.density || "comfortable");
    document.documentElement.setAttribute("data-rtl", LOCALES[locale].dir === "rtl" ? "1" : "0");
  }, [tweaks, locale]);

  const go = useCallback((next) => {
    setView(next);
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);
  const openModal = (kind, project) => setModal({ kind, project });
  const closeModal = () => setModal(null);

  // Derive view payload
  let body = null;
  if (view === "home") {
    body = <HomeView go={go} locale={locale}
      onRegister={() => openModal("register")}
      onBrochure={(p) => openModal("brochure", p)}
      onViewing={() => openModal("viewing")}
      heroVariant={tweaks.heroVariant}
      showCoords={tweaks.showCoordinates}
    />;
  } else if (view.startsWith("projects:")) {
    const cat = view.split(":")[1];
    body = <ProjectsView go={go} initialFilter={cat === "all" ? "all" : cat} />;
  } else if (view.startsWith("microsite:")) {
    const slug = view.split(":")[1];
    body = <Microsite
      slug={slug}
      go={go}
      onRegister={() => openModal("register", slug)}
      onBrochure={() => openModal("brochure", slug)}
      onViewing={() => openModal("viewing", slug)}
      showCoords={tweaks.showCoordinates}
    />;
  } else if (view === "why-mag") {
    body = <WhyMagView go={go} />;
  } else if (view === "brokers") {
    body = <BrokersView onRegister={() => openModal("register")} />;
  } else if (view === "contact") {
    body = <ContactView onRegister={() => openModal("register")} onViewing={() => openModal("viewing")} />;
  }

  return (
    <>
      <TopNav
        view={view}
        locale={locale}
        setLocale={setLocale}
        go={go}
        onRegister={() => openModal("register")}
        onBrochure={(p) => openModal("brochure", p)}
      />
      <main>{body}</main>
      {view !== "home" && view !== "contact" && (
        <></> // (Footer rendered in home etc. below — but we want it on every view)
      )}
      <Footer go={go} />
      <WhatsAppFab />

      {modal && modal.kind === "register" && <RegisterInterestModal onClose={closeModal} project={modal.project} />}
      {modal && modal.kind === "brochure" && <BrochureGateModal onClose={closeModal} project={modal.project} />}
      {modal && modal.kind === "viewing" && <PrivateViewingModal onClose={closeModal} />}

      {/* Tweaks panel */}
      <TweaksPanel title="MAG · Tweaks">
        <TweakSection label="Palette" />
        <TweakRadio
          label="Palette"
          value={tweaks.palette}
          options={["biophilic", "warm-bronze", "creek-stone"]}
          onChange={(v) => setTweak("palette", v)}
        />
        <TweakSection label="Type" />
        <TweakSelect
          label="Display font"
          value={tweaks.displayFont}
          options={[
            { value: "cormorant", label: "Cormorant Garamond" },
            { value: "marcellus", label: "Marcellus" },
            { value: "dm-serif", label: "DM Serif Display" },
            { value: "geist", label: "Geist (Sans)" },
          ]}
          onChange={(v) => setTweak("displayFont", v)}
        />
        <TweakRadio
          label="Density"
          value={tweaks.density}
          options={["comfortable", "compact"]}
          onChange={(v) => setTweak("density", v)}
        />
        <TweakSection label="Page chrome" />
        <TweakToggle
          label="Show coordinates"
          value={tweaks.showCoordinates}
          onChange={(v) => setTweak("showCoordinates", v)}
        />
        <TweakSection label="Hero" />
        <TweakSelect
          label="Hero subject"
          value={tweaks.heroVariant}
          options={[
            { value: "ritz", label: "Ritz-Carlton Creekside" },
            { value: "creekside", label: "Creekside interior" },
            { value: "keturah", label: "Keturah Reserve" },
            { value: "777", label: "MAG 777" },
          ]}
          onChange={(v) => setTweak("heroVariant", v)}
        />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
