// components.jsx — chrome (nav, hero, footer, fab, modal) + register-interest form.
// Loaded BEFORE sections.jsx so window globals share a render order.

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

// ─── Logo SVG (inline so we can recolor via currentColor / fill-override) ──
window.LogoSVG = function LogoSVG() {
  // Inline logo from media/logo-dandb-main.svg. Fills are overridden via CSS by parent class.
  return (
    <object data="media/logo-dandb-main.svg" type="image/svg+xml" aria-label="D&B Properties" style={{ pointerEvents: "none", width: "100%", height: "auto" }} />
  );
};

// Simple inline SVG copy of logo to allow CSS fill override on path[fill]
window.LogoInline = function LogoInline() {
  // CSS-masked monochrome lockup so it inherits currentColor cleanly on dark + light surfaces.
  return (
    <span
      role="img"
      aria-label="D&B Properties"
      style={{
        display: "block",
        width: "100%",
        aspectRatio: "205 / 49",
        backgroundColor: "currentColor",
        WebkitMaskImage: "url(media/logo-dandb-main.svg)",
        maskImage: "url(media/logo-dandb-main.svg)",
        WebkitMaskRepeat: "no-repeat",
        maskRepeat: "no-repeat",
        WebkitMaskSize: "contain",
        maskSize: "contain",
        WebkitMaskPosition: "left center",
        maskPosition: "left center",
      }}
    />
  );
};

// ─── Nav ────────────────────────────────────────────────────────────
window.Nav = function Nav({ locale, setLocale, dark, onOpenRegister, onOpenLocale, localeOpen }) {
  const L = window.LOCALES[locale];
  return (
    <header className={`nav ${dark ? "nav--dark" : "nav--light"}`}>
      <div className="nav__brand">
        <div className={`mark ${dark ? "mark--dark" : "mark--light"}`}>
          <window.LogoInline />
        </div>
        <span className="divider"></span>
        <span className="codename">{window.PROJECT.codename} · {window.PROJECT.name}</span>
      </div>
      <nav className="nav__links" aria-label="Microsite chapters">
        <a href="#project">{L.nav.project}</a>
        <a href="#residences">{L.nav.residences}</a>
        <a href="#amenities">{L.nav.amenities}</a>
        <a href="#location">{L.nav.location}</a>
        <a href="#gallery">{L.nav.gallery}</a>
      </nav>
      <div className="nav__right">
        <button className="locale-toggle" onClick={onOpenLocale} aria-haspopup="menu" aria-expanded={localeOpen}>
          <span style={{ width: 4, height: 4, borderRadius: "50%", background: "var(--gold)", display: "inline-block" }}></span>
          {L.label}
          <span className="chev">▾</span>
        </button>
        <button className="btn btn--gold btn--sm" onClick={onOpenRegister}>
          {L.nav.register} <span className="arr">→</span>
        </button>
      </div>
    </header>
  );
};

// ─── Locale menu ───────────────────────────────────────────────────
window.LocaleMenu = function LocaleMenu({ open, locale, setLocale, onClose }) {
  if (!open) return null;
  const codes = ["en", "ar", "de", "ru", "zh"];
  return (
    <div
      role="dialog"
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 95,
        background: "rgba(11,8,32,0.4)", backdropFilter: "blur(4px)",
        display: "flex", alignItems: "flex-start", justifyContent: "flex-end",
        padding: "76px 24px 24px",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--paper)", border: "1px solid var(--line)",
          padding: 24, width: 280, borderRadius: 2,
        }}
      >
        <div className="eyebrow" style={{ marginBottom: 14 }}>Language</div>
        {codes.map((c) => (
          <button
            key={c}
            onClick={() => { setLocale(c); onClose(); }}
            style={{
              display: "flex", width: "100%", alignItems: "center", justifyContent: "space-between",
              padding: "12px 0", borderBottom: "1px solid var(--line)",
              background: "transparent", border: 0, borderBottomWidth: 1, borderBottomStyle: "solid",
              borderBottomColor: "var(--line)", cursor: "default",
              fontFamily: "var(--sans)", fontSize: 14, color: "var(--text)",
              textAlign: "start",
            }}
          >
            <span style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)", letterSpacing: "0.16em" }}>
                {window.LOCALES[c].label}
              </span>
              <span>
                {c === "en" && "English"}
                {c === "ar" && "العربية"}
                {c === "de" && "Deutsch"}
                {c === "ru" && "Русский"}
                {c === "zh" && "中文"}
              </span>
            </span>
            {locale === c && (
              <span style={{ color: "var(--gold-2)", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.14em" }}>•</span>
            )}
          </button>
        ))}
        <p style={{ marginTop: 14, fontSize: 11.5, color: "var(--muted)", lineHeight: 1.5 }}>
          Matches the corporate site's five-language set (EN / AR / RU / ZH / DE).
          AR mirrors via <code>dir="rtl"</code>.
        </p>
      </div>
    </div>
  );
};

