/* Microsite shell: topbar, hero, story, architecture, residences,
   amenities, location, gallery, connect, footer, sticky dock,
   gallery lightbox. All copy & data come from data.js. */

const { useState: useS, useEffect: useE, useRef, useMemo: useM, useCallback: useCb } = React;

// ============ TOPBAR ============
function TopBar({ project, locale, setLocale, activeChapter, onCTA, onProjectSwitch }) {
  const [solid, setSolid] = useS(false);
  const L = LOCALES[locale];
  useE(() => {
    const onScroll = () => setSolid(window.scrollY > 80);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const chapters = [
    { id: "story", label: L.nav.story },
    { id: "architecture", label: L.nav.architecture },
    { id: "residences", label: L.nav.residences },
    { id: "amenities", label: L.nav.amenities },
    { id: "location", label: L.nav.location },
    { id: "gallery", label: L.nav.gallery },
  ];

  return (
    <header className={`topbar ${solid ? "solid" : ""}`}>
      <div className="brand" onClick={onProjectSwitch} style={{ cursor: "pointer" }}>
        <Wordmark />
      </div>
      <div className="divider" />
      <div className="crumb">
        <b>{project.name}</b> <span style={{ opacity: .5, margin: "0 8px" }}>·</span> {project.district.split("·")[0].trim()}
      </div>

      <div className="spacer" />

      <nav className="chapters">
        {chapters.map(c => (
          <a key={c.id} href={`#${c.id}`} className={activeChapter === c.id ? "active" : ""}>{c.label}</a>
        ))}
      </nav>

      <div className="actions">
        <div className="locale-switch">
          {["en", "ar", "ru", "zh"].map(l => (
            <button key={l} className={locale === l ? "active" : ""} onClick={() => setLocale(l)}>{l.toUpperCase()}</button>
          ))}
        </div>
        <a className="wa-pill" href="https://wa.me/97180015" target="_blank" rel="noreferrer" title="WhatsApp">
          <span className="wa-ic"><WhatsAppGlyph /></span>
          <span className="wa-label">800 15</span>
        </a>
        <button className="btn primary" onClick={() => onCTA("register")}>{L.cta.register} <span className="arrow"/></button>
      </div>
    </header>
  );
}

function Wordmark() {
  // Reproduce the wordmark via the provided SVG file as an <img>.
  return <img className="wordmark" src="media/logo-binghatti.svg" alt="Binghatti" />;
}

function WhatsAppGlyph() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M20.52 3.48A11.94 11.94 0 0 0 3.48 20.52L2 22l1.62-1.4A11.94 11.94 0 0 0 20.52 3.48zM12 21.27a9.27 9.27 0 0 1-4.74-1.3l-.34-.2-2.55.66.67-2.49-.22-.36A9.27 9.27 0 1 1 12 21.27zm5.2-6.95c-.28-.14-1.65-.81-1.9-.9-.26-.1-.45-.14-.64.14-.19.28-.74.9-.9 1.08-.17.18-.33.2-.61.07-.28-.14-1.17-.43-2.23-1.37-.83-.74-1.38-1.65-1.54-1.93-.16-.28-.02-.43.12-.57.13-.13.28-.33.42-.5.14-.16.19-.28.28-.47.09-.18.05-.35-.02-.5-.07-.14-.64-1.54-.88-2.1-.23-.55-.46-.48-.64-.49l-.55-.01c-.18 0-.47.07-.72.34-.25.28-.95.93-.95 2.26 0 1.33.97 2.62 1.1 2.8.14.18 1.92 2.93 4.65 4.11.65.28 1.16.45 1.56.58.65.21 1.25.18 1.72.11.52-.08 1.65-.67 1.88-1.32.23-.65.23-1.21.16-1.33-.07-.12-.25-.18-.53-.32z"/></svg>
  );
}

