// sections.jsx — Cala Del Mar microsite section components
// Expects window.DATA from data.jsx

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

// ─── Logo monograms ────────────────────────────────────────────────────────
function EGNMark({ size = 22, color }) {
  // Simple geometric mark inspired by the project's own monogram language —
  // chevron + diamond — used as a brand stand-in across the prototype.
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden="true">
      <path d="M22 2 L8 16 L22 30" stroke={color || "currentColor"} strokeWidth="2" fill="none" />
      <rect x="12.5" y="11.5" width="9" height="9" transform="rotate(45 17 16)" stroke={color || "currentColor"} strokeWidth="1.5" fill="none" />
    </svg>
  );
}

// ─── Reveal-on-scroll wrapper ──────────────────────────────────────────────
function Reveal({ children, delay = 0, as: Tag = "div", className = "", ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (es) => es.forEach((e) => {
        if (e.isIntersecting) { setTimeout(() => setShown(true), delay); io.disconnect(); }
      }),
      { threshold: 0.12 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`} {...rest}>{children}</Tag>;
}

// ─── Navigation ────────────────────────────────────────────────────────────
function Nav({ onRegister, locale, setLocale, locales }) {
  const [scrolled, setScrolled] = useState(false);
  const [locOpen, setLocOpen] = useState(false);
  useEffect(() => {
    const onS = () => setScrolled(window.scrollY > 80);
    window.addEventListener("scroll", onS, { passive: true });
    return () => window.removeEventListener("scroll", onS);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <a href="#top" className="nav-logo" aria-label="Ellington Properties — home">
        <EGNMark size={20} />
        <span>Ellington</span>
      </a>
      <div className="nav-menu" role="menubar">
        <a href="#design">Design</a>
        <a href="#residences">Residences</a>
        <a href="#amenities">Amenities</a>
        <a href="#location">Location</a>
        <a href="#gallery">Gallery</a>
        <a href="#portfolio">Portfolio</a>
      </div>
      <div className="nav-right">
        <div style={{ position: "relative" }}>
          <button
            className="locale-btn"
            onClick={() => setLocOpen((v) => !v)}
            onBlur={() => setTimeout(() => setLocOpen(false), 180)}
            aria-haspopup="listbox"
            aria-expanded={locOpen}
          >
            {locale} <span style={{ opacity: 0.5, marginLeft: 4 }}>▾</span>
          </button>
          {locOpen && (
            <div
              role="listbox"
              style={{
                position: "absolute", top: "calc(100% + 6px)", right: 0,
                background: "var(--paper)", color: "var(--ink)",
                border: "1px solid var(--hairline)", padding: "6px 0", minWidth: 110, zIndex: 60,
              }}
            >
              {locales.map((l) => (
                <button
                  key={l}
                  onMouseDown={() => { setLocale(l); setLocOpen(false); }}
                  className="locale-btn"
                  style={{
                    display: "block", width: "100%", textAlign: "left",
                    border: 0, padding: "8px 14px",
                    background: locale === l ? "var(--bg)" : "transparent",
                  }}
                >
                  {l}
                </button>
              ))}
            </div>
          )}
        </div>
        <button className="nav-cta" onClick={onRegister}><span>Register Interest</span></button>
      </div>
    </nav>
  );
}

// ─── Hero ──────────────────────────────────────────────────────────────────
function Hero({ project, motion, onRegister, onBrochure }) {
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setLoaded(true), 80);
    return () => clearTimeout(t);
  }, []);
  const heroImgStyle = {
    backgroundImage: `url('media/project-cala-del-mar.webp')`,
    ...(motion === "parallax" ? { transform: "scale(1.0)" } : {}),
  };
  return (
    <section className={`hero ${loaded ? "loaded" : ""}`} id="top">
      <div
        className="hero-img"
        style={motion === "kenburns" ? heroImgStyle : { backgroundImage: `url('media/project-cala-del-mar.webp')`, transform: "scale(1)" }}
      />
      <div className="hero-veil" />
      <div className="hero-grid">
        <div className="hero-center">
          <div className="hero-tag" style={{ marginBottom: 28 }}>
            {project.district} · {project.emirate}
          </div>
          <h1 className="display">Cala <em>Del Mar</em></h1>
          <p className="hero-sub">
            {project.intro}
          </p>
          <div className="hero-ctas">
            <button className="btn btn-light-fill arrow" onClick={onRegister}>Register Interest</button>
            <button className="btn btn-light arrow" onClick={onBrochure}>Download Brochure</button>
          </div>
        </div>
        <div className="hero-bottom">
          <div className="hero-meta"><span>Address</span><b>Al Hamra Island</b></div>
          <div className="hero-meta"><span>Frontage</span><b>Arabian Gulf</b></div>
          <div className="hero-meta"><span>Status</span><b>Off-plan</b></div>
          <div className="hero-meta"><span>Enquiries</span><b>By registration</b></div>
        </div>
      </div>
    </section>
  );
}

// ─── Pull-quote ────────────────────────────────────────────────────────────
function PullQuote({ project }) {
  return (
    <section className="pull wrap">
      <Reveal>
        <span className="eyebrow">§ 01 · The Hook</span>
        <blockquote className="display" style={{ marginTop: 28 }}>
          {project.hook}
        </blockquote>
        <div className="who"><span>An Ellington Properties launch · Al Hamra Island, RAK</span></div>
      </Reveal>
    </section>
  );
}

// ─── Design & architecture (split, with interior) ──────────────────────────
function DesignSection({ project }) {
  return (
    <section className="sec wrap" id="design">
      <div className="sec-head">
        <span className="eyebrow">§ 02 · Design &amp; Architecture</span>
        <span className="mono" style={{ color: "var(--soft)" }}>Atelier note 02 / 06</span>
      </div>
      <div className="split">
        <Reveal className="split-body">
          <span className="eyebrow">A study in restraint</span>
          <h2 className="display">A slow, <em>white volume</em><br />drawn to the sea.</h2>
          {project.designStory.map((para, i) => (
            <p key={i}>{para}</p>
          ))}
        </Reveal>
        <Reveal delay={120}>
          <img src="media/interior-cala-del-mar-1.webp" alt="Cala Del Mar lobby — interior render" loading="lazy" />
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, fontFamily: "var(--mono-font)", fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)" }}>
            <span>Plate 02 · Arrival lobby</span>
            <span>Render · subject &amp; credit to confirm</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ─── Residences ────────────────────────────────────────────────────────────
function Residences({ project }) {
  return (
    <section className="sec wrap" id="residences">
      <div className="sec-head">
        <div>
          <span className="eyebrow">§ 03 · Residences &amp; Concepts</span>
          <h2 className="sec-title display" style={{ marginTop: 18 }}>Four typologies, <em>one horizon.</em></h2>
        </div>
        <p style={{ maxWidth: "32ch", color: "var(--muted)", margin: 0, fontSize: 14, lineHeight: 1.6 }}>
          Plans confirmed at RERA/DLD registration. Pricing on request — please register interest to receive
          the brochure, current availability and a private viewing.
        </p>
      </div>
      <div className="spec">
        {project.residences.map((r) => (
          <Reveal key={r.num} className="spec-cell">
            <div>
              <span className="num">No. {r.num}</span>
              <h3 className="display">{r.name}</h3>
              <span className="detail">{r.detail}</span>
            </div>
            <span className="price">{r.price}</span>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ─── Amenities ─────────────────────────────────────────────────────────────
function AmenityGlyph({ ix }) {
  // Tiny geometric stand-in glyphs — placeholder marks rather than literal icons.
  const map = {
    0: <><circle cx="14" cy="14" r="10" /><path d="M4 14h20" /></>,
    1: <><path d="M4 24 Q14 4 24 24" /></>,
    2: <><rect x="4" y="4" width="20" height="20" /><path d="M4 14h20M14 4v20" /></>,
    3: <><rect x="4" y="4" width="20" height="20" /></>,
    4: <><path d="M4 20l10-14 10 14" /></>,
    5: <><path d="M4 22 Q14 14 24 22 M4 18 Q14 10 24 18" /></>,
    6: <><circle cx="14" cy="14" r="10" /><circle cx="14" cy="14" r="3" /></>,
    7: <><path d="M4 14h20M14 4l10 10-10 10" /></>,
    8: <><path d="M4 6h20v16H4z" /><path d="M9 11l5 4 5-4" /></>,
  };
  return (
    <svg className="glyph" viewBox="0 0 28 28" aria-hidden="true">
      {map[ix % 9]}
    </svg>
  );
}
function Amenities({ project }) {
  return (
    <section className="sec wrap" id="amenities">
      <div className="sec-head">
        <div>
          <span className="eyebrow">§ 04 · Amenities</span>
          <h2 className="sec-title display" style={{ marginTop: 18 }}>An island of <em>quiet utility.</em></h2>
        </div>
      </div>
      <div className="amen">
        {project.amenities.map((a, i) => (
          <Reveal key={a.n} className="amen-cell">
            <div className="ix">
              <AmenityGlyph ix={i} />
              <span className="n">{a.n}</span>
            </div>
            <h4 className="display">{a.title}</h4>
            <p>{a.desc}</p>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ─── Location ──────────────────────────────────────────────────────────────
function MapPlate() {
  // Stylised abstract map plate — not a literal Google map. Just a place plate.
  return (
    <svg viewBox="0 0 400 480" preserveAspectRatio="xMidYMid slice">
      <defs>
        <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
          <path d="M 20 0 L 0 0 0 20" fill="none" stroke="var(--hairline)" strokeWidth="0.5" />
        </pattern>
      </defs>
      <rect width="400" height="480" fill="var(--paper)" />
      <rect width="400" height="480" fill="url(#grid)" />
      {/* Sea */}
      <path d="M0,180 Q120,160 220,180 T400,200 L400,480 L0,480 Z" fill="var(--accent)" opacity="0.16" />
      <path d="M0,200 Q120,180 220,200 T400,220 L400,480 L0,480 Z" fill="var(--accent)" opacity="0.10" />
      {/* Island shape */}
      <path d="M60,260 Q120,220 220,240 Q300,255 340,290 Q330,360 260,380 Q170,395 110,360 Q70,330 60,260 Z" fill="var(--paper)" stroke="var(--ink)" strokeWidth="1" />
      {/* Roads */}
      <path d="M60,260 Q200,300 340,290" fill="none" stroke="var(--hairline)" strokeWidth="1" strokeDasharray="3 3" />
      <path d="M150,225 L180,380" fill="none" stroke="var(--hairline)" strokeWidth="1" strokeDasharray="3 3" />
      {/* Site marker */}
      <g transform="translate(220,310)">
        <circle r="22" fill="none" stroke="var(--ink)" strokeWidth="1" />
        <circle r="6" fill="var(--ink)" />
        <line x1="0" y1="-22" x2="0" y2="-44" stroke="var(--ink)" strokeWidth="1" />
        <text x="6" y="-46" fontFamily="var(--mono-font)" fontSize="9" letterSpacing="2" fill="var(--ink)">CALA DEL MAR</text>
      </g>
      {/* Labels */}
      <text x="38" y="40" fontFamily="var(--mono-font)" fontSize="9" letterSpacing="2" fill="var(--muted)">25.6818° N · 55.7708° E</text>
      <text x="38" y="56" fontFamily="var(--mono-font)" fontSize="9" letterSpacing="2" fill="var(--muted)">AL HAMRA ISLAND · RAK</text>
      <text x="200" y="170" fontFamily="var(--display-font)" fontStyle="italic" fontSize="22" fill="var(--ink)" textAnchor="middle">Arabian Gulf</text>
      <text x="80" y="450" fontFamily="var(--mono-font)" fontSize="8" letterSpacing="2" fill="var(--soft)">↑ N</text>
    </svg>
  );
}
function Location({ project }) {
  return (
    <section className="sec wrap" id="location">
      <div className="sec-head">
        <div>
          <span className="eyebrow">§ 05 · Location &amp; Community</span>
          <h2 className="sec-title display" style={{ marginTop: 18 }}>An island within <em>an island.</em></h2>
        </div>
        <p style={{ maxWidth: "34ch", color: "var(--muted)", margin: 0, fontSize: 14, lineHeight: 1.6 }}>
          Al Hamra Island is a planned, gated community on the northern emirate's coast — a quieter pace
          than Dubai's central waterfront, with golf, marina and beach inside the gate.
        </p>
      </div>
      <div className="loc">
        <Reveal className="loc-map">
          <MapPlate />
        </Reveal>
        <Reveal delay={140}>
          <div className="loc-list" style={{ marginBottom: 32 }}>
            {project.proximity.map((p) => (
              <div className="loc-row" key={p.name}>
                <span className="name display">{p.name}</span>
                <span className="unit">{p.unit}</span>
                <span className="dist display">{p.dist}</span>
              </div>
            ))}
          </div>
          <p style={{ fontFamily: "var(--mono-font)", fontSize: 10.5, letterSpacing: "0.14em", color: "var(--muted)", textTransform: "uppercase" }}>
            Travel times are indicative · Map plate is illustrative, not to scale
          </p>
        </Reveal>
      </div>
    </section>
  );
}

// ─── Gallery + Lightbox ────────────────────────────────────────────────────
function Gallery({ project, onOpen }) {
  return (
    <section className="sec wrap" id="gallery">
      <div className="sec-head">
        <div>
          <span className="eyebrow">§ 06 · Gallery</span>
          <h2 className="sec-title display" style={{ marginTop: 18 }}>Plates 01–05.</h2>
        </div>
        <span className="mono" style={{ color: "var(--soft)" }}>Renders · subject &amp; credit to confirm per release</span>
      </div>
      <div className="gallery">
        {project.gallery.map((g, i) => (
          <div className={`tile ${g.cls}`} key={g.src} data-label={g.label} onClick={() => onOpen(i)}>
            <img src={g.src} alt={g.label} loading="lazy" />
          </div>
        ))}
      </div>
    </section>
  );
}
function Lightbox({ items, index, onClose, onPrev, onNext }) {
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onPrev();
      if (e.key === "ArrowRight") onNext();
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose, onPrev, onNext]);
  if (index == null) return null;
  const item = items[index];
  return (
    <div className="lbx" onClick={onClose} role="dialog" aria-modal="true">
      <img src={item.src} alt={item.label} onClick={(e) => e.stopPropagation()} />
      <button className="lbx-close" onClick={onClose} aria-label="Close">×</button>
      <button className="lbx-nav lbx-prev" onClick={(e) => { e.stopPropagation(); onPrev(); }}>← Prev</button>
      <button className="lbx-nav lbx-next" onClick={(e) => { e.stopPropagation(); onNext(); }}>Next →</button>
      <div className="lbx-meta">{item.label} · Plate {index + 1} / {items.length}</div>
    </div>
  );
}

// ─── Trust + Awards strip ─────────────────────────────────────────────────
function TrustStrip() {
  return (
    <section className="wrap">
      <div className="trust">
        <Reveal className="trust-cell">
          <div className="big display">2014</div>
          <span className="lbl">Founded</span>
          <p>Founded in Dubai by Robert D. Booth (former Emaar senior executive), Elie Naaman and Joseph Thomas.</p>
        </Reveal>
        <Reveal className="trust-cell" delay={80}>
          <div className="big display">25+</div>
          <span className="lbl">Developments delivered &amp; in flight</span>
          <p>Across Palm Jumeirah, Dubai Islands, Mina Rashid, MBR City, Business Bay, Dubai Hills, JVC and RAK.</p>
        </Reveal>
        <Reveal className="trust-cell" delay={160}>
          <div className="big display">2024<span style={{ fontSize: 28, color: "var(--muted)" }}> · </span>2025</div>
          <span className="lbl">International Property Awards</span>
          <p>Verified wins in 2024 and 2025; categories and projects available on request. <em>(Issuer: IPA.)</em></p>
        </Reveal>
        <Reveal className="trust-cell" delay={240}>
          <div className="big display">RERA<span style={{ fontSize: 28, color: "var(--muted)" }}> · </span>DLD</div>
          <span className="lbl">Escrow Framework</span>
          <p>Buyer funds for off-plan are protected through Dubai's RERA/DLD escrow framework. Project-level statuses to be confirmed per release.</p>
        </Reveal>
      </div>
    </section>
  );
}

// ─── Portfolio ────────────────────────────────────────────────────────────
function Portfolio({ items }) {
  return (
    <section className="sec wrap" id="portfolio">
      <div className="sec-head">
        <div>
          <span className="eyebrow">§ 07 · The Wider Portfolio</span>
          <h2 className="sec-title display" style={{ marginTop: 18 }}>Other Ellington developments.</h2>
        </div>
        <a href="#" className="mono arrow" style={{ color: "var(--ink)" }}>View full portfolio&nbsp;&nbsp;</a>
      </div>
      <div className="port">
        {items.map((p, i) => (
          <Reveal key={p.name} className="port-card" delay={i * 80}>
            <img src={p.img} alt={p.name} loading="lazy" />
            <div className="meta">
              <b className="display">{p.name}</b>
              <span>{p.district}</span>
            </div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// Export
Object.assign(window, {
  Reveal, Nav, Hero, PullQuote, DesignSection, Residences, Amenities,
  Location, Gallery, Lightbox, TrustStrip, Portfolio, EGNMark,
});