// ─── Hero ──────────────────────────────────────────────────────────
window.Hero = function Hero({ L, variant, onOpenRegister, accent }) {
  return (
    <section className="hero" data-variant={variant}>
      <div className="hero__bg" style={{ backgroundImage: "url(media/hero-main-banner.webp)" }} role="img" aria-label="Indicative Dubai skyline · template hero" />
      <div className="hero__scrim"></div>

      <div className="hero__top">
        <span>D&B Properties · Bayari Holding</span>
        <span className="meta">
          <span><span className="dot"></span>RERA ORN 16576 · verified</span>
          <span><span className="dot"></span>Template demo · no live prices</span>
        </span>
      </div>

      <div className="hero__center">
        <div className="hero__codename">
          <span className="bar"></span>
          {window.PROJECT.codename} · {L.hero.eyebrow}
        </div>
        {variant === "split" ? (
          <div style={{ display: "grid", gridTemplateColumns: "7fr 5fr", gap: "4rem", alignItems: "center" }}>
            <div>
              <h1 className="hero__title">{window.renderTokens(L.hero.title)}</h1>
              <p className="hero__sub">{L.hero.sub}</p>
              <div className="hero__ctas">
                <button className="btn btn--gold" onClick={onOpenRegister}>
                  {L.hero.ctaPrimary} <span className="arr">→</span>
                </button>
                <button className="btn btn--ghost on-dark">
                  {L.hero.ctaSecondary}
                </button>
              </div>
            </div>
            <div className="hero__sample">
              <div className="tile" style={{ backgroundImage: "url(media/area-dubai-marina.webp)" }} />
              <div className="tile" style={{ backgroundImage: "url(media/listing-tilal-al-ghaf-villa.webp)" }} />
              <div className="tile" style={{ backgroundImage: "url(media/listing-marina-apartment-1.webp)" }} />
              <div className="tile" style={{ backgroundImage: "url(media/feature-waterfront-living.webp)" }} />
            </div>
          </div>
        ) : (
          <React.Fragment>
            <h1 className="hero__title">{window.renderTokens(L.hero.title)}</h1>
            <p className="hero__sub">{L.hero.sub}</p>
            <div className="hero__ctas">
              <button className="btn btn--gold" onClick={onOpenRegister}>
                {L.hero.ctaPrimary} <span className="arr">→</span>
              </button>
              <button className="btn btn--ghost on-dark">
                {L.hero.ctaSecondary}
              </button>
            </div>
          </React.Fragment>
        )}
      </div>

      <div className="hero__bottom">
        <div className="stat">
          <div className="label">Location</div>
          <div className="value">Palm Jebel <em className="it" style={{ color: "#E6D7B8" }}>Ali</em></div>
        </div>
        <div className="stat">
          <div className="label">Completion</div>
          <div className="value">Q4 <em className="it" style={{ color: "#E6D7B8" }}>2027</em></div>
        </div>
        <div className="stat">
          <div className="label">Payment</div>
          <div className="value">60 / <em className="it" style={{ color: "#E6D7B8" }}>40</em></div>
        </div>
        <div className="stat">
          <div className="label">Residences</div>
          <div className="value">1 – 4 BR <span className="small">+ PH</span></div>
        </div>
      </div>
    </section>
  );
};

