// app.jsx — Cala Del Mar microsite root

const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

// ─── Register interest form ────────────────────────────────────────────────
function RegisterSection({ project, contact }) {
  const [form, setForm] = useStateA({
    name: "", email: "", phone: "", country: "", residency: "Investor",
    timing: "Within 3 months", consent: false,
  });
  const [errors, setErrors] = useStateA({});
  const [sent, setSent] = useStateA(false);
  const [refNo] = useStateA(() => "EP-" + Math.random().toString(36).slice(2, 7).toUpperCase());

  const set = (k) => (e) => {
    const v = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    setForm((f) => ({ ...f, [k]: v }));
    if (errors[k]) setErrors((er) => { const n = { ...er }; delete n[k]; return n; });
  };

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = "Required";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) er.email = "Valid email required";
    if (!form.phone.trim() || form.phone.replace(/\D/g, "").length < 7) er.phone = "Phone required";
    if (!form.consent) er.consent = "Required";
    setErrors(er);
    if (Object.keys(er).length) return;
    // Simulated submission — would post to CRM webhook in production
    setTimeout(() => setSent(true), 320);
  };

  return (
    <section id="register" style={{ marginTop: 40 }}>
      <div className="reg-wrap">
        <div className="reg-left">
          <span className="eyebrow">§ 08 · Register Interest</span>
          <h2 className="display">A private viewing,<br /><em>at your pace.</em></h2>
          <p>
            Register your details to receive the full Cala Del Mar brochure, current floor-plan
            availability, and an invitation to a private viewing at the Burlington Tower presentation
            suite or by virtual walkthrough.
          </p>
          <div className="channels">
            <div className="ch-row"><span>Phone</span><b>{contact.phone}</b></div>
            <div className="ch-row"><span>Toll-free (UAE)</span><b>{contact.tollfree}</b></div>
            <div className="ch-row"><span>WhatsApp</span><b>{contact.whatsapp}</b></div>
            <div className="ch-row"><span>Email</span><b>{contact.email}</b></div>
          </div>
        </div>
        <div className="reg-right">
          {!sent ? (
            <form onSubmit={submit} noValidate>
              <div className={`field ${errors.name ? "err" : ""}`}>
                <label htmlFor="f-name">Full Name</label>
                <input id="f-name" value={form.name} onChange={set("name")} autoComplete="name" />
                {errors.name && <span className="err-msg">{errors.name}</span>}
              </div>
              <div className="field-row">
                <div className={`field ${errors.email ? "err" : ""}`}>
                  <label htmlFor="f-email">Email</label>
                  <input id="f-email" type="email" value={form.email} onChange={set("email")} autoComplete="email" />
                  {errors.email && <span className="err-msg">{errors.email}</span>}
                </div>
                <div className={`field ${errors.phone ? "err" : ""}`}>
                  <label htmlFor="f-phone">Phone (incl. country code)</label>
                  <input id="f-phone" value={form.phone} onChange={set("phone")} autoComplete="tel" placeholder="+971…" />
                  {errors.phone && <span className="err-msg">{errors.phone}</span>}
                </div>
              </div>
              <div className="field-row">
                <div className="field">
                  <label htmlFor="f-country">Country of Residence</label>
                  <select id="f-country" value={form.country} onChange={set("country")}>
                    <option value="">— Select —</option>
                    <option>United Arab Emirates</option>
                    <option>Saudi Arabia</option>
                    <option>Kuwait</option>
                    <option>United Kingdom</option>
                    <option>India</option>
                    <option>China</option>
                    <option>Russia</option>
                    <option>France</option>
                    <option>Germany</option>
                    <option>Other</option>
                  </select>
                </div>
                <div className="field">
                  <label htmlFor="f-res">Buyer Profile</label>
                  <select id="f-res" value={form.residency} onChange={set("residency")}>
                    <option>End-user</option>
                    <option>Investor</option>
                    <option>Broker</option>
                  </select>
                </div>
              </div>
              <div className="field">
                <label htmlFor="f-timing">Purchase Timeline</label>
                <select id="f-timing" value={form.timing} onChange={set("timing")}>
                  <option>Within 30 days</option>
                  <option>Within 3 months</option>
                  <option>Within 6 months</option>
                  <option>Researching</option>
                </select>
              </div>
              <div className="consent">
                <input id="f-consent" type="checkbox" checked={form.consent} onChange={set("consent")} />
                <label htmlFor="f-consent">
                  I consent to Ellington Properties contacting me about Cala Del Mar and related launches.
                  No automated decisions; opt-out at any time.
                  {errors.consent && <span style={{ color: "#D97757", marginLeft: 8 }}>· Required</span>}
                </label>
              </div>
              <button type="submit" className="reg-submit">Submit Registration →</button>
              <p style={{ marginTop: 18, fontFamily: "var(--mono-font)", fontSize: 10, letterSpacing: "0.12em", color: "rgba(241,236,223,.45)", textTransform: "uppercase" }}>
                Ref · {refNo} · Brochure will be sent to the email above
              </p>
            </form>
          ) : (
            <div className="reg-success">
              <span className="eyebrow" style={{ color: "rgba(241,236,223,.6)" }}>Registration received</span>
              <h3 className="display" style={{ marginTop: 14 }}>Thank you, {form.name.split(" ")[0] || "—"}.</h3>
              <p>
                Your registration <b style={{ color: "#F1ECDF" }}>{refNo}</b> has been recorded. The Cala Del Mar
                brochure is on its way to <b style={{ color: "#F1ECDF" }}>{form.email}</b>. A senior consultant
                will be in touch within one working day to confirm a private viewing.
              </p>
              <p style={{ marginTop: 24, color: "rgba(241,236,223,.6)", fontSize: 13 }}>
                Prefer to talk now? WhatsApp <b style={{ color: "#F1ECDF" }}>{contact.whatsapp}</b> or call <b style={{ color: "#F1ECDF" }}>{contact.phone}</b>.
              </p>
              <button className="reg-submit" style={{ marginTop: 28 }} onClick={() => { setSent(false); setForm({ name: "", email: "", phone: "", country: "", residency: "Investor", timing: "Within 3 months", consent: false }); }}>
                ← Submit Another
              </button>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ─── Footer ────────────────────────────────────────────────────────────────
function Footer({ contact, socials }) {
  return (
    <footer>
      <div className="wrap">
        <div className="foot">
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
              <EGNMark size={26} />
              <span style={{ fontFamily: "var(--body-font)", fontSize: 13, letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 500 }}>Ellington</span>
            </div>
            <p className="brand display">Live in Design.</p>
            <p className="addr">
              {contact.hq.map((l, i) => (<React.Fragment key={i}>{l}<br /></React.Fragment>))}
            </p>
            <p className="addr" style={{ marginTop: 12 }}>
              {contact.phone} · Toll-free {contact.tollfree}<br />
              WhatsApp {contact.whatsapp}<br />
              {contact.email} · {contact.careEmail}<br />
              <span style={{ fontFamily: "var(--mono-font)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--soft)" }}>
                {contact.hours}
              </span>
            </p>
          </div>
          <div>
            <h5>Project</h5>
            <a href="#design">Design &amp; Architecture</a>
            <a href="#residences">Residences</a>
            <a href="#amenities">Amenities</a>
            <a href="#location">Location</a>
            <a href="#gallery">Gallery</a>
            <a href="#register">Register Interest</a>
          </div>
          <div>
            <h5>Ellington</h5>
            <a href="#">About</a>
            <a href="#portfolio">Portfolio</a>
            <a href="#">Leadership</a>
            <a href="#">Awards</a>
            <a href="#">Careers</a>
            <a href="#">Press</a>
          </div>
          <div>
            <h5>Social</h5>
            {socials.map((s) => (
              <a key={s.label} href={s.url} target="_blank" rel="noopener noreferrer">
                {s.label} <span style={{ fontFamily: "var(--mono-font)", fontSize: 10, marginLeft: 6, color: "var(--soft)", letterSpacing: "0.16em" }}>↗</span>
              </a>
            ))}
          </div>
        </div>
        <div className="foot-bot">
          <span>© {new Date().getFullYear()} Ellington Properties · Part of the Ellington Group</span>
          <span>Project statuses · RERA/DLD confirmed per release · No prices · POA</span>
          <span>EN · AR · RU · ZH · FR</span>
        </div>
      </div>
    </footer>
  );
}

// ─── WhatsApp FAB ──────────────────────────────────────────────────────────
function WhatsAppFab({ number }) {
  const href = `https://wa.me/${number.replace(/\D/g, "")}`;
  return (
    <a className="wa" href={href} target="_blank" rel="noopener noreferrer" aria-label="Chat on WhatsApp" title="Chat on WhatsApp">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
        <path d="M3 21l2-6a8 8 0 1 1 4 4l-6 2z" />
        <path d="M8.5 10c.5 1.5 1.5 3 3.5 4s3.5 1 4 .5l1-1 2.5 1c-.5 1.5-2 2.5-3.5 2.5-2 0-5-1-7-3s-3-5-3-7c0-1.5 1-3 2.5-3.5l1 2.5-1 1c-.5.5-.5 1 0 2.5z" />
      </svg>
    </a>
  );
}

// ─── App root ──────────────────────────────────────────────────────────────
function App() {
  const D = window.DATA;
  const [t, setTweak] = useTweaks(window.CALA_DEFAULTS);
  const [locale, setLocale] = useStateA("EN");
  const [lbxIndex, setLbxIndex] = useStateA(null);

  // Apply tweaks to root via data-attrs
  useEffectA(() => {
    document.documentElement.setAttribute("data-palette", t.palette);
    document.documentElement.setAttribute("data-type", t.typePairing);
    document.documentElement.setAttribute("data-density", t.density);
  }, [t.palette, t.typePairing, t.density]);

  const scrollToRegister = () => {
    const el = document.getElementById("register");
    if (el) window.scrollTo({ top: el.offsetTop - 40, behavior: "smooth" });
  };
  const fakeBrochure = () => {
    alert("In production: triggers a gated brochure download (email-gate → PDF).\n\nFor this prototype, please use the Register Interest form below.");
    scrollToRegister();
  };

  return (
    <>
      <Nav
        onRegister={scrollToRegister}
        locale={locale}
        setLocale={setLocale}
        locales={D.locales}
      />
      <Hero
        project={D.project}
        motion={t.heroMotion}
        onRegister={scrollToRegister}
        onBrochure={fakeBrochure}
      />
      <PullQuote project={D.project} />
      <DesignSection project={D.project} />
      <Residences project={D.project} />
      <Amenities project={D.project} />
      <Location project={D.project} />
      <Gallery project={D.project} onOpen={setLbxIndex} />
      <TrustStrip />
      <Portfolio items={D.portfolio} />
      <RegisterSection project={D.project} contact={D.contact} />
      <Footer contact={D.contact} socials={D.socials} />
      <WhatsAppFab number={D.contact.whatsapp} />

      {lbxIndex !== null && (
        <Lightbox
          items={D.project.gallery}
          index={lbxIndex}
          onClose={() => setLbxIndex(null)}
          onPrev={() => setLbxIndex((i) => (i - 1 + D.project.gallery.length) % D.project.gallery.length)}
          onNext={() => setLbxIndex((i) => (i + 1) % D.project.gallery.length)}
        />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette" />
        <TweakRadio
          label="Mood"
          value={t.palette}
          options={["light", "dark"]}
          onChange={(v) => setTweak("palette", v)}
        />
        <TweakSection label="Typography" />
        <TweakRadio
          label="Display face"
          value={t.typePairing}
          options={["cormorant", "fraunces", "grotesque"]}
          onChange={(v) => setTweak("typePairing", v)}
        />
        <TweakSection label="Hero" />
        <TweakRadio
          label="Motion"
          value={t.heroMotion}
          options={["static", "kenburns"]}
          onChange={(v) => setTweak("heroMotion", v)}
        />
      </TweaksPanel>
    </>
  );
}

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