/* Sobha Realty microsite — interactive forms + modals */

const FD = window.SR_DATA;

/* ============================================================
   Modal scaffolding
   ============================================================ */
function Modal({ children, onClose, wide }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.documentElement.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.documentElement.style.overflow = "";
    };
  }, [onClose]);
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal"
           style={ wide ? { maxWidth: 880, padding:0 } : {} }
           onClick={(e)=>e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Close">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M3 3L13 13M13 3L3 13" stroke="currentColor" strokeWidth="1.5" />
          </svg>
        </button>
        {children}
      </div>
    </div>
  );
}

/* ============================================================
   Common form atoms
   ============================================================ */
function Field({ label, children, full }) {
  return (
    <div className="field" style={ full ? { gridColumn: "1 / -1" } : {} }>
      <label>{label}</label>
      {children}
    </div>
  );
}

function PhoneField({ value, onChange, dialCode, setDial }) {
  return (
    <div className="field-tel">
      <div className="field">
        <label>Code</label>
        <select value={dialCode} onChange={(e)=>setDial(e.target.value)}>
          {FD.dialCodes.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
      </div>
      <div className="field">
        <label>Phone</label>
        <input type="tel" value={value} onChange={(e)=>onChange(e.target.value)} placeholder="50 123 4567" />
      </div>
    </div>
  );
}

function RouteChooser({ value, onChange }) {
  return (
    <div className="route-row" role="radiogroup" aria-label="Enquiry route">
      {FD.routes.map(r => (
        <label key={r.id} className={value===r.id?"checked":""}>
          <input type="radio" name="route" checked={value===r.id} onChange={()=>onChange(r.id)} />
          <span className="rk">{r.k}</span>
          <span className="rv">{r.v}</span>
        </label>
      ))}
    </div>
  );
}

/* ============================================================
   Register interest — multi-step
   ============================================================ */
function RegisterFlow({ onClose, defaultRoute = "sales" }) {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    route: defaultRoute,
    community: FD.featured.name,
    residence: "2 Bedroom",
    budget: "AED 2M – 5M",
    name: "",
    email: "",
    phone: "",
    dial: "+971",
    country: "United Arab Emirates",
    contactPref: "WhatsApp",
    source: "Campaign · Sobha One",
    timing: "0–3 months",
    notes: "",
    consent: false,
    marketing: true
  });
  const upd = (k,v) => setForm(prev => ({...prev, [k]:v}));

  const steps = [
    { name:"Route",      desc:"Pick your enquiry channel" },
    { name:"Interest",   desc:"Community & residence" },
    { name:"Contact",    desc:"How we reach you" },
    { name:"Review",     desc:"Confirm & send" }
  ];
  const last = step === steps.length - 1;

  const next = () => setStep(s => Math.min(s+1, steps.length));
  const prev = () => setStep(s => Math.max(s-1, 0));

  const submit = () => setStep(steps.length); // success
  const sent = step === steps.length;

  return (
    <Modal onClose={onClose}>
      <div className="modal-inner">
        {!sent && (
          <>
            <div className="eyebrow">Register interest · Sobha One</div>
            <h3 style={{marginTop:14}}>{steps[step].name}.</h3>
            <p className="sub">{steps[step].desc}.</p>

            <div className="step-meta">
              <span>Step <b>{step+1}</b> / {steps.length}</span>
              <span>Approx. 60 seconds</span>
            </div>
            <div className="steps">
              {steps.map((_, i) => (
                <div key={i} className={"step-dot " + (i<step?"done": (i===step?"current":""))}></div>
              ))}
            </div>

            {/* Step 0 — route */}
            {step === 0 && (
              <>
                <RouteChooser value={form.route} onChange={(v)=>upd("route", v)} />
                <p className="body" style={{fontSize:12.5, color:"var(--muted)"}}>
                  Sales: <b>{FD.phones.sales}</b> · Customer & WhatsApp: <b>{FD.phones.customer}</b>.
                  We never route enquiries to the careers line.
                </p>
              </>
            )}

            {/* Step 1 — interest */}
            {step === 1 && (
              <>
                <div className="form-row">
                  <Field label="Community">
                    <select value={form.community} onChange={(e)=>upd("community", e.target.value)}>
                      {FD.communities.map(c => <option key={c.slug}>{c.name}</option>)}
                    </select>
                  </Field>
                  <Field label="Residence type">
                    <select value={form.residence} onChange={(e)=>upd("residence", e.target.value)}>
                      {FD.residences.map(r => <option key={r.id}>{r.label}</option>)}
                      <option>Villa</option>
                      <option>Penthouse</option>
                    </select>
                  </Field>
                </div>
                <div className="form-row">
                  <Field label="Indicative budget">
                    <select value={form.budget} onChange={(e)=>upd("budget", e.target.value)}>
                      <option>Under AED 2M</option>
                      <option>AED 2M – 5M</option>
                      <option>AED 5M – 10M</option>
                      <option>AED 10M – 25M</option>
                      <option>Above AED 25M</option>
                    </select>
                  </Field>
                  <Field label="Timing">
                    <select value={form.timing} onChange={(e)=>upd("timing", e.target.value)}>
                      <option>0–3 months</option>
                      <option>3–6 months</option>
                      <option>6–12 months</option>
                      <option>Just researching</option>
                    </select>
                  </Field>
                </div>
                <Field label="Anything specific?" full>
                  <textarea value={form.notes} onChange={(e)=>upd("notes",e.target.value)}
                            placeholder="Aspect, level, floor plate, family size, second-home or investment…" />
                </Field>
              </>
            )}

            {/* Step 2 — contact */}
            {step === 2 && (
              <>
                <div className="form-row">
                  <Field label="Full name">
                    <input value={form.name} onChange={(e)=>upd("name", e.target.value)} placeholder="Your name" />
                  </Field>
                  <Field label="Email">
                    <input type="email" value={form.email} onChange={(e)=>upd("email", e.target.value)} placeholder="you@email.com" />
                  </Field>
                </div>
                <div className="form-row">
                  <PhoneField value={form.phone} onChange={(v)=>upd("phone",v)} dialCode={form.dial} setDial={(v)=>upd("dial",v)} />
                  <Field label="Country of residence">
                    <input value={form.country} onChange={(e)=>upd("country", e.target.value)} />
                  </Field>
                </div>
                <Field label="Preferred contact" full>
                  <div style={{display:"flex", gap:18, padding:"6px 0"}}>
                    {["WhatsApp","Phone","Email"].map(p => (
                      <label key={p} style={{display:"flex", gap:6, fontSize:13}}>
                        <input type="radio" name="pref"
                               checked={form.contactPref===p}
                               onChange={()=>upd("contactPref", p)} />
                        {p}
                      </label>
                    ))}
                  </div>
                </Field>
                <div className="checkbox" style={{marginTop:12}}>
                  <input type="checkbox" checked={form.consent} onChange={(e)=>upd("consent", e.target.checked)} />
                  <span>I consent to Sobha Realty processing my enquiry and contacting me. <a href="#" style={{textDecoration:"underline", color:"var(--ink)"}}>Privacy notice</a>.</span>
                </div>
                <div className="checkbox" style={{marginTop:10}}>
                  <input type="checkbox" checked={form.marketing} onChange={(e)=>upd("marketing", e.target.checked)} />
                  <span>Send me future Sobha campaign launches and look books.</span>
                </div>
              </>
            )}

            {/* Step 3 — review */}
            {step === 3 && (
              <div style={{
                border:"1px solid var(--border)",
                borderRadius:2,
                background:"var(--bg)",
                padding:24
              }}>
                <div className="fine" style={{marginBottom:14}}>Review · CRM payload</div>
                <ReviewLine k="Route"        v={FD.routes.find(r=>r.id===form.route).k} />
                <ReviewLine k="Community"    v={form.community} />
                <ReviewLine k="Residence"    v={form.residence} />
                <ReviewLine k="Budget"       v={form.budget} />
                <ReviewLine k="Timing"       v={form.timing} />
                <ReviewLine k="Name"         v={form.name || "—"} />
                <ReviewLine k="Email"        v={form.email || "—"} />
                <ReviewLine k="Phone"        v={(form.phone ? form.dial + " " + form.phone : "—")} />
                <ReviewLine k="Country"      v={form.country} />
                <ReviewLine k="Contact via"  v={form.contactPref} />
                <ReviewLine k="Source"       v={form.source} />
                <ReviewLine k="Notes"        v={form.notes || "—"} />
                <ReviewLine k="Consent"      v={form.consent ? "Granted" : "Required ↑"} flag={!form.consent} />
              </div>
            )}

            <div className="form-foot">
              <span className="privacy">
                We will route you to <b>{FD.routes.find(r=>r.id===form.route).k}</b> at Sobha Realty.
                Department emails confirmed at handover.
              </span>
              <div style={{display:"flex", gap:8}}>
                {step > 0 && <button className="btn btn-ghost" onClick={prev}>Back</button>}
                {!last && <button className="btn" onClick={next}>Continue <span className="arrow"></span></button>}
                {last && (
                  <button className="btn btn-primary"
                          onClick={submit}
                          disabled={!form.consent || !form.name || !form.email}>
                    Send enquiry <span className="arrow"></span>
                  </button>
                )}
              </div>
            </div>
          </>
        )}

        {sent && (
          <div className="success-pane">
            <div className="check">
              <svg viewBox="0 0 24 24" fill="none">
                <path d="M5 12.5L10 17L19 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <h3>Enquiry sent.</h3>
            <p>A Sobha Realty sales consultant will reach you on {form.contactPref.toLowerCase()} within one business day. The campaign source is logged for analytics.</p>
            <div className="ticket">Reference · SR-{Math.floor(Math.random()*900000+100000)}</div>
            <div style={{display:"flex", gap:10, justifyContent:"center", marginTop:16}}>
              <a className="btn btn-ghost" href={FD.phones.waLink} target="_blank" rel="noopener">Open WhatsApp</a>
              <button className="btn" onClick={onClose}>Close</button>
            </div>
            <div className="consent-note" style={{marginTop:20}}>
              UTM, locale and community slug captured. No commercial terms returned in this prototype.
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}

function ReviewLine({ k, v, flag }) {
  return (
    <div style={{
      display:"grid", gridTemplateColumns:"160px 1fr",
      gap:16, padding:"8px 0",
      borderBottom:"1px solid var(--border-soft)",
      fontSize:13
    }}>
      <span style={{
        fontFamily:"var(--mono)", fontSize:10.5, letterSpacing:".14em",
        textTransform:"uppercase", color:"var(--muted)"
      }}>{k}</span>
      <span style={{ color: flag ? "var(--signal)" : "var(--ink)" }}>{v}</span>
    </div>
  );
}

/* ============================================================
   Brochure gate
   ============================================================ */
function BrochureFlow({ onClose }) {
  const [sent, setSent] = React.useState(false);
  const [form, setForm] = React.useState({ name:"", email:"", phone:"", dial:"+971", consent:false });
  const upd = (k,v) => setForm(p => ({...p, [k]:v}));

  return (
    <Modal onClose={onClose} wide>
      <div className="brochure-modal">
        <div className="preview">
          <span className="pdf-badge">PDF · Concept look book</span>
          <img src="media/render-sobha-one-dusk.webp" alt="Sobha One brochure preview" />
          <div className="meta">
            <span>Brochure · Sobha One</span>
            <h4>Vertical garden,<br />Ras Al Khor.</h4>
          </div>
        </div>
        <div className="form-pane">
          {!sent && (
            <>
              <div className="eyebrow">Gated brochure</div>
              <h3 style={{marginTop:10}}>Download the<br />Sobha One look book.</h3>
              <p className="sub">
                A PDF concept book with renders, residences, and amenities. Final
                specifications and pricing are issued through the sales gallery.
              </p>

              <Field label="Full name" full>
                <input value={form.name} onChange={(e)=>upd("name", e.target.value)} placeholder="Your name" />
              </Field>
              <div className="form-row" style={{marginTop:12}}>
                <Field label="Email">
                  <input type="email" value={form.email} onChange={(e)=>upd("email", e.target.value)} placeholder="you@email.com" />
                </Field>
                <PhoneField value={form.phone} onChange={(v)=>upd("phone", v)} dialCode={form.dial} setDial={(v)=>upd("dial", v)} />
              </div>

              <div className="checkbox" style={{marginTop:16}}>
                <input type="checkbox" checked={form.consent} onChange={(e)=>upd("consent", e.target.checked)} />
                <span>I agree to receive the look book and follow-up from Sobha Realty.</span>
              </div>

              <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", marginTop:22, gap:12, flexWrap:"wrap"}}>
                <span className="fine">≈ 18 MB PDF · concept renders</span>
                <button className="btn btn-primary"
                        onClick={()=>setSent(true)}
                        disabled={!form.email || !form.consent}>
                  Send brochure <span className="arrow"></span>
                </button>
              </div>
              <div className="consent-note" style={{marginTop:18}}>
                Brochure subject and RERA-DLD status confirmed at handover.
              </div>
            </>
          )}

          {sent && (
            <div className="success-pane">
              <div className="check">
                <svg viewBox="0 0 24 24" fill="none">
                  <path d="M5 12.5L10 17L19 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>
              <h3>Check your inbox.</h3>
              <p>We've sent the Sobha One look book to <b>{form.email}</b>. Add <i>microsite@sobharealty.com</i> to your safe-senders.</p>
              <button className="btn" onClick={onClose}>Close</button>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}

/* ============================================================
   Private viewing — date + time picker
   ============================================================ */
function ViewingFlow({ onClose }) {
  const today = new Date();
  const days = [];
  for (let i=1; i<=7; i++){
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    days.push(d);
  }
  const dayLbl = (d) => ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()];
  const times = ["10:00","11:30","13:00","14:30","16:00","17:30"];

  const [day, setDay] = React.useState(2);
  const [time, setTime] = React.useState("11:30");
  const [where, setWhere] = React.useState("Sales Gallery · Sobha Hartland");
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [dial, setDial] = React.useState("+971");
  const [confirmed, setConfirmed] = React.useState(false);

  return (
    <Modal onClose={onClose}>
      <div className="modal-inner">
        {!confirmed && (
          <>
            <div className="eyebrow">Private viewing</div>
            <h3 style={{marginTop:10}}>Book a Sobha One viewing.</h3>
            <p className="sub">
              Pick a day and time. Our team confirms the slot on WhatsApp within the hour.
              Gallery hours [confirm with sales].
            </p>

            <Field label="Where" full>
              <select value={where} onChange={(e)=>setWhere(e.target.value)}>
                <option>Sales Gallery · Sobha Hartland</option>
                <option>PNCA / Development Office · Hartland II</option>
                <option>CRM & Collections · Hartland II</option>
                <option>Virtual · Zoom or Teams</option>
              </select>
            </Field>

            <div className="fine" style={{marginTop:20}}>Date · next 7 days</div>
            <div className="viewing-grid">
              {days.map((d, i) => (
                <button key={i}
                        type="button"
                        className={"day " + (i===day?"active":"")}
                        onClick={()=>setDay(i)}>
                  <div className="dow">{dayLbl(d)}</div>
                  <div className="dnum">{d.getDate()}</div>
                </button>
              ))}
            </div>

            <div className="fine" style={{marginTop:16}}>Time</div>
            <div className="time-grid">
              {times.map(tm => (
                <button key={tm} type="button"
                        className={tm===time?"active":""}
                        onClick={()=>setTime(tm)}>{tm}</button>
              ))}
            </div>

            <div className="form-row" style={{marginTop:18}}>
              <Field label="Full name">
                <input value={name} onChange={(e)=>setName(e.target.value)} placeholder="Your name" />
              </Field>
              <PhoneField value={phone} onChange={setPhone} dialCode={dial} setDial={setDial} />
            </div>

            <div className="form-foot">
              <span className="privacy">
                Booking will be held for 30 minutes pending WhatsApp confirmation
                from <b>{FD.phones.customer}</b>.
              </span>
              <button className="btn btn-primary"
                      onClick={()=>setConfirmed(true)}
                      disabled={!name || !phone}>
                Request slot <span className="arrow"></span>
              </button>
            </div>
          </>
        )}

        {confirmed && (
          <div className="success-pane">
            <div className="check">
              <svg viewBox="0 0 24 24" fill="none">
                <path d="M5 12.5L10 17L19 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <h3>Slot requested.</h3>
            <p>
              <b>{dayLbl(days[day])} {days[day].getDate()}</b> at <b>{time}</b> · {where}.
              We'll confirm on WhatsApp at {dial} {phone}.
            </p>
            <div className="ticket">Hold · SV-{Math.floor(Math.random()*900000+100000)}</div>
            <div style={{display:"flex", gap:10, justifyContent:"center", marginTop:14}}>
              <a className="btn btn-ghost" href={FD.phones.waLink} target="_blank" rel="noopener">Open WhatsApp</a>
              <button className="btn" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}

/* ============================================================
   Channel partner / broker enquiry
   ============================================================ */
function BrokerFlow({ onClose }) {
  const [sent, setSent] = React.useState(false);
  const [f, setF] = React.useState({
    company:"", license:"", contact:"", email:"", phone:"", dial:"+971",
    market:"UAE retail", consent:false
  });
  const upd = (k,v) => setF(p => ({...p, [k]:v}));

  return (
    <Modal onClose={onClose}>
      <div className="modal-inner">
        {!sent && (
          <>
            <div className="eyebrow">Channel partners</div>
            <h3 style={{marginTop:10}}>Apply to represent Sobha Realty.</h3>
            <p className="sub">
              For RERA-registered brokerages and international agents. Approved
              partners receive launch packs, gated commissions and dedicated routing.
            </p>

            <div className="form-row">
              <Field label="Company">
                <input value={f.company} onChange={(e)=>upd("company", e.target.value)} placeholder="Brokerage / agency" />
              </Field>
              <Field label="Trade / RERA licence">
                <input value={f.license} onChange={(e)=>upd("license", e.target.value)} placeholder="Number" />
              </Field>
            </div>
            <div className="form-row">
              <Field label="Primary contact">
                <input value={f.contact} onChange={(e)=>upd("contact", e.target.value)} placeholder="Name & role" />
              </Field>
              <Field label="Email">
                <input type="email" value={f.email} onChange={(e)=>upd("email", e.target.value)} placeholder="you@firm.com" />
              </Field>
            </div>
            <div className="form-row">
              <PhoneField value={f.phone} onChange={(v)=>upd("phone", v)} dialCode={f.dial} setDial={(v)=>upd("dial",v)} />
              <Field label="Primary market">
                <select value={f.market} onChange={(e)=>upd("market", e.target.value)}>
                  <option>UAE retail</option>
                  <option>GCC retail</option>
                  <option>India / South Asia</option>
                  <option>Greater China</option>
                  <option>Europe</option>
                  <option>Russia / CIS</option>
                </select>
              </Field>
            </div>

            <div className="checkbox" style={{marginTop:14}}>
              <input type="checkbox" checked={f.consent} onChange={(e)=>upd("consent", e.target.checked)} />
              <span>I agree to Sobha Realty channel-partner terms and KYC checks.</span>
            </div>

            <div className="form-foot">
              <span className="privacy">
                Channel-partner phone lead <b>+971 50 513 4993</b> requires confirmation
                before public routing.
              </span>
              <button className="btn btn-primary"
                      onClick={()=>setSent(true)}
                      disabled={!f.email || !f.consent}>
                Submit application <span className="arrow"></span>
              </button>
            </div>
          </>
        )}

        {sent && (
          <div className="success-pane">
            <div className="check">
              <svg viewBox="0 0 24 24" fill="none">
                <path d="M5 12.5L10 17L19 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <h3>Application received.</h3>
            <p>Channel-partner team will respond within two business days following internal KYC checks.</p>
            <button className="btn" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </Modal>
  );
}

/* ============================================================
   In-page lead band — surfaces the multi-route lead form inline
   ============================================================ */
function LeadBand({ openBroker }) {
  const [tab, setTab] = React.useState("register");

  return (
    <section className="lead-band" id="lead-band">
      <div className="container">
        <div className="lead-inner">
          <div>
            <div className="eyebrow">Speak with the sales team</div>
            <h2 className="h-1" style={{marginTop:16, maxWidth:"16ch"}}>
              Four routes,<br /><em>one conversation.</em>
            </h2>
            <p className="lead" style={{marginTop:22}}>
              Sales, customer service, investor relations, and channel partners route
              through this form. WhatsApp on <b>{FD.phones.customer}</b>, sales
              line on <b>{FD.phones.sales}</b>.
            </p>

            <div style={{marginTop:36}}>
              <div className="fine">Confirm on launch</div>
              <ul style={{
                listStyle:"none", margin:"14px 0 0", padding:0,
                display:"flex", flexDirection:"column", gap:10, fontSize:13, color:"var(--muted)"
              }}>
                <li>• Sales-gallery hours and visitor parking</li>
                <li>• Department email addresses</li>
                <li>• Channel-partner phone routing</li>
                <li>• App Store / Play Store URLs</li>
                <li>• Per-community RERA / DLD numbers</li>
              </ul>
            </div>
          </div>

          <InlineLeadCard tab={tab} setTab={setTab} openBroker={openBroker} />
        </div>
      </div>
    </section>
  );
}

function InlineLeadCard({ tab, setTab, openBroker }) {
  return (
    <div className="lead-form">
      <div className="lead-tabs">
        <button className={tab==="register"?"active":""} onClick={()=>setTab("register")}>Register interest</button>
        <button className={tab==="viewing"?"active":""}  onClick={()=>setTab("viewing")}>Private viewing</button>
        <button className={tab==="partner"?"active":""}  onClick={()=>setTab("partner")}>Channel partner</button>
      </div>

      {tab==="register" && <QuickRegister />}
      {tab==="viewing"  && <QuickViewing />}
      {tab==="partner"  && <QuickBroker openBroker={openBroker} />}
    </div>
  );
}

/* — Inline quick forms (lighter than modal versions) — */
function QuickRegister() {
  const [route, setRoute] = React.useState("sales");
  const [f, setF] = React.useState({ name:"", email:"", phone:"", dial:"+971", consent:false });
  const upd = (k,v) => setF(p => ({...p, [k]:v}));
  const [sent, setSent] = React.useState(false);
  if (sent) return <SuccessInline onReset={()=>setSent(false)} msg="Enquiry sent. We'll reach you via WhatsApp within one business day." />;
  return (
    <>
      <RouteChooser value={route} onChange={setRoute} />
      <div className="form-row">
        <Field label="Full name">
          <input value={f.name} onChange={(e)=>upd("name", e.target.value)} placeholder="Your name" />
        </Field>
        <Field label="Email">
          <input type="email" value={f.email} onChange={(e)=>upd("email", e.target.value)} placeholder="you@email.com" />
        </Field>
      </div>
      <div className="form-row">
        <PhoneField value={f.phone} onChange={(v)=>upd("phone",v)} dialCode={f.dial} setDial={(v)=>upd("dial",v)} />
        <Field label="Community of interest">
          <select defaultValue="Sobha One">
            {FD.communities.map(c => <option key={c.slug}>{c.name}</option>)}
          </select>
        </Field>
      </div>
      <div className="checkbox" style={{marginTop:12}}>
        <input type="checkbox" checked={f.consent} onChange={(e)=>upd("consent", e.target.checked)} />
        <span>Consent to Sobha Realty contacting me about this enquiry.</span>
      </div>
      <div className="form-foot">
        <span className="privacy">Campaign source <b>microsite · Sobha One</b> auto-captured.</span>
        <button className="btn btn-primary"
                onClick={()=>setSent(true)}
                disabled={!f.email || !f.consent}>
          Send enquiry <span className="arrow"></span>
        </button>
      </div>
    </>
  );
}

function QuickViewing() {
  const [day, setDay] = React.useState(2);
  const [time, setTime] = React.useState("11:30");
  const today = new Date();
  const days = []; for (let i=1;i<=7;i++){ const d=new Date(today); d.setDate(today.getDate()+i); days.push(d);}
  const dayLbl = (d) => ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()];
  const times = ["10:00","11:30","13:00","14:30","16:00","17:30"];
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [dial, setDial] = React.useState("+971");
  const [sent, setSent] = React.useState(false);
  if (sent) return <SuccessInline onReset={()=>setSent(false)}
            msg={`Slot held · ${dayLbl(days[day])} ${days[day].getDate()} at ${time}. WhatsApp confirm shortly.`} />;
  return (
    <>
      <div className="fine">Date · next 7 days</div>
      <div className="viewing-grid">
        {days.map((d,i)=>(
          <button key={i} type="button" className={"day "+(i===day?"active":"")} onClick={()=>setDay(i)}>
            <div className="dow">{dayLbl(d)}</div>
            <div className="dnum">{d.getDate()}</div>
          </button>
        ))}
      </div>
      <div className="fine" style={{marginTop:14}}>Time</div>
      <div className="time-grid">
        {times.map(tm => (
          <button key={tm} type="button" className={tm===time?"active":""} onClick={()=>setTime(tm)}>{tm}</button>
        ))}
      </div>
      <div className="form-row" style={{marginTop:14}}>
        <Field label="Full name">
          <input value={name} onChange={(e)=>setName(e.target.value)} placeholder="Your name" />
        </Field>
        <PhoneField value={phone} onChange={setPhone} dialCode={dial} setDial={setDial} />
      </div>
      <div className="form-foot">
        <span className="privacy">We'll text on <b>{FD.phones.customer}</b> within the hour.</span>
        <button className="btn btn-primary"
                onClick={()=>setSent(true)}
                disabled={!name || !phone}>
          Request slot <span className="arrow"></span>
        </button>
      </div>
    </>
  );
}

function QuickBroker({ openBroker }) {
  return (
    <>
      <p className="body" style={{maxWidth:"60ch"}}>
        For RERA-registered brokerages and international agents. Approved partners
        receive a launch pack, gated commissions, dedicated WhatsApp line, and a
        co-branded landing-page kit per launch.
      </p>
      <div style={{
        display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:14, marginTop:24, marginBottom:24
      }}>
        <Stat n="14" k="UAE developments" />
        <Stat n="30B" k="FY25 sales · AED" />
        <Stat n="4★" k="GRESB 2025" />
      </div>
      <button className="btn btn-primary" onClick={openBroker}>
        Open partner application <span className="arrow"></span>
      </button>
    </>
  );
}

function Stat({ n, k }) {
  return (
    <div style={{
      border:"1px solid var(--border)", borderRadius:2, padding:"16px 14px",
      display:"flex", flexDirection:"column", gap:6, background:"var(--bg)"
    }}>
      <span className="num" style={{fontSize:30, lineHeight:1}}>{n}</span>
      <span style={{fontFamily:"var(--mono)", fontSize:10.5, letterSpacing:".14em", textTransform:"uppercase", color:"var(--muted)"}}>{k}</span>
    </div>
  );
}

function SuccessInline({ msg, onReset }) {
  return (
    <div style={{
      display:"flex", flexDirection:"column", gap:14, alignItems:"flex-start",
      padding:"6px 0"
    }}>
      <div style={{
        width:44, height:44, borderRadius:50, background:"var(--primary)",
        color:"#fff", display:"grid", placeItems:"center"
      }}>
        <svg viewBox="0 0 24 24" fill="none" width="20" height="20">
          <path d="M5 12.5L10 17L19 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
      <div className="h-2" style={{fontSize:24}}>Sent.</div>
      <p className="body" style={{margin:0, maxWidth:"42ch"}}>{msg}</p>
      <button className="btn btn-ghost btn-sm" onClick={onReset}>Send another →</button>
    </div>
  );
}

Object.assign(window, {
  RegisterFlow, BrochureFlow, ViewingFlow, BrokerFlow, LeadBand
});