// ============ HERO ============
function Hero({ project, locale, onCTA }) {
  const L = LOCALES[locale];
  const [loaded, setLoaded] = useS(false);
  useE(() => { setLoaded(false); requestAnimationFrame(() => setLoaded(true)); }, [project.id]);

  const today = new Date().toLocaleDateString(locale === "ar" ? "ar-AE" : locale, { year: "numeric", month: "short", day: "numeric" });

  return (
    <section className="hero" id="top">
      <div className={`hero-bg ${loaded ? "kenburns" : ""}`} style={{ backgroundImage: `url(${project.image})`, opacity: loaded ? 1 : 0 }} />
      <div className="hero-grid">
        <div className="hero-meta">
          <div className="eyebrow"><span className="dot"/>{project.type === "branded" ? "Branded residence" : "Signature collection"}</div>
          <h1 className="display">
            {project.name.split(" ").map((w, i, arr) => i === arr.length - 1 ? <em key={i}>{w}</em> : <span key={i}>{w} </span>)}
          </h1>
          <div className="hero-sub">{project.tagline}</div>
        </div>
        <div className="hero-right">
          <div className="hero-tags">
            {project.tags.map(t => <span key={t} className={t.toLowerCase().includes("branded") ? "accent" : ""}>{t}</span>)}
          </div>
          <div className="hero-cta">
            <button className="btn solid" style={{ background: "#fff", color: "var(--text)", borderColor: "#fff" }} onClick={() => onCTA("register")}>
              {L.cta.register} <span className="arrow"/>
            </button>
            <button className="btn btn-ghost" onClick={() => onCTA("brochure")}>{L.cta.brochure}</button>
          </div>
        </div>
      </div>

      <div className="scroll-cue">
        <span>{L.hero.scroll}</span>
        <div className="line" />
      </div>

      <div className="ribbon">
        <div className="cell"><span>Status</span><b className="live">{L.hero.live}</b></div>
        <div className="cell"><span>District</span><b>{project.district.split("·")[0].trim()}</b></div>
        <div className="cell"><span>Developer</span><b>Binghatti Developers</b></div>
        <div className="cell"><span>Date</span><b>{today}</b></div>
        <div style={{ flex: 1 }}/>
        <div className="cell" style={{ textAlign: "end" }}><span>Microsite ref</span><b>BG-{project.id.toUpperCase()}-2026</b></div>
      </div>
    </section>
  );
}

// ============ STORY ============
function StorySection({ project, locale }) {
  const L = LOCALES[locale];
  return (
    <section id="story" className="wrap">
      <div className="section-head fade-in">
        <div className="label">
          <div className="num">{L.chapter.num01}</div>
          <div className="eyebrow"><span className="dot"/>Developer</div>
        </div>
        <div>
          <h2 className="display">{L.story.title}</h2>
          <div className="lede">{L.story.lede}</div>
        </div>
      </div>
      <div className="story-grid fade-in">
        <div className="label-col">
          {Object.entries(L.story.meta).map(([k, v]) => (
            <div className="row" key={k}>
              <span>{v[0]}</span>
              <b>{v[1]}</b>
            </div>
          ))}
          <div className="row"><span style={{ color: "var(--accent)" }}>Source attribution</span><b>{L.hero.attribOfficial}</b></div>
        </div>
        <div className="copy">
          <p>{L.story.p1}</p>
          <p>{L.story.p2}</p>
          <p>{L.story.p3}</p>
        </div>
        <div className="pull">"{L.story.pull}"</div>
      </div>
    </section>
  );
}