// ─── Register Interest form (in-page CTA section + modal) ─────────
window.RegisterForm = function RegisterForm({ L, compact }) {
  const [step, setStep] = useState(1);
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({
    name: "", phone: "", email: "",
    unit: ["2-bedroom"], budget: "", notes: "", consent: false,
  });
  const [errors, setErrors] = useState({});

  function toggleUnit(u) {
    const has = form.unit.includes(u);
    setForm({ ...form, unit: has ? form.unit.filter((x) => x !== u) : [...form.unit, u] });
  }

  function validateStep1() {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.phone.trim()) e.phone = "Required";
    else if (!/^[\d\s+()-]{7,}$/.test(form.phone)) e.phone = "Looks short — include country code";
    if (!form.email.trim()) e.email = "Required";
    else if (!/^[^@]+@[^@]+\.[^@]+$/.test(form.email)) e.email = "Invalid email";
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function submit() {
    if (!form.consent) {
      setErrors({ ...errors, consent: "Please confirm" });
      return;
    }
    // honeypot 'website' field would be checked here in prod
    setSubmitted(true);
    // demo: log goal
    console.info("[goal] lead_register", { ...form, source: "marsa-cove", locale: window.__LOCALE });
  }

  if (submitted) {
    return (
      <div className="form-card form-success">
        <div className="tick">
          <span className="check">✓</span>
          Lead received · queued to off-plan team
        </div>
        <h4>Thanks, <span className="it">{form.name.split(" ")[0] || "we'll be in touch"}</span>.</h4>
        <p>
          A senior off-plan consultant will be in touch within one working day with the
          developer's full deck, the 60/40 payment plan, current availability and any
          remaining inventory tiers. Direct from the source — no bots, no invented prices.
        </p>
        <div className="form-actions">
          <a className="btn btn--ghost on-light">
            <span style={{ width: 12, height: 12, background: "var(--gold)", borderRadius: "50%", display: "inline-block" }}></span>
            Continue on WhatsApp
          </a>
          <button className="btn btn--ghost on-light" onClick={() => { setSubmitted(false); setStep(1); setForm({ name: "", phone: "", email: "", unit: ["2-bedroom"], budget: "", notes: "", consent: false }); }}>
            Submit another
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="form-card">
      <div className="step">
        <span>Step {step} of 2 · {step === 1 ? "About you" : "Your interest"}</span>
        <span className="dot-row">
          <span className={`d ${step >= 1 ? "is-active" : ""} ${step > 1 ? "is-done" : ""}`}></span>
          <span className={`d ${step >= 2 ? "is-active" : ""}`}></span>
        </span>
      </div>

      <h3>
        {step === 1
          ? <React.Fragment>Start your <span className="it">enquiry</span></React.Fragment>
          : <React.Fragment>What are you <span className="it">looking</span> for?</React.Fragment>}
      </h3>

      {/* honeypot */}
      <input type="text" name="website" tabIndex="-1" autoComplete="off" style={{ position: "absolute", left: -9999, opacity: 0 }} aria-hidden="true" />

      {step === 1 && (
        <React.Fragment>
          <div className={`fld ${errors.name ? "err" : ""}`}>
            <div className="l">Name <span className="req">*</span></div>
            <input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Your full name" />
            {errors.name && <div className="errtxt">{errors.name}</div>}
          </div>
          <div className="fld row">
            <div className={`fld ${errors.phone ? "err" : ""}`} style={{ marginBottom: 0 }}>
              <div className="l">Phone <span className="req">*</span></div>
              <input type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="+971 …" />
              {errors.phone && <div className="errtxt">{errors.phone}</div>}
            </div>
            <div className={`fld ${errors.email ? "err" : ""}`} style={{ marginBottom: 0 }}>
              <div className="l">Email <span className="req">*</span></div>
              <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@…" />
              {errors.email && <div className="errtxt">{errors.email}</div>}
            </div>
          </div>
          <div className="form-actions">
            <button
              className="btn"
              onClick={() => { if (validateStep1()) setStep(2); }}
            >
              Continue <span className="arr">→</span>
            </button>
            <span className="note">
              We never call without permission. RERA registered — ORN 16576.
            </span>
          </div>
        </React.Fragment>
      )}

      {step === 2 && (
        <React.Fragment>
          <div className="fld">
            <div className="l">Unit type interest <span className="req">*</span></div>
            <div className="unit-pick">
              {["1-bedroom", "2-bedroom", "3-bedroom", "Townhouse", "Duplex", "Penthouse"].map((u) => (
                <button
                  key={u}
                  className={form.unit.includes(u) ? "is-on" : ""}
                  onClick={() => toggleUnit(u)}
                >{u}</button>
              ))}
            </div>
          </div>
          <div className="fld">
            <div className="l">Budget band <span style={{ color: "var(--muted)", fontWeight: 400 }}>(optional — for us to filter)</span></div>
            <select value={form.budget} onChange={(e) => setForm({ ...form, budget: e.target.value })}>
              <option value="">— Prefer not to say —</option>
              <option>Under AED 2M</option>
              <option>AED 2M — 4M</option>
              <option>AED 4M — 7M</option>
              <option>AED 7M — 12M</option>
              <option>AED 12M +</option>
            </select>
          </div>
          <div className="fld">
            <div className="l">Anything else?</div>
            <textarea value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} placeholder="Timing, sea aspect, payment preferences …"></textarea>
          </div>
          <div className={`fld ${errors.consent ? "err" : ""}`}>
            <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 13, color: "var(--muted)", lineHeight: 1.5 }}>
              <input type="checkbox" checked={form.consent} onChange={(e) => setForm({ ...form, consent: e.target.checked })} style={{ marginTop: 3 }} />
              <span>
                I'd like D&B Properties to share the developer's full deck and contact me via WhatsApp / phone / email.
              </span>
            </label>
            {errors.consent && <div className="errtxt">{errors.consent}</div>}
          </div>
          <div className="form-actions">
            <button className="btn btn--ghost on-light" onClick={() => setStep(1)}>← Back</button>
            <button className="btn btn--gold" onClick={submit}>
              Register Interest <span className="arr">→</span>
            </button>
            <span className="note">
              Goal: <code style={{ fontFamily: "var(--mono)", fontSize: 11 }}>{L.cta.goal}</code> · Lead routed to off-plan CRM queue.
            </span>
          </div>
        </React.Fragment>
      )}
    </div>
  );
};

