// Multi-step service request form
const Request = ({ t, lang, selectedParcel, setPage, preselectedServices }) => {
  const data = window.DAOOB_DATA;
  const hasPreselected = Array.isArray(preselectedServices) && preselectedServices.length > 0;
  const [step, setStep] = React.useState(hasPreselected ? 2 : 1);
  const [picks, setPicks] = React.useState(hasPreselected ? preselectedServices : [0]);
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", org: "", role: "Individual investor", note: "" });

  const sel = data.parcels.find(p => p.id === selectedParcel) || data.parcels.find(p => p.featured);
  const district = data.districts[sel.district];

  const togglePick = (i) => setPicks(p => p.includes(i) ? p.filter(x => x !== i) : [...p, i]);

  const studies = t.services.list;
  const pickedStudies = picks.map(i => studies[i]);
  const totalRange = pickedStudies.reduce((acc, s) => acc + (s.daoob || 500), 0);
  const officeTotalRange = pickedStudies.reduce((acc, s) => {
    const m = s.price.match(/[\d,]+/);
    const n = m ? parseInt(m[0].replace(/,/g, ""), 10) : 0;
    return acc + n;
  }, 0);
  const leadDays = 0;

  const ref = "DAO-2026-" + (190 + picks.length).toString().padStart(4, "0");

  return (
    <div>
      <div className="page-header">
        <div className="container">
          <div className="eyebrow">{t.nav.get_started}</div>
          <h1 className="t-h1">{t.request.h1}</h1>
        </div>
      </div>
      <div className="request-page">
        <div>
          <div className="steps">
            {[1,2,3,4].map(n => (
              <div key={n} className={"step" + (step === n ? " active" : "") + (step > n ? " done" : "")}>
                <div className="n">0{n}</div>
                <div className="t">{t.request[`s${n}`]}</div>
              </div>
            ))}
          </div>

          <div className="form-block">
            {step === 1 && (
              <div className="col gap-6">
                <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontSize: 24, fontWeight: 400 }}>{t.request.s1}</h3>
                <div className="card" style={{ padding: 24, background: "var(--paper-2)", border: "1px solid var(--hairline)" }}>
                  <div style={{ display: "flex", gap: 20, alignItems: "center" }}>
                    <div style={{ width: 80, height: 80, borderRadius: 6, background: "var(--green-800)", flexShrink: 0, display: "grid", placeItems: "center", color: "var(--gold-400)" }}>
                      <Icon name="pin" size={28} stroke={1.5}/>
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-400)" }}>{t.request.parcel_ref}</div>
                      <div style={{ fontFamily: "var(--font-serif)", fontSize: 24, marginTop: 4 }}>{sel.id}</div>
                      <div style={{ fontSize: 14, color: "var(--ink-500)", marginTop: 4 }}>
                        {district[lang]} · {data.zoningTypes[sel.zone][lang]} · {sel.area.toLocaleString()} {t.map.sqm}
                      </div>
                    </div>
                    <button className="btn btn-ghost btn-sm" onClick={() => setPage("map")}>
                      {lang === "ar" ? "تغيير القطعة" : "Change parcel"}
                    </button>
                  </div>
                </div>
                <p style={{ color: "var(--ink-500)", fontSize: 14, margin: 0 }}>
                  {lang === "ar" ? "تم استخراج بيانات القطعة من سجل REGA. يمكنك مواصلة طلب الدراسة." : "Parcel data resolved against the REGA registry. You're ready to commission a study."}
                </p>
              </div>
            )}

            {step === 2 && (
              <div className="col gap-6">
                <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontSize: 24, fontWeight: 400 }}>{t.request.s2}</h3>
                <div className="study-grid">
                  {studies.map((s, i) => (
                    <div key={i} className={"study-pick" + (picks.includes(i) ? " on" : "")} onClick={() => togglePick(i)}>
                      <div className="check">{picks.includes(i) && <Icon name="check" size={12} stroke={2.5}/>}</div>
                      <div style={{ flex: 1 }}>
                        <div className="t">{s.t}</div>
                        <div className="d">{s.d}</div>
                        <div className="study-pick-prices">
                          <span className="spp-ai">{(s.daoob || 500).toLocaleString()} {lang === "ar" ? "ر.س" : "SAR"} · {t.services.compare.ai_lead}</span>
                          <span className="spp-office">{s.price} · {s.lead}</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {step === 3 && (
              <div className="col gap-4">
                <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontSize: 24, fontWeight: 400 }}>{t.request.s3}</h3>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                  <div className="field">
                    <label>{t.request.contact_name}</label>
                    <input value={form.name} onChange={e => setForm({...form, name: e.target.value})}/>
                  </div>
                  <div className="field">
                    <label>{t.request.contact_email}</label>
                    <input value={form.email} onChange={e => setForm({...form, email: e.target.value})}/>
                  </div>
                  <div className="field">
                    <label>{t.request.contact_phone}</label>
                    <input value={form.phone} onChange={e => setForm({...form, phone: e.target.value})}/>
                  </div>
                  <div className="field">
                    <label>{t.request.contact_org}</label>
                    <input value={form.org} onChange={e => setForm({...form, org: e.target.value})}/>
                  </div>
                  <div className="field" style={{ gridColumn: "span 2" }}>
                    <label>{t.request.contact_role}</label>
                    <select value={form.role} onChange={e => setForm({...form, role: e.target.value})}>
                      {(lang === "ar"
                        ? ["مستثمر فرد","مطور","صندوق / مكتب عائلي","جهة حكومية","مستثمر أجنبي"]
                        : ["Individual investor","Developer","Family office / fund","Government","Foreign investor"]
                      ).map(o => <option key={o}>{o}</option>)}
                    </select>
                  </div>
                  <div className="field" style={{ gridColumn: "span 2" }}>
                    <label>{t.request.contact_note}</label>
                    <textarea rows="4" value={form.note} onChange={e => setForm({...form, note: e.target.value})}/>
                  </div>
                </div>
              </div>
            )}

            {step === 4 && (
              <div className="col gap-6">
                <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontSize: 24, fontWeight: 400 }}>{t.request.s4}</h3>
                <div style={{ border: "1px solid var(--hairline)", borderRadius: 8 }}>
                  <ReviewRow l={t.request.parcel_ref} v={`${sel.id} · ${district[lang]}`}/>
                  <ReviewRow l={t.request.selected_studies} v={pickedStudies.length ? pickedStudies.map(s => s.t).join(" · ") : t.request.none_selected}/>
                  <ReviewRow l={t.request.contact_name} v={form.name || "—"}/>
                  <ReviewRow l={t.request.contact_email} v={form.email || "—"}/>
                  <ReviewRow l={t.request.contact_phone} v={form.phone || "—"}/>
                  <ReviewRow l={t.request.contact_org} v={form.org || "—"}/>
                  <ReviewRow l={t.request.contact_note} v={form.note || "—"}/>
                </div>
                <div style={{ padding: 20, background: "var(--green-50)", borderRadius: 6, fontSize: 13, color: "var(--green-800)" }}>
                  {lang === "ar"
                    ? "بإرسالك الطلب، يبدأ وكلاء دؤوب الذكاء العمل فوراً. ستصلك الدراسة الكاملة خلال 72 ساعة."
                    : "On submit, Daoob AI agents begin work immediately. Your full report arrives within 72 hours."}
                </div>
              </div>
            )}

            {step === 5 && (
              <div className="col gap-6 center" style={{ padding: "48px 24px", textAlign: "center", flexDirection: "column" }}>
                <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--green-50)", color: "var(--green-700)", display: "grid", placeItems: "center" }}>
                  <Icon name="check" size={28} stroke={2}/>
                </div>
                <div>
                  <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontSize: 28, fontWeight: 400 }}>{t.request.success_t}</h3>
                  <p style={{ color: "var(--ink-500)", marginTop: 8, maxWidth: 480 }}>{t.request.success_d.replace("{ref}", ref)}</p>
                </div>
                <div style={{ display: "flex", gap: 12 }}>
                  <button className="btn btn-primary" onClick={() => setPage("dashboard")}>
                    {lang === "ar" ? "افتح لوحتي" : "Open my dashboard"}
                  </button>
                  <button className="btn btn-outline" onClick={() => setPage("map")}>
                    {lang === "ar" ? "اطلب دراسة أخرى" : "Request another study"}
                  </button>
                </div>
              </div>
            )}

            {step < 5 && (
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 32, paddingTop: 24, borderTop: "1px solid var(--hairline)" }}>
                <button className="btn btn-ghost" onClick={() => setStep(Math.max(1, step - 1))} disabled={step === 1} style={step === 1 ? { opacity: 0.4, pointerEvents: "none" } : {}}>
                  {t.request.back}
                </button>
                {step < 4 ? (
                  <button className="btn btn-primary" onClick={() => setStep(step + 1)}>
                    {t.request.next} <Icon name="arrow-right" size={14}/>
                  </button>
                ) : (
                  <button className="btn btn-gold" onClick={() => setStep(5)}>
                    {t.request.submit}
                  </button>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Aside summary */}
        <div className="summary-aside">
          <div className="summary-card">
            <h4>{t.request.s4}</h4>
            <div className="summary-row">
              <span>{t.request.parcel_ref}</span>
              <span className="v" style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{sel.id}</span>
            </div>
            <div className="summary-row">
              <span>{lang === "ar" ? "الحي" : "District"}</span>
              <span className="v">{district[lang]}</span>
            </div>
            <div className="summary-row">
              <span>{lang === "ar" ? "المساحة" : "Area"}</span>
              <span className="v t-num">{sel.area.toLocaleString()} m²</span>
            </div>
            <div className="summary-row">
              <span>{t.request.selected_studies}</span>
              <span className="v">{pickedStudies.length}</span>
            </div>
            <div className="summary-row">
              <span>{t.request.lead_time}</span>
              <span className="v">{t.services.compare.ai_lead}</span>
            </div>
            {officeTotalRange > 0 && (
              <div className="summary-row" style={{ opacity: 0.6 }}>
                <span style={{ fontSize: 12 }}>{lang === "ar" ? "السعر التقليدي" : "Traditional offices"}</span>
                <span className="v" style={{ textDecoration: "line-through", fontSize: 13 }}>{officeTotalRange.toLocaleString()} SAR</span>
              </div>
            )}
            <div className="summary-row total">
              <span>{t.request.total}</span>
              <span className="v t-num">{totalRange.toLocaleString()} SAR</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const ReviewRow = ({ l, v }) => (
  <div style={{ display: "flex", padding: "14px 20px", borderBottom: "1px solid var(--hairline)", fontSize: 14 }}>
    <div style={{ flex: "0 0 200px", color: "var(--ink-500)", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.04em" }}>{l}</div>
    <div style={{ flex: 1, color: "var(--ink-900)" }}>{v}</div>
  </div>
);

Object.assign(window, { Request });