// ============ ARCHITECTURE ============
function ArchSection({ project, locale }) {
  const L = LOCALES[locale];
  return (
    <section id="architecture" className="arch" style={{ backgroundImage: `url(${project.image})` }}>
      <div className="arch-content">
        <div>
          <div className="eyebrow" style={{ color: "rgba(255,255,255,0.7)" }}>
            <span className="dot"/>{L.chapter.num02}
          </div>
          <h3 className="display" style={{ marginTop: 16 }}>{L.arch.title}</h3>
        </div>
        <div className="arch-caption">
          {L.arch.caption}
          {project.rightsFlag && (
            <div style={{ marginTop: 18, fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--accent)", padding: 12, border: "1px solid rgba(182,138,53,.5)", background: "rgba(0,0,0,.3)" }}>
              ⚠ {project.rightsFlag}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ============ RESIDENCES ============
function ResidencesSection({ project, locale, onCTA }) {
  const L = LOCALES[locale];
  const [activeIdx, setActive] = useS(0);

  // Reset on project switch
  useE(() => { setActive(0); }, [project.id]);

  const concept = project.concepts[activeIdx];

  return (
    <section id="residences" className="wrap residences">
      <div className="section-head">
        <div className="label">
          <div className="num">{L.chapter.num03}</div>
          <div className="eyebrow"><span className="dot"/>{L.res.title}</div>
        </div>
        <div>
          <h2 className="display">A concept brief — never a contractual spec.</h2>
          <div className="lede">{L.res.lede}</div>
        </div>
      </div>

      <div className="res-tabs">
        {project.concepts.map((c, i) => (
          <button key={c} className={i === activeIdx ? "active" : ""} onClick={() => setActive(i)}>{c}</button>
        ))}
      </div>

      <div className="res-panel">
        <div className="res-img">
          {/* placeholder — confirmed floor plans not yet supplied */}
          <div className="stripe-ph">
            <span>{concept} · plan placeholder</span>
          </div>
        </div>
        <div className="res-detail">
          <div className="eyebrow" style={{ marginBottom: 12 }}><span className="dot"/>Concept · {activeIdx + 1} / {project.concepts.length}</div>
          <h3 className="display">{concept}</h3>
          <p style={{ color: "var(--muted)", fontSize: 14, lineHeight: 1.6, margin: "0 0 24px" }}>
            A {concept.toLowerCase()} typology within {project.name} — final layout, area schedule, ceiling heights, finishes
            specification and pricing released on signed brochure request.
          </p>

          <div className="res-line tbc"><span>Net area</span><span>{L.res.tbc}</span></div>
          <div className="res-line tbc"><span>Outdoor</span><span>{L.res.tbc}</span></div>
          <div className="res-line tbc"><span>Aspect</span><span>{L.res.tbc}</span></div>
          <div className="res-line tbc"><span>Ceiling</span><span>{L.res.tbc}</span></div>
          <div className="res-line tbc"><span>Indicative price</span><span>{L.res.tbc}</span></div>
          <div className="res-line tbc"><span>Handover</span><span>{L.res.tbc}</span></div>

          <div className="res-note">{L.res.no_specs}</div>

          <div style={{ marginTop: 24, display: "flex", gap: 8, flexWrap: "wrap" }}>
            <button className="btn solid" onClick={() => onCTA("register")}>{L.res.register} <span className="arrow"/></button>
            <button className="btn" onClick={() => onCTA("brochure")}>{L.cta.brochure}</button>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ AMENITIES ============
function AmenityIcon({ kind }) {
  const C = "currentColor";
  const sw = 1.2;
  switch (kind) {
    case 0: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>;
    case 1: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><path d="M2 17c1.5-1 3 1 5 0s3.5-2 5.5 0 3.5 2 5.5 0M2 13c1.5-1 3 1 5 0s3.5-2 5.5 0 3.5 2 5.5 0"/></svg>;
    case 2: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><path d="M3 20h18M5 20V8M19 20V8M5 8h14M9 8V4h6v4"/></svg>;
    case 3: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><circle cx="12" cy="9" r="3.5"/><path d="M5 21c0-4 3.5-6 7-6s7 2 7 6"/></svg>;
    case 4: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><path d="M4 12h2M18 12h2M6 9v6M18 9v6M8 12h8M9 7l-2 2M15 7l2 2M9 17l-2-2M15 17l2-2"/></svg>;
    case 5: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 9h18M7 5v14"/></svg>;
    case 6: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><circle cx="12" cy="8" r="3"/><path d="M6 21c0-3 3-5 6-5s6 2 6 5M9 13l-3 3M15 13l3 3"/></svg>;
    case 7: return <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth={sw}><rect x="3" y="5" width="18" height="12" rx="1"/><path d="M3 21h18M9 17v4M15 17v4"/></svg>;
    default: return null;
  }
}

function AmenitiesSection({ locale }) {
  const L = LOCALES[locale];
  const cells = [L.amen.a1, L.amen.a2, L.amen.a3, L.amen.a4, L.amen.a5, L.amen.a6, L.amen.a7, L.amen.a8];
  return (
    <section id="amenities" className="wrap">
      <div className="section-head">
        <div className="label">
          <div className="num">{L.chapter.num04}</div>
          <div className="eyebrow"><span className="dot"/>{L.amen.title}</div>
        </div>
        <div>
          <h2 className="display">Curated, by category — confirmed, by brochure.</h2>
          <div className="lede">{L.amen.lede}</div>
        </div>
      </div>
      <div className="amen-grid">
        {cells.map(([title, body], i) => (
          <div className="amen-cell" key={i}>
            <div className="glyph"><AmenityIcon kind={i} /></div>
            <h4>{title}</h4>
            <p>{body}</p>
            <div className="stat">Subject to confirmation</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ LOCATION ============
function LocationSection({ project, locale }) {
  const L = LOCALES[locale];

  // Stylised abstract map background — not a true Dubai map
  return (
    <section id="location" className="wrap">
      <div className="section-head">
        <div className="label">
          <div className="num">{L.chapter.num05}</div>
          <div className="eyebrow"><span className="dot"/>{L.loc.title}</div>
        </div>
        <div>
          <h2 className="display">A district line drawn around the project.</h2>
          <div className="lede">{L.loc.lede}</div>
        </div>
      </div>

      <div className="loc-grid">
        <div className="map-frame">
          <svg className="map" viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice">
            <defs>
              <linearGradient id="gMap" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0" stopColor="#0a2530"/>
                <stop offset="1" stopColor="#03101a"/>
              </linearGradient>
              <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                <path d="M40 0 L0 0 0 40" fill="none" stroke="rgba(0,167,200,0.08)" strokeWidth="0.5"/>
              </pattern>
            </defs>
            <rect width="400" height="500" fill="url(#gMap)"/>
            <rect width="400" height="500" fill="url(#grid)"/>
            {/* Abstract waterway */}
            <path d="M-20 380 Q 100 320 200 360 T 420 340" stroke="rgba(0,167,200,0.5)" strokeWidth="22" fill="none" strokeLinecap="round"/>
            <path d="M-20 380 Q 100 320 200 360 T 420 340" stroke="rgba(0,194,224,0.8)" strokeWidth="2" fill="none"/>
            {/* Roads */}
            <line x1="0" y1="120" x2="400" y2="120" stroke="rgba(255,255,255,0.15)" strokeWidth="1.5"/>
            <line x1="0" y1="200" x2="400" y2="200" stroke="rgba(255,255,255,0.1)" strokeWidth="1"/>
            <line x1="100" y1="0" x2="180" y2="500" stroke="rgba(255,255,255,0.1)" strokeWidth="1"/>
            <line x1="280" y1="0" x2="320" y2="500" stroke="rgba(255,255,255,0.1)" strokeWidth="1"/>
            {/* District plots */}
            {Array.from({ length: 16 }).map((_, i) => {
              const x = 40 + (i % 4) * 80;
              const y = 40 + Math.floor(i / 4) * 80;
              const w = 30 + Math.random() * 30;
              const h = 30 + Math.random() * 30;
              return <rect key={i} x={x} y={y} width={w} height={h} fill="rgba(255,255,255,0.04)" stroke="rgba(255,255,255,0.08)" strokeWidth="0.5"/>;
            })}
            {/* Nearby labels */}
            <text x="60" y="40" fill="rgba(255,255,255,0.4)" fontSize="9" fontFamily="JetBrains Mono">DOWNTOWN</text>
            <text x="220" y="80" fill="rgba(255,255,255,0.4)" fontSize="9" fontFamily="JetBrains Mono">BUSINESS BAY</text>
            <text x="310" y="430" fill="rgba(255,255,255,0.4)" fontSize="9" fontFamily="JetBrains Mono">CREEK</text>
            <text x="20" y="280" fill="rgba(255,255,255,0.4)" fontSize="9" fontFamily="JetBrains Mono">DIFC</text>
          </svg>
          <div className="map-pin" />
          <div className="map-label">
            <span>{L.loc.pin}</span>
            <b>{project.district.split("·")[0].trim()}</b>
          </div>
        </div>

        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 18 }}>
            {L.loc.nearby}
          </div>
          <div className="dist-list">
            {NEARBY.map((d) => (
              <div className="dist-row" key={d.name}>
                <div className="dist-name">{d.name}</div>
                <div className="dist-bar"><i style={{ width: (d.frac * 100) + "%" }}/></div>
                <div className="dist-mins">~ {d.mins} min</div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 32, padding: 18, background: "var(--surface)", border: "1px solid var(--border)", fontSize: 12, color: "var(--muted)", lineHeight: 1.55 }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}><span className="dot"/>Source notes</div>
            Map is illustrative — not a Binghatti site plan and not to scale.
            Final coordinates, building number and drive times are confirmed against the signed brochure
            and current traffic conditions. Address on file: Sheikh Zayed Road, Dubai, UAE — 341186
            (exact building / floor TBC).
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ GALLERY ============
function GallerySection({ locale, onOpen }) {
  const L = LOCALES[locale];
  const tiles = ["t-a", "t-b", "t-c", "t-d", "t-e", "t-f"];
  return (
    <section id="gallery" className="wrap gallery">
      <div className="section-head">
        <div className="label">
          <div className="num">{L.chapter.num06}</div>
          <div className="eyebrow"><span className="dot"/>{L.gal.title}</div>
        </div>
        <div>
          <h2 className="display">Six frames. Click to enlarge.</h2>
          <div className="lede">{L.gal.lede}</div>
        </div>
      </div>
      <div className="gallery-grid">
        {GALLERY.map((g, i) => (
          <div
            key={i}
            className={`gal-tile ${tiles[i]}`}
            style={{ backgroundImage: `url(${g.src})` }}
            data-cap={g.cap}
            onClick={() => onOpen(i)}
          />
        ))}
      </div>
    </section>
  );
}

function Lightbox({ idx, onClose, onPrev, onNext }) {
  useE(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onPrev();
      if (e.key === "ArrowRight") onNext();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose, onPrev, onNext]);
  const g = GALLERY[idx];
  return (
    <div className="lightbox" onClick={onClose}>
      <button className="lb-close" onClick={onClose} aria-label="Close">×</button>
      <button className="lb-arrow prev" onClick={(e) => { e.stopPropagation(); onPrev(); }}>‹</button>
      <button className="lb-arrow next" onClick={(e) => { e.stopPropagation(); onNext(); }}>›</button>
      <img src={g.src} alt={g.cap} onClick={(e) => e.stopPropagation()}/>
      <div className="lb-cap">{idx + 1} / {GALLERY.length} · {g.cap}</div>
    </div>
  );
}

// ============ CONNECT ============
function ConnectSection({ locale, onCTA }) {
  const L = LOCALES[locale];
  const cards = [
    [...L.conn.c1, "register"],
    [...L.conn.c2, "viewing"],
    [...L.conn.c3, "brochure"],
    [...L.conn.c4, "broker"],
  ];
  return (
    <section id="connect" className="connect">
      <div className="wrap">
        <div>
          <div className="eyebrow" style={{ color: "rgba(255,255,255,0.7)", marginBottom: 18 }}><span className="dot"/>{L.chapter.num07}</div>
          <h2 className="display">{L.conn.title}</h2>
          <p className="conn-sub">{L.conn.sub}</p>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 24 }}>
            <a className="btn" style={{ color: "#fff", borderColor: "rgba(255,255,255,.3)" }} href="https://wa.me/97180015" target="_blank" rel="noreferrer">
              {L.cta.whatsapp} +971 800 15 <span className="arrow"/>
            </a>
          </div>

          <div style={{ marginTop: 40, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }}>
            {REGIONS.map(r => (
              <div key={r.code} style={{ background: "rgba(255,255,255,.04)", border: "1px solid rgba(255,255,255,.1)", padding: 16 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                  <span style={{ fontSize: 18 }}>{r.flag}</span>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase" }}>{r.desk}</span>
                </div>
                <div style={{ fontSize: 13, opacity: .8 }}>{r.line}</div>
                <div style={{ fontSize: 12, color: "var(--primary)" }}>{r.email}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="conn-cards">
          {cards.map(([num, title, sub, act]) => (
            <button className="conn-card" key={num} onClick={() => onCTA(act)}>
              <div className="conn-num">{num}</div>
              <h4>{title}</h4>
              <p>{sub}</p>
              <div className="conn-arr">Open <span className="arrow" style={{ background: "var(--primary)" }}/></div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ FOOTER ============
function Footer({ project, locale, onProjectSwitch }) {
  const L = LOCALES[locale];
  return (
    <footer className="site-foot">
      <div className="foot-grid">
        <div>
          <Wordmark />
          <div style={{ marginTop: 8, fontFamily: "var(--font-display)", fontSize: 22, color: "#fff", maxWidth: "22ch", lineHeight: 1.2 }}>
            {L.foot.tagline}
          </div>
          <div style={{ marginTop: 24, fontSize: 12, color: "#999" }}>
            {L.foot.address}
          </div>
        </div>

        <div>
          <h5>{L.foot.projects}</h5>
          <ul>
            {PROJECT_ORDER.map(id => {
              const p = PROJECTS[id];
              return <li key={id}><a href="#" onClick={(e) => { e.preventDefault(); onProjectSwitch(id); }}>{p.name}</a></li>;
            })}
          </ul>
        </div>

        <div>
          <h5>{L.foot.offices}</h5>
          <ul>
            {REGIONS.map(r => <li key={r.code}>{r.flag} {r.desk} · {r.line}</li>)}
          </ul>
        </div>

        <div>
          <h5>{L.foot.connect}</h5>
          <ul>
            <li><a href="https://wa.me/97180015" target="_blank" rel="noreferrer">WhatsApp · +971 800 15</a></li>
            <li><a href="mailto:sales@binghatti.com">sales@binghatti.com</a></li>
            <li><a href="mailto:uksales@binghatti.com">uksales@binghatti.com</a></li>
            <li style={{ marginTop: 14, opacity: .5 }}>Instagram · Facebook · LinkedIn · YouTube · Snapchat</li>
          </ul>
        </div>
      </div>
      <div className="foot-bot">
        <div>{L.foot.copy}</div>
        <div className="attribs">
          {L.foot.attribs.map((a, i) => <span key={i}>{a}</span>)}
        </div>
      </div>
    </footer>
  );
}

// ============ STICKY DOCK ============
function CTADock({ project, locale, onCTA, hidden }) {
  const [show, setShow] = useS(false);
  if (hidden) return null;
  const L = LOCALES[locale];
  useE(() => {
    const onScroll = () => {
      const sh = window.scrollY;
      const vh = window.innerHeight;
      const dh = document.body.scrollHeight;
      // show after hero, hide near footer
      setShow(sh > vh * 0.9 && sh + vh < dh - 200);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className={`cta-dock ${show ? "show" : ""}`}>
      <span className="dock-meta">{project.name} · enquiry</span>
      <button onClick={() => onCTA("register")}>{L.cta.register} <span className="arrow"/></button>
    </div>
  );
}

// ============ SIDE RAIL ============
function SideRail({ activeChapter, locale }) {
  const L = LOCALES[locale];
  const chapters = [
    ["story", L.nav.story],
    ["architecture", L.nav.architecture],
    ["residences", L.nav.residences],
    ["amenities", L.nav.amenities],
    ["location", L.nav.location],
    ["gallery", L.nav.gallery],
    ["connect", L.nav.connect],
  ];
  return (
    <aside className="side-rail">
      {chapters.map(([id, label]) => (
        <a key={id} href={`#${id}`} className={"dot-row " + (activeChapter === id ? "active" : "")}>
          <span className="dot"/>
          <span className="label">{label}</span>
        </a>
      ))}
    </aside>
  );
}

// ============ TWEAKS ============
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#00A7C8",
  "accentLabel": "Cyan",
  "showDock": true,
  "showFab": true,
  "showSideRail": true,
  "heroOverlay": 0.55,
  "loremMode": false,
  "darkSurface": false
}/*EDITMODE-END*/;

function MicrositeTweaks({ t, setTweak, projectId, setProjectId, locale, setLocale }) {
  const { TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakToggle, TweakSlider, TweakSelect } = window;
  if (!TweaksPanel) return null;
  return (
    <TweaksPanel title="Tweaks · Microsite">
      <TweakSection label="Launch" />
      <TweakSelect
        label="Project"
        value={projectId}
        options={PROJECT_ORDER}
        format={(id) => PROJECTS[id].name}
        onChange={(v) => setProjectId(v)}
      />
      <TweakRadio
        label="Locale"
        value={locale}
        options={["en", "ar", "ru", "zh"]}
        onChange={(v) => setLocale(v)}
      />

      <TweakSection label="Brand accent" />
      <TweakColor
        label="Primary"
        value={t.accent}
        options={["#00A7C8", "#7AD6EA", "#B68A35", "#E94F1D", "#1A1D20"]}
        onChange={(v) => setTweak("accent", v)}
      />

      <TweakSection label="Surface" />
      <TweakToggle label="Sticky CTA dock" value={t.showDock} onChange={(v) => setTweak("showDock", v)} />
      <TweakToggle label="WhatsApp FAB" value={t.showFab} onChange={(v) => setTweak("showFab", v)} />
      <TweakToggle label="Side rail" value={t.showSideRail} onChange={(v) => setTweak("showSideRail", v)} />
      <TweakToggle label="Dark surfaces" value={t.darkSurface} onChange={(v) => setTweak("darkSurface", v)} />
      <TweakSlider label="Hero overlay" value={t.heroOverlay} min={0} max={1} step={0.05} onChange={(v) => setTweak("heroOverlay", v)} />
    </TweaksPanel>
  );
}

// ============ APP ============
function App() {
  const [projectId, setProjectId] = useS("etherea");
  const [locale, setLocale] = useS("en");
  const [activeChapter, setActiveChapter] = useS("story");
  const [modal, setModal] = useS(null);
  const [lightboxIdx, setLightboxIdx] = useS(null);
  const [projectPickerOpen, setPickerOpen] = useS(false);

  const useTweaks = window.useTweaks || ((d) => [d, () => {}]);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const project = PROJECTS[projectId];

  // Push accent + surface tweaks to CSS vars
  useE(() => {
    const r = document.documentElement.style;
    r.setProperty("--primary", t.accent);
    r.setProperty("--hero-overlay", String(t.heroOverlay));
    // Compute a deeper hover variant by appending an alpha sample; simple: same
    if (t.darkSurface) {
      r.setProperty("--bg", "#0E1318");
      r.setProperty("--bg-deep", "#161B22");
      r.setProperty("--surface", "#181E25");
      r.setProperty("--text", "#F0EEE8");
      r.setProperty("--text-soft", "#C8C6C0");
      r.setProperty("--muted", "#9097A0");
      r.setProperty("--muted-2", "#6A7079");
      r.setProperty("--border", "#272D34");
      r.setProperty("--border-soft", "#1F252C");
    } else {
      ["--bg","--bg-deep","--surface","--text","--text-soft","--muted","--muted-2","--border","--border-soft"].forEach(v => r.removeProperty(v));
    }
  }, [t.accent, t.darkSurface]);

  // Set RTL on body for arabic
  useE(() => {
    document.body.setAttribute("data-locale", locale);
    document.documentElement.lang = locale;
    document.documentElement.dir = locale === "ar" ? "rtl" : "ltr";
  }, [locale]);

  // Scrollspy
  useE(() => {
    const ids = ["story", "architecture", "residences", "amenities", "location", "gallery", "connect"];
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.filter(e => e.isIntersecting).sort((a,b) => b.intersectionRatio - a.intersectionRatio);
        if (visible[0]) setActiveChapter(visible[0].target.id);
      },
      { rootMargin: "-30% 0px -55% 0px", threshold: [0, 0.25, 0.5, 0.75, 1] }
    );
    ids.forEach(id => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [projectId]);

  // Fade-in observer
  useE(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add("seen"); });
    }, { threshold: 0.12 });
    document.querySelectorAll(".fade-in").forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, [projectId, locale]);

  // Scroll-to-top on project switch
  useE(() => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [projectId]);

  const onCTA = useCb((kind) => setModal(kind), []);
  const onOpenLB = useCb((i) => setLightboxIdx(i), []);

  // Listen for tweak panel project / locale / accent updates
  useE(() => {
    const fn = (e) => {
      if (!e?.data) return;
      if (e.data.type === "__bg_set_project" && PROJECTS[e.data.id]) setProjectId(e.data.id);
      if (e.data.type === "__bg_set_locale") setLocale(e.data.locale);
    };
    window.addEventListener("message", fn);
    return () => window.removeEventListener("message", fn);
  }, []);

  return (
    <>
      <TopBar
        project={project}
        locale={locale}
        setLocale={setLocale}
        activeChapter={activeChapter}
        onCTA={onCTA}
        onProjectSwitch={() => setPickerOpen(true)}
      />
      {t.showSideRail && <SideRail activeChapter={activeChapter} locale={locale} />}

      <Hero project={project} locale={locale} onCTA={onCTA} />
      <StorySection project={project} locale={locale} />
      <ArchSection project={project} locale={locale} />
      <ResidencesSection project={project} locale={locale} onCTA={onCTA} />
      <AmenitiesSection locale={locale} />
      <LocationSection project={project} locale={locale} />
      <GallerySection locale={locale} onOpen={onOpenLB} />
      <ConnectSection locale={locale} onCTA={onCTA} />
      <Footer project={project} locale={locale} onProjectSwitch={(id) => setProjectId(id)} />

      <CTADock project={project} locale={locale} onCTA={onCTA} hidden={!t.showDock} />

      {t.showFab && (
        <a className="wa-fab" href="https://wa.me/97180015" target="_blank" rel="noreferrer">
          <span className="wa-ic-fab"><WhatsAppGlyph /></span>
          <span>WhatsApp · 800 15</span>
        </a>
      )}

      <MicrositeTweaks
        t={t} setTweak={setTweak}
        projectId={projectId} setProjectId={setProjectId}
        locale={locale} setLocale={setLocale}
      />

      {modal === "register" && <RegisterInterestModal project={project} onClose={() => setModal(null)} />}
      {modal === "brochure" && <BrochureModal project={project} onClose={() => setModal(null)} />}
      {modal === "viewing" && <ViewingModal project={project} onClose={() => setModal(null)} />}
      {modal === "broker" && <BrokerModal project={project} onClose={() => setModal(null)} />}

      {lightboxIdx != null && (
        <Lightbox
          idx={lightboxIdx}
          onClose={() => setLightboxIdx(null)}
          onPrev={() => setLightboxIdx((lightboxIdx - 1 + GALLERY.length) % GALLERY.length)}
          onNext={() => setLightboxIdx((lightboxIdx + 1) % GALLERY.length)}
        />
      )}

      {projectPickerOpen && (
        <ProjectPicker
          current={projectId}
          onPick={(id) => { setProjectId(id); setPickerOpen(false); }}
          onClose={() => setPickerOpen(false)}
        />
      )}
    </>
  );
}

function ProjectPicker({ current, onPick, onClose }) {
  return (
    <div className="modal-bg" onClick={(e) => { if (e.target.classList.contains("modal-bg")) onClose(); }}>
      <div className="modal" style={{ maxWidth: 880 }}>
        <div className="modal-head">
          <div>
            <div className="step">Microsite template · jump to launch</div>
            <h3>Active launches</h3>
          </div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body" style={{ padding: 0 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 1, background: "var(--border-soft)" }}>
            {PROJECT_ORDER.map(id => {
              const p = PROJECTS[id];
              return (
                <button
                  key={id}
                  onClick={() => onPick(id)}
                  style={{
                    background: id === current ? "var(--ink-dark)" : "var(--bg)",
                    color: id === current ? "#fff" : "var(--text)",
                    border: 0,
                    padding: 0,
                    textAlign: "start",
                    cursor: "pointer",
                    display: "flex",
                    flexDirection: "column",
                    overflow: "hidden",
                  }}
                >
                  <div style={{ aspectRatio: "5/3", backgroundImage: `url(${p.image})`, backgroundSize: "cover", backgroundPosition: "center" }} />
                  <div style={{ padding: 16 }}>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", color: p.type === "branded" ? "var(--accent)" : "var(--primary)", marginBottom: 6 }}>
                      {p.type === "branded" ? "Branded residence" : "Signature collection"}
                    </div>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 24, lineHeight: 1.05 }}>{p.name}</div>
                    <div style={{ fontSize: 12, color: id === current ? "rgba(255,255,255,.6)" : "var(--muted)", marginTop: 6 }}>{p.district}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

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