// ─── CTA section (full-bleed Register Interest) ───────────────────
window.CTASection = function CTASection({ L }) {
  return (
    <section id="register" className="cta-section">
      <div className="shell">
        <div className="cta-grid">
          <div className="fade-up">
            <div className="chapter-num num" style={{ marginBottom: "1.25rem" }}>
              <span className="bar"></span>{L.cta.eyebrow}
            </div>
            <h2 className="section-title">{window.renderTokens(L.cta.title)}</h2>
            <p className="lede muted" style={{ marginTop: "1.5rem" }}>{L.cta.body}</p>
            <ul style={{ listStyle: "none", padding: 0, marginTop: "2rem", display: "flex", flexDirection: "column", gap: 14 }}>
              {[
                ["Developer-direct payment plan", "No middleman, no marked-up tiers."],
                ["RERA-registered consultant", "ORN 16576 · verified on PropertyFinder broker profile."],
                ["End-to-end multilingual support", "EN · AR · DE · RU · ZH from enquiry through handover."],
                ["Re-sale exit thinking, day one", "Modelled against community absorption and listing data."],
              ].map(([t, s], i) => (
                <li key={i} style={{ display: "grid", gridTemplateColumns: "20px 1fr", gap: 14 }}>
                  <span style={{ width: 12, height: 12, background: "var(--gold)", borderRadius: "50%", marginTop: 6 }}></span>
                  <div>
                    <div style={{ fontFamily: "var(--serif)", fontSize: "1.2rem", letterSpacing: "-0.005em" }}>{t}</div>
                    <div style={{ fontSize: 13.5, color: "var(--muted)" }}>{s}</div>
                  </div>
                </li>
              ))}
            </ul>
          </div>
          <div className="fade-up">
            <window.RegisterForm L={L} />
          </div>
        </div>
      </div>
    </section>
  );
};

