// Multi-step quote form
const { useState: useStateForm } = React;

function QuoteForm({ lang, onDone }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    machine: "", height: "", rental: "", duration: "",
    name: "", company: "", phone: "", email: "",
    startDate: "", city: "Ankara", details: "",
  });
  const [errs, setErrs] = useState({});
  const [done, setDone] = useState(false);
  const [ref, setRef] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitErr, setSubmitErr] = useState("");

  const T = lang === "tr" ? {
    steps: ["MAKİNE", "SÜRE", "İLETİŞİM", "ONAY"],
    next: "Devam",
    back: "Geri",
    submit: "Teklif İste",
    stepOf: (a, b) => `Adım ${a} / ${b}`,
    machineQ: "Hangi makineyi istiyorsun?",
    machineSub: "İhtiyaca en yakın türü seç.",
    machines: [
      { v: "Makaslı Platform", s: "Dikey · 6–18 m" },
      { v: "Eklemli Platform", s: "Engel üstü · 12–43 m" },
      { v: "Teleskopik Platform", s: "Düz uzun · 18–58 m" },
      { v: "Sepetli Platform", s: "Araç üstü · 20–105 m" },
      { v: "Forklift", s: "1.5 – 10 ton" },
      { v: "Karar vermedim", s: "Danışmanla konuş" },
    ],
    heightQ: "Yaklaşık yükseklik?",
    heights: ["0–10 m", "10–20 m", "20–40 m", "40+ m"],
    rentalQ: "Nasıl kiralamak istiyorsun?",
    rentals: [
      { v: "Operatörlü", s: "SRC belgeli sürücü dahil" },
      { v: "Kuru (operatörsüz)", s: "Kullanıcı eğitimi dahil" },
    ],
    durationQ: "Kiralama süresi?",
    durations: ["Günlük", "Haftalık", "Aylık", "Proje (3+ ay)"],
    infoTitle: "Seninle nasıl iletişime geçelim?",
    fields: {
      name: "Ad Soyad",
      company: "Firma",
      phone: "Telefon",
      email: "E-mail",
      startDate: "Başlangıç Tarihi",
      city: "Şehir",
      details: "Ek notlar",
    },
    confirmTitle: "Özet",
    confirmSub: "Gönderdikten sonra 30 dk içinde dönüyoruz.",
    successT: "Teklif talebi alındı.",
    successS: "Uzmanımız 30 dakika içinde telefondan geri dönecek. Acil durumlarda aşağıdaki numarayı arayabilirsin.",
    successRef: "Referans",
    errReq: "Zorunlu alan",
    errEmail: "Geçersiz e-mail",
  } : {
    steps: ["MACHINE", "PERIOD", "CONTACT", "REVIEW"],
    next: "Next",
    back: "Back",
    submit: "Request Quote",
    stepOf: (a, b) => `Step ${a} / ${b}`,
    machineQ: "Which machine do you need?",
    machineSub: "Pick the closest type.",
    machines: [
      { v: "Scissor Lift", s: "Vertical · 6–18 m" },
      { v: "Articulating Boom", s: "Over-obstacle · 12–43 m" },
      { v: "Telescopic Boom", s: "Long straight · 18–58 m" },
      { v: "Truck-Mounted", s: "Truck basket · 20–105 m" },
      { v: "Forklift", s: "1.5 – 10 ton" },
      { v: "Not sure yet", s: "Talk to an advisor" },
    ],
    heightQ: "Approx. height?",
    heights: ["0–10 m", "10–20 m", "20–40 m", "40+ m"],
    rentalQ: "Rental type?",
    rentals: [
      { v: "Operated", s: "SRC certified driver included" },
      { v: "Dry (no operator)", s: "User training included" },
    ],
    durationQ: "Rental period?",
    durations: ["Daily", "Weekly", "Monthly", "Project (3+ mo)"],
    infoTitle: "How should we reach you?",
    fields: {
      name: "Full name",
      company: "Company",
      phone: "Phone",
      email: "Email",
      startDate: "Start date",
      city: "City",
      details: "Notes",
    },
    confirmTitle: "Summary",
    confirmSub: "We'll call back within 30 minutes.",
    successT: "Quote request received.",
    successS: "Our specialist will call you back within 30 minutes. For urgent requests please call the number below.",
    successRef: "Reference",
    errReq: "Required",
    errEmail: "Invalid email",
  };

  const setField = (k, v) => setData(d => ({ ...d, [k]: v }));

  const validate = () => {
    const e = {};
    if (step === 0) {
      if (!data.machine) e.machine = T.errReq;
      if (!data.height) e.height = T.errReq;
    } else if (step === 1) {
      if (!data.rental) e.rental = T.errReq;
      if (!data.duration) e.duration = T.errReq;
    } else if (step === 2) {
      if (!data.name) e.name = T.errReq;
      if (!data.phone) e.phone = T.errReq;
      if (data.email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email)) e.email = T.errEmail;
    }
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (!validate()) return;
    if (step < 3) setStep(s => s + 1);
  };
  const back = () => setStep(s => Math.max(0, s - 1));

  const submit = async () => {
    setSubmitting(true);
    setSubmitErr("");
    try {
      const body = new URLSearchParams({
        name:      data.name,
        phone:     data.phone,
        email:     data.email,
        company:   data.company,
        city:      data.city,
        machine:   data.machine,
        height:    data.height,
        rental:    data.rental,
        duration:  data.duration,
        startDate: data.startDate,
        message:   data.details,
      });
      const res = await fetch("send_mail.php", { method: "POST", body });
      const json = await res.json();
      if (json.ok) {
        const r = "AVK-" + Math.random().toString(36).slice(2, 7).toUpperCase() + "-" + new Date().getFullYear();
        setRef(r);
        setDone(true);
      } else {
        setSubmitErr(json.error || (lang === "tr" ? "Gönderim başarısız." : "Submission failed."));
      }
    } catch (e) {
      setSubmitErr(lang === "tr" ? "Bağlantı hatası. Lütfen telefon ile arayın." : "Connection error. Please call us directly.");
    } finally {
      setSubmitting(false);
    }
  };

  if (done) {
    return (
      <div className="form-success">
        <div className="check">✓</div>
        <h3>{T.successT}</h3>
        <p>{T.successS}</p>
        <div className="ref">{T.successRef}: {ref}</div>
        <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
          <a href="tel:+903123955862" className="btn btn-primary btn-arrow">0312 395 58 62</a>
          <button className="btn btn-ghost" onClick={() => { setDone(false); setStep(0); setData({ ...data, machine: "", height: "", rental: "", duration: "", name: "", company: "", phone: "", email: "", details: "" }); if (onDone) onDone(); }}>{lang === "tr" ? "Yeni teklif" : "New quote"}</button>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="steps">
        {T.steps.map((s, i) => (
          <div key={i} className={"step " + (i < step ? "done" : i === step ? "current" : "")}>
            <div className="step-label">0{i+1} · {s}</div>
          </div>
        ))}
      </div>

      {step === 0 && (
        <>
          <div className="field">
            <label>{T.machineQ}</label>
            <div className="choice-grid">
              {T.machines.map(m => (
                <div key={m.v} className={"choice " + (data.machine === m.v ? "selected" : "")} onClick={() => setField("machine", m.v)}>
                  <div className="ch-title">{m.v}</div>
                  <div className="ch-sub">{m.s}</div>
                </div>
              ))}
            </div>
            {errs.machine && <div className="err-msg">{errs.machine}</div>}
          </div>
          <div className="field">
            <label>{T.heightQ}</label>
            <div className="choice-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
              {T.heights.map(h => (
                <div key={h} className={"choice " + (data.height === h ? "selected" : "")} onClick={() => setField("height", h)}>
                  <div className="ch-title" style={{ textAlign: "center" }}>{h}</div>
                </div>
              ))}
            </div>
            {errs.height && <div className="err-msg">{errs.height}</div>}
          </div>
        </>
      )}

      {step === 1 && (
        <>
          <div className="field">
            <label>{T.rentalQ}</label>
            <div className="choice-grid">
              {T.rentals.map(m => (
                <div key={m.v} className={"choice " + (data.rental === m.v ? "selected" : "")} onClick={() => setField("rental", m.v)}>
                  <div className="ch-title">{m.v}</div>
                  <div className="ch-sub">{m.s}</div>
                </div>
              ))}
            </div>
            {errs.rental && <div className="err-msg">{errs.rental}</div>}
          </div>
          <div className="field">
            <label>{T.durationQ}</label>
            <div className="choice-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
              {T.durations.map(h => (
                <div key={h} className={"choice " + (data.duration === h ? "selected" : "")} onClick={() => setField("duration", h)}>
                  <div className="ch-title" style={{ textAlign: "center" }}>{h}</div>
                </div>
              ))}
            </div>
            {errs.duration && <div className="err-msg">{errs.duration}</div>}
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <div className={"field " + (errs.name ? "err" : "")}>
              <label>{T.fields.name} *</label>
              <input value={data.name} onChange={e => setField("name", e.target.value)} />
              {errs.name && <div className="err-msg">{errs.name}</div>}
            </div>
            <div className="field">
              <label>{T.fields.company}</label>
              <input value={data.company} onChange={e => setField("company", e.target.value)} />
            </div>
            <div className={"field " + (errs.phone ? "err" : "")}>
              <label>{T.fields.phone} *</label>
              <input value={data.phone} onChange={e => setField("phone", e.target.value)} placeholder="0555 000 00 00" />
              {errs.phone && <div className="err-msg">{errs.phone}</div>}
            </div>
            <div className={"field " + (errs.email ? "err" : "")}>
              <label>{T.fields.email}</label>
              <input value={data.email} onChange={e => setField("email", e.target.value)} />
              {errs.email && <div className="err-msg">{errs.email}</div>}
            </div>
            <div className="field">
              <label>{T.fields.startDate}</label>
              <input type="date" value={data.startDate} onChange={e => setField("startDate", e.target.value)} />
            </div>
            <div className="field">
              <label>{T.fields.city}</label>
              <select value={data.city} onChange={e => setField("city", e.target.value)}>
                {["Ankara","Konya","Eskişehir","Kayseri","Sivas","Çankırı","Diğer"].map(c => <option key={c}>{c}</option>)}
              </select>
            </div>
          </div>
          <div className="field">
            <label>{T.fields.details}</label>
            <textarea value={data.details} onChange={e => setField("details", e.target.value)} placeholder={lang === "tr" ? "Şantiye adresi, özel koşullar, iş tanımı..." : "Site address, special requirements..."} />
          </div>
        </>
      )}

      {step === 3 && (
        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-3)", letterSpacing: ".1em", textTransform: "uppercase", marginBottom: 16 }}>{T.confirmTitle}</div>
          <div style={{ border: "1px solid var(--line)", background: "var(--bg-2)" }}>
            {[
              [T.steps[0], data.machine + " · " + data.height],
              [T.steps[1], data.rental + " · " + data.duration],
              [T.fields.name, data.name + (data.company ? " · " + data.company : "")],
              [T.fields.phone, data.phone + (data.email ? " · " + data.email : "")],
              [T.fields.startDate + " / " + T.fields.city, (data.startDate || "—") + " · " + data.city],
              [T.fields.details, data.details || "—"],
            ].map(([k, v], i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "140px 1fr", padding: "12px 16px", borderBottom: "1px solid var(--line)", gap: 16 }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)", letterSpacing: ".1em", textTransform: "uppercase", alignSelf: "center" }}>{k}</div>
                <div style={{ fontSize: 14 }}>{v}</div>
              </div>
            ))}
          </div>
          <p style={{ marginTop: 16, color: "var(--fg-2)", fontSize: 14 }}>{T.confirmSub}</p>
        </div>
      )}

      {submitErr && <div style={{ color: "var(--danger)", fontFamily: "var(--font-mono)", fontSize: 12, marginTop: 12, padding: "10px 14px", border: "1px solid var(--danger)", background: "color-mix(in srgb, var(--danger) 8%, transparent)" }}>{submitErr}</div>}
      <div className="form-actions">
        <div className="step-info">{T.stepOf(step + 1, 4)}</div>
        <div style={{ display: "flex", gap: 10 }}>
          {step > 0 && <button className="btn btn-ghost" onClick={back} disabled={submitting}>{T.back}</button>}
          {step < 3 && <button className="btn btn-primary btn-arrow" onClick={next}>{T.next}</button>}
          {step === 3 && <button className="btn btn-primary btn-arrow" onClick={submit} disabled={submitting}>{submitting ? (lang === "tr" ? "Gönderiliyor…" : "Sending…") : T.submit}</button>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { QuoteForm });
