/* Lead funnel modals: Register Interest (3-step), Brochure (gated),
   Private Viewing, Broker Enquiry. */

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

// ============ shared modal frame ============
function ModalFrame({ title, subtitle, onClose, step, totalSteps, children, footer }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);

  return (
    <div className="modal-bg" onClick={(e) => { if (e.target.classList.contains("modal-bg")) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-head">
          <div>
            {step != null && (
              <div className="step">Step {step} of {totalSteps}</div>
            )}
            <h3>{title}</h3>
            {subtitle && <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 6 }}>{subtitle}</div>}
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        </div>
        {step != null && (
          <div style={{ padding: "16px 28px 0" }}>
            <div className="stepper">
              {Array.from({ length: totalSteps }).map((_, i) => (
                <div key={i} className={`step-bar ${i + 1 < step ? "done" : i + 1 === step ? "current" : ""}`} />
              ))}
            </div>
          </div>
        )}
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

function SecureLabel() {
  return (
    <div className="secure">
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="4" y="11" width="16" height="10" rx="1"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
      Encrypted · Routed by region · No call centre
    </div>
  );
}

// ============ REGISTER INTEREST ============
function RegisterInterestModal({ project, onClose }) {
  const [step, setStep] = useState(1);
  const [data, setData] = useState({
    region: "AE",
    firstName: "",
    lastName: "",
    email: "",
    dial: "+971",
    phone: "",
    motivation: "investor",
    timeframe: "3-months",
    budget: "",
    consent: false,
    whatsappOk: true,
  });
  const [errors, setErrors] = useState({});
  const [done, setDone] = useState(null);

  const update = (k, v) => { setData({ ...data, [k]: v }); setErrors({ ...errors, [k]: null }); };

  const validateStep = () => {
    const e = {};
    if (step === 1) {
      if (!data.region) e.region = "Required";
    }
    if (step === 2) {
      if (!data.firstName.trim()) e.firstName = "Required";
      if (!data.lastName.trim()) e.lastName = "Required";
      if (!data.email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) e.email = "Email format";
      if (!data.phone.match(/^[0-9 \-]{6,}$/)) e.phone = "Phone format";
    }
    if (step === 3) {
      if (!data.consent) e.consent = "Required";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => { if (validateStep()) setStep(step + 1); };
  const submit = () => {
    if (!validateStep()) return;
    const ref = "REG-" + Math.random().toString(36).slice(2, 8).toUpperCase();
    const region = REGIONS.find(r => r.code === data.region);
    setDone({ ref, region });
  };

  if (done) {
    return (
      <ModalFrame title=" " onClose={onClose}>
        <div className="success-state">
          <div className="check-circle">✓</div>
          <h3>Routed to {done.region.desk}.</h3>
          <p>
            Your enquiry for <b>{project.name}</b> is queued with the {done.region.label} desk.
            A relationship manager will reach you on the phone or WhatsApp number you provided within one business day.
          </p>
          <div className="ticket">Reference · {done.ref}</div>
          <div style={{ display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
            <a className="btn primary" href={`https://wa.me/${done.region.whatsapp}`} target="_blank" rel="noreferrer">
              Open WhatsApp <span className="arrow"/>
            </a>
            <button className="btn" onClick={onClose}>Close</button>
          </div>
        </div>
      </ModalFrame>
    );
  }

  return (
    <ModalFrame
      title={step === 1 ? "Which desk should handle you?" : step === 2 ? "Your details" : "Confirm and submit"}
      subtitle={`${project.name} · register interest`}
      step={step}
      totalSteps={3}
      onClose={onClose}
      footer={
        <>
          <SecureLabel />
          <div style={{ display: "flex", gap: 8 }}>
            {step > 1 && <button className="btn" onClick={() => setStep(step - 1)}>Back</button>}
            {step < 3 ? (
              <button className="btn primary" onClick={next}>Continue <span className="arrow"/></button>
            ) : (
              <button className="btn primary" onClick={submit}>Submit enquiry <span className="arrow"/></button>
            )}
          </div>
        </>
      }
    >
      {step === 1 && (
        <>
          <p style={{ marginTop: 0 }}>Binghatti routes leads to a real regional desk — UAE, KSA, UK or China. Pick the country you'd like to be contacted from.</p>
          <div className="region-grid">
            {REGIONS.map((r) => (
              <button key={r.code} className={r.code === data.region ? "selected" : ""} onClick={() => update("region", r.code)}>
                <div className="flag">{r.flag}</div>
                <div className="code">{r.label}</div>
              </button>
            ))}
          </div>
          <div style={{ background: "var(--surface)", border: "1px solid var(--border)", padding: 18, fontSize: 13, color: "var(--muted)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--text)", marginBottom: 4 }}>
                {REGIONS.find(r => r.code === data.region).desk}
              </div>
              {REGIONS.find(r => r.code === data.region).line} · {REGIONS.find(r => r.code === data.region).email}
            </div>
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div className="field-row">
            <div className="field">
              <label>First name <span className="req">*</span></label>
              <input value={data.firstName} onChange={(e) => update("firstName", e.target.value)} placeholder="Hessa" />
              {errors.firstName && <div className="err">{errors.firstName}</div>}
            </div>
            <div className="field">
              <label>Last name <span className="req">*</span></label>
              <input value={data.lastName} onChange={(e) => update("lastName", e.target.value)} placeholder="Al Maktoum" />
              {errors.lastName && <div className="err">{errors.lastName}</div>}
            </div>
          </div>
          <div className="field">
            <label>Email <span className="req">*</span></label>
            <input type="email" value={data.email} onChange={(e) => update("email", e.target.value)} placeholder="you@domain.com" />
            {errors.email && <div className="err">{errors.email}</div>}
          </div>
          <div className="field">
            <label>Phone (WhatsApp-capable preferred) <span className="req">*</span></label>
            <div className="phone-comp">
              <select value={data.dial} onChange={(e) => update("dial", e.target.value)}>
                {COUNTRY_DIAL_CODES.map(c => <option key={c.code} value={c.code}>{c.label}</option>)}
              </select>
              <input value={data.phone} onChange={(e) => update("phone", e.target.value)} placeholder="50 123 4567" />
            </div>
            {errors.phone && <div className="err">{errors.phone}</div>}
          </div>
        </>
      )}

      {step === 3 && (
        <>
          <div className="field">
            <label>I am</label>
            <select value={data.motivation} onChange={(e) => update("motivation", e.target.value)}>
              <option value="investor">Investor — yield / capital appreciation</option>
              <option value="end-user">End-user — personal residence</option>
              <option value="advisor">Family office / advisor on behalf of buyer</option>
              <option value="broker">Licensed broker</option>
            </select>
          </div>
          <div className="field-row">
            <div className="field">
              <label>Timeframe</label>
              <select value={data.timeframe} onChange={(e) => update("timeframe", e.target.value)}>
                <option value="3-months">Within 3 months</option>
                <option value="6-months">3 – 6 months</option>
                <option value="12-months">6 – 12 months</option>
                <option value="exploring">Exploring</option>
              </select>
            </div>
            <div className="field">
              <label>Budget (indicative, optional)</label>
              <select value={data.budget} onChange={(e) => update("budget", e.target.value)}>
                <option value="">Prefer not to say</option>
                <option>AED 1M – 3M</option>
                <option>AED 3M – 5M</option>
                <option>AED 5M – 10M</option>
                <option>AED 10M+</option>
              </select>
            </div>
          </div>

          <label className="check">
            <input type="checkbox" checked={data.whatsappOk} onChange={(e) => update("whatsappOk", e.target.checked)} />
            <span>Contact me on WhatsApp as well as email. (Recommended — fastest response from the regional desk.)</span>
          </label>
          <label className="check">
            <input type="checkbox" checked={data.consent} onChange={(e) => update("consent", e.target.checked)} />
            <span>
              I consent to my details being shared with the routed regional sales desk for the purpose of this enquiry only.
              I understand that all project specifications, pricing, statuses, areas and handovers are provided through the signed brochure
              and are not represented as audited facts on this campaign page. <span className="req">*</span>
            </span>
          </label>
          {errors.consent && <div className="err">Consent required</div>}

          <div style={{ background: "var(--surface)", border: "1px solid var(--border)", padding: 16, fontSize: 12, color: "var(--muted)" }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--text)", marginBottom: 8 }}>Summary</div>
            <div><b style={{ color: "var(--text)" }}>{project.name}</b> · {REGIONS.find(r => r.code === data.region).desk}</div>
            <div>{data.firstName} {data.lastName} · {data.email}</div>
            <div>{data.dial} {data.phone}</div>
          </div>
        </>
      )}
    </ModalFrame>
  );
}

// ============ BROCHURE GATE ============
function BrochureModal({ project, onClose }) {
  const [data, setData] = useState({ name: "", email: "", region: "AE", consent: false });
  const [errors, setErrors] = useState({});
  const [stage, setStage] = useState("form"); // form | sending | done
  const [progress, setProgress] = useState(0);

  const submit = () => {
    const e = {};
    if (!data.name.trim()) e.name = "Required";
    if (!data.email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) e.email = "Email format";
    if (!data.consent) e.consent = "Consent required";
    setErrors(e);
    if (Object.keys(e).length) return;

    setStage("sending");
    let p = 0;
    const t = setInterval(() => {
      p += 7 + Math.random() * 10;
      if (p >= 100) { p = 100; clearInterval(t); setTimeout(() => setStage("done"), 250); }
      setProgress(p);
    }, 110);
  };

  if (stage === "sending") {
    return (
      <ModalFrame title="Preparing your brochure…" onClose={onClose}>
        <div style={{ padding: "20px 0" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 12 }}>
            Building tailored PDF · {Math.floor(progress)}%
          </div>
          <div style={{ height: 4, background: "var(--border-soft)", overflow: "hidden", marginBottom: 32 }}>
            <div style={{ height: "100%", background: "var(--primary)", width: progress + "%", transition: "width .1s linear" }} />
          </div>
          <div style={{ display: "grid", gap: 8, fontSize: 13, color: "var(--muted)" }}>
            <div>· Verifying email…</div>
            <div style={{ opacity: progress > 35 ? 1 : .3 }}>· Routing to {REGIONS.find(r => r.code === data.region).desk}…</div>
            <div style={{ opacity: progress > 65 ? 1 : .3 }}>· Compiling project pack…</div>
            <div style={{ opacity: progress > 90 ? 1 : .3 }}>· Attaching brochure PDF…</div>
          </div>
        </div>
      </ModalFrame>
    );
  }

  if (stage === "done") {
    return (
      <ModalFrame title=" " onClose={onClose}>
        <div className="success-state">
          <div className="check-circle">✓</div>
          <h3>Brochure on the way.</h3>
          <p>
            We've sent the <b>{project.name}</b> brochure pack to <b>{data.email}</b>.
            The {REGIONS.find(r => r.code === data.region).label} desk is copied — expect a follow-up within one business day.
          </p>
          <div className="ticket">Pack ID · BRO-{Math.random().toString(36).slice(2, 8).toUpperCase()}</div>
          <button className="btn primary" onClick={onClose}>Continue browsing <span className="arrow"/></button>
        </div>
      </ModalFrame>
    );
  }

  return (
    <ModalFrame
      title="Gated brochure download"
      subtitle={`${project.name} · PDF pack`}
      onClose={onClose}
      footer={
        <>
          <SecureLabel />
          <button className="btn primary" onClick={submit}>Send brochure <span className="arrow"/></button>
        </>
      }
    >
      <p style={{ marginTop: 0 }}>
        The brochure is released by email — not as an anonymous download. We share campaign-specific PDFs with verified contacts so we can follow up properly.
      </p>
      <div className="field">
        <label>Full name <span className="req">*</span></label>
        <input value={data.name} onChange={(e) => { setData({ ...data, name: e.target.value }); setErrors({ ...errors, name: null }); }} placeholder="Hessa Al Maktoum" />
        {errors.name && <div className="err">{errors.name}</div>}
      </div>
      <div className="field">
        <label>Work email <span className="req">*</span></label>
        <input type="email" value={data.email} onChange={(e) => { setData({ ...data, email: e.target.value }); setErrors({ ...errors, email: null }); }} placeholder="you@domain.com" />
        {errors.email && <div className="err">{errors.email}</div>}
      </div>
      <div className="field">
        <label>Region (routing only)</label>
        <div className="region-grid">
          {REGIONS.map((r) => (
            <button key={r.code} className={r.code === data.region ? "selected" : ""} onClick={() => setData({ ...data, region: r.code })}>
              <div className="flag">{r.flag}</div>
              <div className="code">{r.label}</div>
            </button>
          ))}
        </div>
      </div>
      <label className="check">
        <input type="checkbox" checked={data.consent} onChange={(e) => { setData({ ...data, consent: e.target.checked }); setErrors({ ...errors, consent: null }); }} />
        <span>I consent to be contacted by the routed desk for this brochure request. No spec on this page is a contractual figure. <span className="req">*</span></span>
      </label>
      {errors.consent && <div className="err">{errors.consent}</div>}
    </ModalFrame>
  );
}

// ============ PRIVATE VIEWING ============
function ViewingModal({ project, onClose }) {
  const [data, setData] = useState({
    mode: "experience",
    name: "", email: "", phone: "", dial: "+971",
    date: null, slot: null, region: "AE", consent: false,
  });
  const [errors, setErrors] = useState({});
  const [done, setDone] = useState(false);

  // Generate next 14 days
  const dates = useMemo(() => {
    const out = [];
    const today = new Date();
    for (let i = 1; i <= 12; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() + i);
      out.push({
        iso: d.toISOString().slice(0, 10),
        weekday: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()],
        day: d.getDate(),
      });
    }
    return out;
  }, []);
  const slots = ["10:00", "11:30", "13:00", "14:30", "16:00", "17:30"];

  const submit = () => {
    const e = {};
    if (!data.name.trim()) e.name = "Required";
    if (!data.email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) e.email = "Email format";
    if (!data.phone.match(/^[0-9 \-]{6,}$/)) e.phone = "Phone format";
    if (!data.date) e.date = "Pick a date";
    if (!data.slot) e.slot = "Pick a slot";
    if (!data.consent) e.consent = "Required";
    setErrors(e);
    if (Object.keys(e).length === 0) setDone(true);
  };

  if (done) {
    return (
      <ModalFrame title=" " onClose={onClose}>
        <div className="success-state">
          <div className="check-circle">✓</div>
          <h3>Viewing confirmed.</h3>
          <p>
            We've reserved <b>{data.date}</b> at <b>{data.slot}</b> for <b>{project.name}</b> ({data.mode === "experience" ? "Experience Centre" : "Video walk-through"}).
            A calendar invite is on its way to <b>{data.email}</b>.
          </p>
          <div className="ticket">Booking · VW-{Math.random().toString(36).slice(2, 8).toUpperCase()}</div>
          <button className="btn primary" onClick={onClose}>Close <span className="arrow"/></button>
        </div>
      </ModalFrame>
    );
  }

  return (
    <ModalFrame
      title="Book a private viewing"
      subtitle={`${project.name} · with a relationship manager`}
      onClose={onClose}
      footer={
        <>
          <SecureLabel />
          <button className="btn primary" onClick={submit}>Confirm booking <span className="arrow"/></button>
        </>
      }
    >
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 18 }}>
        {[
          { v: "experience", t: "Experience Centre", s: "In person · Dubai" },
          { v: "video", t: "Video walk-through", s: "Zoom / WhatsApp · 45 min" },
        ].map(o => (
          <button key={o.v} onClick={() => setData({ ...data, mode: o.v })}
            style={{
              background: data.mode === o.v ? "var(--text)" : "var(--surface)",
              color: data.mode === o.v ? "var(--bg)" : "var(--text)",
              border: "1px solid " + (data.mode === o.v ? "var(--text)" : "var(--border)"),
              padding: "18px 16px", textAlign: "start", cursor: "pointer",
            }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", opacity: .7, marginBottom: 4 }}>{o.s}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>{o.t}</div>
          </button>
        ))}
      </div>

      <div className="field">
        <label>Date</label>
        <div className="date-strip">
          {dates.map(d => (
            <button key={d.iso} className={data.date === d.iso ? "selected" : ""} onClick={() => setData({ ...data, date: d.iso })}>
              <div className="d-wk">{d.weekday}</div>
              <div className="d-num">{d.day}</div>
            </button>
          ))}
        </div>
        {errors.date && <div className="err">{errors.date}</div>}
      </div>

      <div className="field">
        <label>Time slot</label>
        <div className="slot-grid">
          {slots.map((s, i) => (
            <button key={s} className={`${data.slot === s ? "selected" : ""} ${i === 2 && data.date === dates[0]?.iso ? "disabled" : ""}`}
              onClick={() => setData({ ...data, slot: s })}>{s}</button>
          ))}
        </div>
        {errors.slot && <div className="err">{errors.slot}</div>}
      </div>

      <div className="field-row">
        <div className="field">
          <label>Name <span className="req">*</span></label>
          <input value={data.name} onChange={e => setData({ ...data, name: e.target.value })}/>
          {errors.name && <div className="err">{errors.name}</div>}
        </div>
        <div className="field">
          <label>Email <span className="req">*</span></label>
          <input type="email" value={data.email} onChange={e => setData({ ...data, email: e.target.value })}/>
          {errors.email && <div className="err">{errors.email}</div>}
        </div>
      </div>
      <div className="field">
        <label>Phone <span className="req">*</span></label>
        <div className="phone-comp">
          <select value={data.dial} onChange={e => setData({ ...data, dial: e.target.value })}>
            {COUNTRY_DIAL_CODES.map(c => <option key={c.code} value={c.code}>{c.label}</option>)}
          </select>
          <input value={data.phone} onChange={e => setData({ ...data, phone: e.target.value })}/>
        </div>
        {errors.phone && <div className="err">{errors.phone}</div>}
      </div>
      <label className="check">
        <input type="checkbox" checked={data.consent} onChange={e => setData({ ...data, consent: e.target.checked })}/>
        <span>I understand finishes, layouts and pricing shown at the viewing remain subject to the signed brochure and SPA.</span>
      </label>
      {errors.consent && <div className="err">{errors.consent}</div>}
    </ModalFrame>
  );
}

// ============ BROKER ENQUIRY ============
function BrokerModal({ project, onClose }) {
  const [data, setData] = useState({ company: "", license: "", name: "", email: "", phone: "", dial: "+971", consent: false });
  const [errors, setErrors] = useState({});
  const [done, setDone] = useState(false);

  const submit = () => {
    const e = {};
    if (!data.company.trim()) e.company = "Required";
    if (!data.license.trim()) e.license = "RERA broker number required";
    if (!data.name.trim()) e.name = "Required";
    if (!data.email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) e.email = "Email format";
    if (!data.consent) e.consent = "Required";
    setErrors(e);
    if (Object.keys(e).length === 0) setDone(true);
  };

  if (done) {
    return (
      <ModalFrame title=" " onClose={onClose}>
        <div className="success-state">
          <div className="check-circle">✓</div>
          <h3>Broker desk notified.</h3>
          <p>Your licensed-broker enquiry for <b>{project.name}</b> is now with the Binghatti broker desk. They handle commercial terms separately from the buyer funnel.</p>
          <div className="ticket">Broker enquiry · BRK-{Math.random().toString(36).slice(2, 8).toUpperCase()}</div>
          <button className="btn primary" onClick={onClose}>Close <span className="arrow"/></button>
        </div>
      </ModalFrame>
    );
  }

  return (
    <ModalFrame
      title="Licensed broker enquiry"
      subtitle={`${project.name} · separate commercial track`}
      onClose={onClose}
      footer={
        <>
          <SecureLabel />
          <button className="btn primary" onClick={submit}>Submit <span className="arrow"/></button>
        </>
      }
    >
      <div className="field-row">
        <div className="field">
          <label>Brokerage company <span className="req">*</span></label>
          <input value={data.company} onChange={e => setData({ ...data, company: e.target.value })}/>
          {errors.company && <div className="err">{errors.company}</div>}
        </div>
        <div className="field">
          <label>RERA broker no. <span className="req">*</span></label>
          <input value={data.license} onChange={e => setData({ ...data, license: e.target.value })}/>
          {errors.license && <div className="err">{errors.license}</div>}
        </div>
      </div>
      <div className="field-row">
        <div className="field">
          <label>Your name <span className="req">*</span></label>
          <input value={data.name} onChange={e => setData({ ...data, name: e.target.value })}/>
          {errors.name && <div className="err">{errors.name}</div>}
        </div>
        <div className="field">
          <label>Work email <span className="req">*</span></label>
          <input type="email" value={data.email} onChange={e => setData({ ...data, email: e.target.value })}/>
          {errors.email && <div className="err">{errors.email}</div>}
        </div>
      </div>
      <div className="field">
        <label>Phone</label>
        <div className="phone-comp">
          <select value={data.dial} onChange={e => setData({ ...data, dial: e.target.value })}>
            {COUNTRY_DIAL_CODES.map(c => <option key={c.code} value={c.code}>{c.label}</option>)}
          </select>
          <input value={data.phone} onChange={e => setData({ ...data, phone: e.target.value })}/>
        </div>
      </div>
      <label className="check">
        <input type="checkbox" checked={data.consent} onChange={e => setData({ ...data, consent: e.target.checked })}/>
        <span>I confirm I'm a RERA-licensed broker; commercial terms (commission, lead handling) are agreed separately with the Binghatti broker desk and are not represented on this page.</span>
      </label>
      {errors.consent && <div className="err">{errors.consent}</div>}
    </ModalFrame>
  );
}

// expose
Object.assign(window, { RegisterInterestModal, BrochureModal, ViewingModal, BrokerModal });
