// Forms + Modals + Lead docks
const { useState: useStateF, useEffect: useEffectF } = React;

function RegisterInterestSection({ lang }) {
  const t = I18N[lang];
  const [data, setData] = useStateF({
    name: "", phone: "", email: "", residence: ["Two-bedroom"], timeline: "0-3 months",
    nationality: "United Arab Emirates",
  });
  const [errors, setErrors] = useStateF({});
  const [submitted, setSubmitted] = useStateF(false);

  const toggleRes = (key) => {
    const cur = data.residence;
    const next = cur.includes(key) ? cur.filter(k => k !== key) : [...cur, key];
    setData({ ...data, residence: next });
  };

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!data.name.trim()) errs.name = "Required";
    if (!data.phone.trim() || data.phone.replace(/\D/g, "").length < 7) errs.phone = "Enter a valid phone";
    if (!/^\S+@\S+\.\S+$/.test(data.email)) errs.email = "Enter a valid email";
    setErrors(errs);
    if (Object.keys(errs).length === 0) {
      setSubmitted(true);
    }
  };

  return (
    <section className="section register" id="register" data-screen-label="11 Register">
      <div className="container">
        <div className="register-inner">
          <div className="register-copy">
            <span className="section-num" style={{ color: "var(--muted-d)" }}>07 — Get in</span>
            <h2 className="display">
              The first <em>tranche</em> will go to people on this list.
            </h2>
            <p>
              Specifications, floor plates, payment plans and final pricing are with the
              developer for sign-off. Register and we'll send the private brochure
              48 hours ahead of public release — and a viewing slot reserved in your name.
            </p>
            <div className="agent-card">
              <div className="ph">LH</div>
              <div>
                <h6>Louis Harding</h6>
                <div className="role">Off-plan launch lead · Confirm current</div>
                <div className="links">
                  <a href="https://wa.me/97144090999"><Icons.WhatsApp /></a>
                  <a href="tel:+97144081000"><Icons.Phone /></a>
                  <a href="mailto:info@bhomes.com"><Icons.Mail /></a>
                </div>
              </div>
            </div>
          </div>
          <div>
            {submitted ? (
              <div className="form-success">
                <h3>You're on the list.</h3>
                <p>
                  We'll be in touch within one business day — and we'll send the private
                  brochure 48 hours before public release. Check your inbox for confirmation.
                </p>
                <div style={{ display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap" }}>
                  <a className="btn btn-primary" href="https://wa.me/97144090999" target="_blank" rel="noopener">
                    <span style={{ width: 14, height: 14, display: "inline-flex" }}><Icons.WhatsApp /></span>
                    Continue on WhatsApp
                  </a>
                  <button className="btn btn-outline" onClick={() => { setSubmitted(false); setData({ ...data, name: "", phone: "", email: "" }); }}>
                    Submit another
                  </button>
                </div>
              </div>
            ) : (
              <form className="form-card" onSubmit={submit} noValidate>
                <div className="step">Register interest — 2 minutes</div>
                <h3>Tell us a little about you.</h3>
                <div className="field-row">
                  <div className="field">
                    <label htmlFor="ri-name">Full name *</label>
                    <input id="ri-name" className={errors.name ? "error" : ""}
                      value={data.name} onChange={e => setData({ ...data, name: e.target.value })} />
                    {errors.name && <div className="err">{errors.name}</div>}
                  </div>
                  <div className="field">
                    <label htmlFor="ri-phone">Phone (international) *</label>
                    <input id="ri-phone" className={errors.phone ? "error" : ""}
                      placeholder="+971…"
                      value={data.phone} onChange={e => setData({ ...data, phone: e.target.value })} />
                    {errors.phone && <div className="err">{errors.phone}</div>}
                  </div>
                </div>
                <div className="field-row">
                  <div className="field">
                    <label htmlFor="ri-email">Email *</label>
                    <input id="ri-email" type="email" className={errors.email ? "error" : ""}
                      value={data.email} onChange={e => setData({ ...data, email: e.target.value })} />
                    {errors.email && <div className="err">{errors.email}</div>}
                  </div>
                  <div className="field">
                    <label htmlFor="ri-nat">Nationality</label>
                    <select id="ri-nat" value={data.nationality} onChange={e => setData({ ...data, nationality: e.target.value })}>
                      <option>United Arab Emirates</option>
                      <option>United Kingdom</option>
                      <option>Russia</option>
                      <option>China (incl. HK)</option>
                      <option>India</option>
                      <option>Saudi Arabia</option>
                      <option>Other GCC</option>
                      <option>Other</option>
                    </select>
                  </div>
                </div>

                <div className="field" style={{ marginTop: 8 }}>
                  <label>Residence interest (any)</label>
                  <div className="checkbox-row">
                    {["One-bedroom", "Two-bedroom", "Three-bedroom", "Four-bedroom · penthouse"].map(k => (
                      <label key={k} className={data.residence.includes(k) ? "on" : ""}>
                        <input type="checkbox" checked={data.residence.includes(k)} onChange={() => toggleRes(k)} />
                        {k}
                      </label>
                    ))}
                  </div>
                </div>

                <div className="field">
                  <label htmlFor="ri-time">Decision timeline</label>
                  <select id="ri-time" value={data.timeline} onChange={e => setData({ ...data, timeline: e.target.value })}>
                    <option>0–3 months</option>
                    <option>3–6 months</option>
                    <option>6–12 months</option>
                    <option>Exploratory</option>
                  </select>
                </div>

                <p className="consent">
                  By submitting you agree to be contacted by a Betterhomes consultant about
                  this launch. We don't share your details, and you can opt out at any time.
                </p>
                <div className="form-actions">
                  <button type="submit" className="btn btn-primary">{t.register}</button>
                  <button type="button" className="btn btn-outline" style={{ borderColor: "rgba(255,255,255,0.4)", color: "var(--paper)" }}>
                    <span style={{ width: 14, height: 14, display: "inline-flex" }}><Icons.Download /></span>
                    {t.brochure}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Book Viewing Modal (3-step) ----------
function BookViewingModal({ open, onClose }) {
  const [step, setStep] = useStateF(0);
  const [pick, setPick] = useStateF({ date: null, time: null, name: "", phone: "", email: "", channel: "in-person" });
  const [errors, setErrors] = useStateF({});
  const [done, setDone] = useStateF(false);

  useEffectF(() => {
    if (!open) { setStep(0); setDone(false); setPick({ date: null, time: null, name: "", phone: "", email: "", channel: "in-person" }); setErrors({}); }
  }, [open]);

  if (!open) return null;

  const today = new Date();
  const dates = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    return d;
  });
  const weekdayNames = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  const times = ["10:00", "11:00", "12:00", "14:00", "15:00", "16:00", "17:00", "18:00"];

  const next = () => {
    if (step === 0) {
      const errs = {};
      if (!pick.date) errs.date = "Pick a date";
      if (!pick.time) errs.time = "Pick a time";
      setErrors(errs);
      if (Object.keys(errs).length) return;
    }
    if (step === 1) {
      const errs = {};
      if (!pick.name.trim()) errs.name = "Required";
      if (!pick.phone.trim()) errs.phone = "Required";
      if (!/^\S+@\S+\.\S+$/.test(pick.email)) errs.email = "Valid email required";
      setErrors(errs);
      if (Object.keys(errs).length) return;
    }
    if (step < 2) { setStep(step + 1); setErrors({}); }
    else { setDone(true); }
  };

  return (
    <div className="modal-scrim" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="bv-title">
        <div className="modal-head">
          <h3 id="bv-title">{done ? "Viewing booked" : "Book a viewing"}</h3>
          <button className="modal-close" onClick={onClose} aria-label="Close">
            <span style={{ width: 18, height: 18, display: "inline-flex" }}><Icons.X /></span>
          </button>
        </div>
        <div className="modal-body">
          {!done && (
            <div className="modal-progress">
              {[0, 1, 2].map(i => <span key={i} className={"seg " + (i <= step ? "on" : "")} />)}
            </div>
          )}

          {done ? (
            <div style={{ textAlign: "center", padding: "24px 8px 8px" }}>
              <div style={{ width: 56, height: 56, margin: "0 auto 18px", borderRadius: "50%", background: "var(--bronze-soft)", color: "var(--bronze-2)", display: "grid", placeItems: "center" }}>
                <span style={{ width: 24, height: 24, display: "inline-flex" }}><Icons.Calendar /></span>
              </div>
              <h3 style={{ fontFamily: "var(--font-display)", fontSize: 26, margin: "0 0 6px", fontWeight: 400 }}>
                {pick.date && pick.date.toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" })} · {pick.time}
              </h3>
              <p style={{ color: "var(--muted)", maxWidth: 380, margin: "0 auto 20px" }}>
                You'll receive a calendar invite at <strong style={{ color: "var(--ink)" }}>{pick.email}</strong>.
                A consultant will WhatsApp you 24 hours before to confirm.
              </p>
              <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
                <button className="btn btn-primary" onClick={onClose}>Done</button>
                <a className="btn btn-outline" href="https://wa.me/97144090999"><Icons.WhatsApp /> WhatsApp now</a>
              </div>
            </div>
          ) : step === 0 ? (
            <>
              <div className="step">Step 1 of 3 · Pick a slot</div>
              <h3>Choose a date</h3>
              <div className="date-grid">
                {dates.map((d, i) => (
                  <div key={i}
                    className={"date-pill " + (pick.date && pick.date.toDateString() === d.toDateString() ? "on" : "")}
                    onClick={() => setPick({ ...pick, date: d })}>
                    <div className="d">{d.getDate()}</div>
                    <div className="w">{weekdayNames[d.getDay()]}</div>
                  </div>
                ))}
              </div>
              {errors.date && <div className="err">{errors.date}</div>}
              <h3 style={{ marginTop: 24 }}>Choose a time</h3>
              <div className="time-grid">
                {times.map(tm => (
                  <div key={tm} className={"time-pill " + (pick.time === tm ? "on" : "")}
                    onClick={() => setPick({ ...pick, time: tm })}>{tm}</div>
                ))}
              </div>
              {errors.time && <div className="err">{errors.time}</div>}
              <div className="checkbox-row" style={{ marginTop: 18 }}>
                {["in-person", "video walkthrough"].map(ch => (
                  <label key={ch} className={pick.channel === ch ? "on" : ""}>
                    <input type="radio" name="ch" checked={pick.channel === ch} onChange={() => setPick({ ...pick, channel: ch })} />
                    {ch === "in-person" ? "In-person · sales gallery" : "Video walkthrough"}
                  </label>
                ))}
              </div>
            </>
          ) : step === 1 ? (
            <>
              <div className="step">Step 2 of 3 · Your details</div>
              <h3>Who should we expect?</h3>
              <div className="field">
                <label>Full name *</label>
                <input className={errors.name ? "error" : ""} value={pick.name} onChange={e => setPick({ ...pick, name: e.target.value })} />
                {errors.name && <div className="err">{errors.name}</div>}
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Phone *</label>
                  <input className={errors.phone ? "error" : ""} value={pick.phone} placeholder="+971…" onChange={e => setPick({ ...pick, phone: e.target.value })} />
                  {errors.phone && <div className="err">{errors.phone}</div>}
                </div>
                <div className="field">
                  <label>Email *</label>
                  <input className={errors.email ? "error" : ""} value={pick.email} type="email" onChange={e => setPick({ ...pick, email: e.target.value })} />
                  {errors.email && <div className="err">{errors.email}</div>}
                </div>
              </div>
            </>
          ) : (
            <>
              <div className="step">Step 3 of 3 · Confirm</div>
              <h3>Confirm your viewing</h3>
              <div style={{ border: "1px solid var(--line)", padding: 20, marginBottom: 16 }}>
                <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "10px 16px", fontSize: 14 }}>
                  <div style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" }}>Project</div>
                  <div>Butterfly Towers · Business Bay</div>
                  <div style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" }}>Date</div>
                  <div>{pick.date && pick.date.toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", year: "numeric" })}</div>
                  <div style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" }}>Time</div>
                  <div>{pick.time}</div>
                  <div style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" }}>Format</div>
                  <div style={{ textTransform: "capitalize" }}>{pick.channel}</div>
                  <div style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" }}>Name</div>
                  <div>{pick.name}</div>
                  <div style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase" }}>Contact</div>
                  <div>{pick.phone} · {pick.email}</div>
                </div>
              </div>
              <p className="consent">A consultant will contact you within one business day to confirm location, parking and what to bring.</p>
            </>
          )}

          {!done && (
            <div className="form-actions" style={{ justifyContent: "space-between", marginTop: 20 }}>
              {step > 0 ? (
                <button className="btn btn-outline" onClick={() => setStep(step - 1)}>Back</button>
              ) : <span />}
              <button className="btn btn-primary" onClick={next}>
                {step === 2 ? "Confirm viewing" : "Continue"}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- Lead docks ----------
function LeadBar({ visible, onBookViewing, onRegister }) {
  const t = I18N["en"];
  return (
    <div className={"lead-bar " + (visible ? "visible" : "")}>
      <div>
        <div className="lab">Butterfly Towers</div>
        <div className="price">Pre-launch · <em>POA</em></div>
      </div>
      <div className="divider-v"></div>
      <div className="actions">
        <button className="btn btn-ghost" onClick={onBookViewing}>{t.bookView}</button>
        <button className="btn btn-primary" onClick={onRegister}>{t.register}</button>
        <a className="btn btn-ghost" href="https://wa.me/97144090999" target="_blank" rel="noopener" aria-label="WhatsApp">
          <span style={{ width: 14, height: 14, display: "inline-flex" }}><Icons.WhatsApp /></span>
        </a>
      </div>
    </div>
  );
}

function LeadRail({ visible, onBookViewing, onRegister }) {
  return (
    <div className={"lead-rail " + (visible ? "visible" : "")} aria-label="Quick lead actions">
      <button onClick={onBookViewing} title="Book a viewing">
        <span style={{ width: 20, height: 20, display: "inline-flex" }}><Icons.Calendar /></span>
      </button>
      <button onClick={onRegister} title="Register interest">
        <span style={{ width: 20, height: 20, display: "inline-flex" }}><Icons.Mail /></span>
      </button>
      <a className="whatsapp" href="https://wa.me/97144090999" target="_blank" rel="noopener" title="WhatsApp"
         style={{ width: 54, height: 54, borderRadius: "50%", display: "grid", placeItems: "center" }}>
        <span style={{ width: 22, height: 22, display: "inline-flex" }}><Icons.WhatsApp /></span>
      </a>
    </div>
  );
}

Object.assign(window, { RegisterInterestSection, BookViewingModal, LeadBar, LeadRail });