// ─── Modal (mini register form) ───────────────────────────────────
window.RegisterModal = function RegisterModal({ open, onClose, L }) {
  useEffect(() => {
    function onKey(e) { if (e.key === "Escape") onClose(); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div className={`modal-bg ${open ? "is-open" : ""}`} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ position: "relative" }}>
        <button className="close" onClick={onClose} aria-label="Close">×</button>
        <div className="eyebrow" style={{ marginBottom: 10 }}>
          <span className="gold-dot"></span>{window.PROJECT.codename} · Register Interest
        </div>
        <window.RegisterForm L={L} compact />
      </div>
    </div>
  );
};

// ─── WhatsApp FAB ──────────────────────────────────────────────────
window.WhatsAppFAB = function WhatsAppFAB({ L, show }) {
  if (!show) return null;
  return (
    <a
      className="wa-fab"
      href="https://wa.me/+97180032632"
      target="_blank"
      rel="noopener"
      onClick={() => console.info("[goal] whatsapp_click")}
    >
      <span className="ic">W</span>
      <span>
        <span className="sub">{L.waFab.sub}</span>
        {L.waFab.main}
      </span>
    </a>
  );
};

// ─── Footer ────────────────────────────────────────────────────────
window.Footer = function Footer({ L }) {
  return (
    <footer className="footer">
      <div className="shell">
        <div className="footer__main">
          <div className="footer__brand">
            <div className="mark"><window.LogoInline /></div>
            <p>
              D&B Properties is a Dubai real-estate brokerage founded in 2015, the flagship of Bayari Holding.
              Full-service across buy, rent, off-plan, commercial, holiday homes, property management and
              investment advisory. RERA ORN 16576 · verified.
            </p>
            <p style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "rgba(251,250,246,0.4)" }}>
              Floor 13, Blue Bay Tower · Business Bay, Dubai
            </p>
          </div>
          <div className="footer__col">
            <h5>This launch</h5>
            <ul>
              <li><a href="#project">Project overview</a></li>
              <li><a href="#residences">Residences</a></li>
              <li><a href="#amenities">Amenities</a></li>
              <li><a href="#location">Location</a></li>
              <li><a href="#gallery">Gallery</a></li>
              <li><a href="#register">Register interest</a></li>
            </ul>
          </div>
          <div className="footer__col">
            <h5>D&B Properties</h5>
            <ul>
              <li><a>Buy</a></li>
              <li><a>Rent</a></li>
              <li><a>Off-plan</a></li>
              <li><a>Commercial</a></li>
              <li><a>Holiday homes</a></li>
              <li><a>Free valuation</a></li>
              <li><a>List your property</a></li>
            </ul>
          </div>
          <div className="footer__col">
            <h5>Contact</h5>
            <ul>
              <li><a>+971 4 871 9200</a></li>
              <li><a>800 32632 · toll-free</a></li>
              <li><a>+971 56 520 3470</a></li>
              <li><a>inquiry@dandbdubai.com</a></li>
              <li><a>WhatsApp</a></li>
            </ul>
          </div>
        </div>
        <div className="footer__legal">
          <div>© 2026 D&B Properties · Bayari Holding · RERA ORN 16576</div>
          <div className="src">
            <span className="badge">Template Demo</span>
            <span>Microsite Layer · Not the corporate site</span>
          </div>
        </div>
      </div>
    </footer>
  );
};
