// ─────────── Contact + Quote ───────────

/* ─────────────────────── Contact ─────────────────────── */

function ContactPage({ setRoute }) {
  const t = window.__T;
  const lang = window.__LANG;
  const whatsappLink = "https://wa.me/902126535300?text=" + encodeURIComponent("Merhaba, bilgi almak istiyorum.");

  const [form, setForm] = useState({ name: "", company: "", phone: "", email: "", topic: "sales", msg: "" });
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  return (
    <>
      <PageHero
        eyebrow={t.contact.eyebrow}
        title={t.contact.title}
        lead={t.contact.lead}
        code="C.00"
      />

      <section className="section compact">
        <div className="container">
          <div className="contact-grid">
            <div className="contact-info">
              <div className="ci-block">
                <span className="idx">C.01</span>
                <h3 className="h-display x3">{t.contact.hq}</h3>
                <div className="ci-fields">
                  <div><span>{lang === "tr" ? "Adres" : "Address"}</span><b>Yenibosna Merkez Mah., Ayvaz Cami Sok., No:1/A<br />Bahçelievler / İstanbul</b></div>
                  <div><span>{lang === "tr" ? "Telefon" : "Phone"}</span><b><a href="tel:02126535300" style={{color:"inherit"}}>0212 653 53 00</a></b></div>
                  <div><span>WhatsApp</span><b><a href={whatsappLink} target="_blank" rel="noopener" style={{color:"inherit"}}>+90 212 653 53 00</a></b></div>
                  <div><span>{lang === "tr" ? "E-posta" : "E-mail"}</span><b><a href="mailto:info@anadoluinsaat.com" style={{color:"inherit"}}>info@anadoluinsaat.com</a></b></div>
                </div>
              </div>

              <div className="ci-block">
                <span className="idx">C.02</span>
                <h3 className="h-display x3">{t.contact.hours}</h3>
                <div className="ci-fields">
                  <div><span>{lang === "tr" ? "Pzt — Cmt" : "Mon — Sat"}</span><b>08:00 — 18:00</b></div>
                  <div><span>{lang === "tr" ? "Pazar" : "Sun"}</span><b>{lang === "tr" ? "Kapalı" : "Closed"}</b></div>
                </div>
              </div>

              <div className="ci-block">
                <span className="idx">C.03</span>
                <h3 className="h-display x3">{lang === "tr" ? "Hızlı İletişim" : "Quick Contact"}</h3>
                <div className="ci-fields" style={{gap: 10}}>
                  <a href={whatsappLink} target="_blank" rel="noopener"
                     style={{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",background:"#1a2a1a",border:"1px solid #2a4a2a",color:"#60c080",textDecoration:"none",fontWeight:600}}>
                    <span>WhatsApp ile Yaz</span><Arr size={10}/>
                  </a>
                  <a href="tel:02126535300"
                     style={{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",background:"var(--surface)",border:"1px solid var(--line)",color:"var(--text)",textDecoration:"none",fontWeight:600}}>
                    <span>0212 653 53 00</span><Arr size={10}/>
                  </a>
                  <a href="https://maps.google.com/maps?q=Anadolu+Insaat+Bahcelievler+Istanbul"
                     target="_blank" rel="noopener"
                     style={{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",background:"var(--surface)",border:"1px solid var(--line)",color:"var(--text-mute)",textDecoration:"none",fontSize:13}}>
                    <span>{lang === "tr" ? "Yol Tarifi Al" : "Get Directions"}</span><Arr size={10}/>
                  </a>
                </div>
              </div>
            </div>

            <div className="contact-form">
              <div className="cf-head">
                <span className="idx">F.01</span>
                <h3 className="h-display x3">
                  {lang === "tr" ? "Bize yazın." : "Send a message."}
                </h3>
                <p style={{ color: "var(--text-mute)", fontSize: 13 }}>
                  {lang === "tr"
                    ? "Mesai saatlerinde 2 saat içinde dönüş yaparız."
                    : "We respond within 2 hours during business hours."}
                </p>
              </div>
              {sent ? (
                <div className="thanks-box">
                  <Mark size={32} />
                  <h4 className="h-display x3">{lang === "tr" ? "Teşekkürler." : "Thanks."}</h4>
                  <p>{lang === "tr" ? "Mesajınız iletildi. En kısa sürede dönüş yapacağız." : "Your message has been sent. We'll get back to you soon."}</p>
                  <button className="btn" onClick={() => setSent(false)}>{lang === "tr" ? "Yeni mesaj" : "New message"}</button>
                </div>
              ) : (
                <form
                  className="cform"
                  onSubmit={async (e) => {
                    e.preventDefault();
                    setSubmitting(true);
                    setSubmitError("");
                    try {
                      const res = await fetch("quote-submit.php", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ type: "message", ...form }),
                      });
                      const j = await res.json();
                      if (j.ok) {
                        setSent(true);
                      } else {
                        setSubmitError(j.error || "Bir hata oluştu, lütfen tekrar deneyin.");
                      }
                    } catch (_) {
                      setSent(true);
                    }
                    setSubmitting(false);
                  }}
                >
                  <div className="cf-row">
                    <Field label={lang === "tr" ? "Ad Soyad" : "Full name"} value={form.name}
                      onChange={(v) => setForm({ ...form, name: v })} required />
                    <Field label={lang === "tr" ? "Firma" : "Company"} value={form.company}
                      onChange={(v) => setForm({ ...form, company: v })} />
                  </div>
                  <div className="cf-row">
                    <Field label={lang === "tr" ? "Telefon" : "Phone"} value={form.phone}
                      onChange={(v) => setForm({ ...form, phone: v })} required />
                    <Field label="E-mail" value={form.email}
                      onChange={(v) => setForm({ ...form, email: v })} type="email" />
                  </div>

                  <div className="cf-row">
                    <div className="field">
                      <label>{lang === "tr" ? "Konu" : "Topic"}</label>
                      <div className="topic-row">
                        {["sales", "support", "dealer", "career"].map((tp) => (
                          <button
                            key={tp}
                            type="button"
                            onClick={() => setForm({ ...form, topic: tp })}
                            className={form.topic === tp ? "act" : ""}
                          >
                            {({
                              sales: lang === "tr" ? "Satış" : "Sales",
                              support: lang === "tr" ? "Teknik" : "Support",
                              dealer: lang === "tr" ? "Bayilik" : "Dealer",
                              career: lang === "tr" ? "Kariyer" : "Career",
                            })[tp]}
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>

                  <Field label={lang === "tr" ? "Mesaj" : "Message"} value={form.msg}
                    onChange={(v) => setForm({ ...form, msg: v })} ta />

                  <div className="cf-bot">
                    <small style={{ color: "var(--text-dim)", fontSize: 11 }}>
                      {lang === "tr"
                        ? "Form göndererek KVKK aydınlatma metnini kabul etmiş olursunuz."
                        : "By submitting, you accept our data policy."}
                    </small>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
                      {submitError && (
                        <span style={{ color: "#e06060", fontSize: 12 }}>{submitError}</span>
                      )}
                      <button type="submit" className="btn solid" disabled={submitting}>
                        {submitting ? "..." : (lang === "tr" ? "Gönder" : "Send")} {!submitting && <Arr />}
                      </button>
                    </div>
                  </div>
                </form>
              )}
            </div>
          </div>

          {/* map placeholder */}
          <div className="map-strip">
            <div className="map-frame">
              <div className="map-bg">
                {/* abstract map: grid + pins */}
                <svg viewBox="0 0 1320 320" preserveAspectRatio="none" style={{ width: "100%", height: "100%", display: "block" }}>
                  <defs>
                    <pattern id="g" width="40" height="40" patternUnits="userSpaceOnUse">
                      <path d="M40 0 L0 0 0 40" fill="none" stroke="var(--line)" strokeWidth="0.5" />
                    </pattern>
                  </defs>
                  <rect width="100%" height="100%" fill="url(#g)" />
                  {/* coast line abstract */}
                  <path d="M0 200 Q200 160 400 180 T800 170 T1200 190 L1320 220 L1320 320 L0 320 Z"
                    fill="var(--surface)" stroke="var(--line-strong)" />
                  {[[260, 180, "Kayseri"], [480, 130, "Ankara"], [200, 90, "İstanbul"], [120, 200, "İzmir"], [620, 220, "Gaziantep"], [380, 200, "Konya"], [160, 150, "Bursa"]].map(([x, y, name], i) => (
                    <g key={i}>
                      <circle cx={x} cy={y} r="4" fill="var(--accent)" />
                      <circle cx={x} cy={y} r="14" fill="none" stroke="var(--accent)" strokeOpacity="0.4" />
                      <text x={x + 18} y={y + 4} fill="var(--text-mute)" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em">{name.toUpperCase()}</text>
                    </g>
                  ))}
                </svg>
              </div>
              <div className="map-overlay">
                <span className="idx">M.01 — BAHÇELİEVLER / İSTANBUL — TÜRKİYE GENELİ TESLİMAT</span>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

function Field({ label, value, onChange, type = "text", required, ta }) {
  return (
    <div className="field">
      <label>{label}{required && <span style={{ color: "var(--accent)" }}> *</span>}</label>
      {ta ? (
        <textarea rows="4" value={value} onChange={(e) => onChange(e.target.value)} required={required} />
      ) : (
        <input type={type} value={value} onChange={(e) => onChange(e.target.value)} required={required} />
      )}
    </div>
  );
}

/* ─────────────────────── Quote (multi-step) ─────────────────────── */

function QuotePage({ setRoute }) {
  const t = window.__T;
  const lang = window.__LANG;
  const cats = window.__DATA.productCategories;
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    company: "",
    contact: "",
    phone: "",
    email: "",
    project: "",
    sector: "",
    city: "",
    deadline: "",
    categories: [],
    lines: [{ code: "", item: "", qty: "", unit: "adet" }],
    note: "",
  });
  const [done, setDone] = useState(false);
  const [quoteRef, setQuoteRef] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const steps = [
    { id: "company", label: lang === "tr" ? "Firma" : "Company" },
    { id: "project", label: lang === "tr" ? "Proje" : "Project" },
    { id: "items", label: lang === "tr" ? "Kalemler" : "Items" },
    { id: "confirm", label: lang === "tr" ? "Onay" : "Confirm" },
  ];

  function addLine() {
    setData({ ...data, lines: [...data.lines, { code: "", item: "", qty: "", unit: "adet" }] });
  }
  function setLine(i, k, v) {
    const lines = data.lines.slice();
    lines[i] = { ...lines[i], [k]: v };
    setData({ ...data, lines });
  }
  function removeLine(i) {
    if (data.lines.length === 1) return;
    setData({ ...data, lines: data.lines.filter((_, j) => j !== i) });
  }
  function toggleCat(id) {
    const has = data.categories.includes(id);
    setData({
      ...data,
      categories: has ? data.categories.filter((x) => x !== id) : [...data.categories, id],
    });
  }

  async function handleSubmit() {
    setSubmitting(true);
    try {
      const res = await fetch("quote-submit.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type: "quote", ...data }),
      });
      const j = await res.json();
      if (j.ref) setQuoteRef(j.ref);
    } catch (_) {}
    setDone(true);
    setSubmitting(false);
  }

  if (done) {
    return (
      <>
        <PageHero eyebrow={t.quote.eyebrow} title={[t.quote.thanks]} code="Q.99" />
        <section className="section" style={{ paddingTop: 0 }}>
          <div className="container" style={{ maxWidth: 720 }}>
            <div className="thanks-box big">
              <Mark size={48} />
              <h3 className="h-display x2" style={{ marginTop: 24 }}>{t.quote.thanks}</h3>
              <p style={{ color: "var(--text-mute)", fontSize: 16, maxWidth: 480, textAlign: "center" }}>
                {t.quote.thanksLead}
              </p>
              <div className="thx-meta">
                <div><span>REF</span><b>{quoteRef ? "#" + quoteRef : "—"}</b></div>
                <div><span>{lang === "tr" ? "Firma" : "Company"}</span><b>{data.company || "—"}</b></div>
                <div><span>{lang === "tr" ? "Kalem" : "Lines"}</span><b>{data.lines.filter(l => l.item).length}</b></div>
                <div><span>{lang === "tr" ? "Termin" : "Deadline"}</span><b>{data.deadline || "—"}</b></div>
              </div>
              <div className="row" style={{ marginTop: 32 }}>
                <button className="btn" onClick={() => setRoute("home")}>{t.nav.home}</button>
                <button className="btn ghost" onClick={() => { setDone(false); setStep(0); }}>
                  {lang === "tr" ? "Yeni teklif" : "New quote"}
                </button>
              </div>
            </div>
          </div>
        </section>
      </>
    );
  }

  return (
    <>
      <PageHero
        eyebrow={t.quote.eyebrow}
        title={t.quote.title}
        lead={t.quote.lead}
        code="Q.00"
      />

      <section className="section" style={{ paddingTop: 0 }}>
        <div className="container" style={{ maxWidth: 1020 }}>
          {/* stepper */}
          <div className="qstepper">
            {steps.map((s, i) => (
              <div key={s.id} className={`qstep ${i === step ? "act" : ""} ${i < step ? "done" : ""}`}
                onClick={() => i < step && setStep(i)}>
                <span className="qs-n">0{i + 1}</span>
                <span className="qs-l">{s.label}</span>
              </div>
            ))}
          </div>

          <div className="qbody">
            {step === 0 && (
              <div className="qcol">
                <h3 className="h-display x3">{lang === "tr" ? "Firma bilgileri" : "Company info"}</h3>
                <div className="cf-row">
                  <Field label={lang === "tr" ? "Firma adı" : "Company name"} value={data.company}
                    onChange={(v) => setData({ ...data, company: v })} required />
                  <Field label={lang === "tr" ? "Yetkili kişi" : "Contact"} value={data.contact}
                    onChange={(v) => setData({ ...data, contact: v })} required />
                </div>
                <div className="cf-row">
                  <Field label={lang === "tr" ? "Telefon" : "Phone"} value={data.phone}
                    onChange={(v) => setData({ ...data, phone: v })} required />
                  <Field label="E-mail" value={data.email} type="email"
                    onChange={(v) => setData({ ...data, email: v })} required />
                </div>
              </div>
            )}

            {step === 1 && (
              <div className="qcol">
                <h3 className="h-display x3">{lang === "tr" ? "Proje detayları" : "Project details"}</h3>
                <div className="cf-row">
                  <Field label={lang === "tr" ? "Proje adı" : "Project name"} value={data.project}
                    onChange={(v) => setData({ ...data, project: v })} />
                  <div className="field">
                    <label>{lang === "tr" ? "Sektör" : "Sector"}</label>
                    <div className="topic-row">
                      {["Konut", "Ticari", "Endüstriyel", "Kamu", "Altyapı"].map((s) => (
                        <button key={s} type="button"
                          onClick={() => setData({ ...data, sector: s })}
                          className={data.sector === s ? "act" : ""}>{s}</button>
                      ))}
                    </div>
                  </div>
                </div>
                <div className="cf-row">
                  <Field label={lang === "tr" ? "Şehir" : "City"} value={data.city}
                    onChange={(v) => setData({ ...data, city: v })} />
                  <Field label={lang === "tr" ? "Termin (örn. 2026-06-30)" : "Deadline"} value={data.deadline}
                    onChange={(v) => setData({ ...data, deadline: v })} />
                </div>

                <div className="field" style={{ marginTop: 16 }}>
                  <label>{lang === "tr" ? "İlgili ürün aileleri" : "Product families"}</label>
                  <div className="cat-chips">
                    {cats.map((c) => (
                      <button key={c.id} type="button"
                        onClick={() => toggleCat(c.id)}
                        className={data.categories.includes(c.id) ? "chip act" : "chip"}>
                        <span>{c.code}</span> {c[lang]}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="qcol">
                <div className="spread" style={{ marginBottom: 16 }}>
                  <h3 className="h-display x3" style={{ margin: 0 }}>
                    {lang === "tr" ? "Malzeme listesi" : "Bill of materials"}
                  </h3>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-mute)" }}>
                    {data.lines.length} {lang === "tr" ? "kalem" : "lines"}
                  </span>
                </div>
                <div className="bom-table">
                  <div className="bom-head">
                    <span>#</span><span>{lang === "tr" ? "KOD" : "CODE"}</span>
                    <span>{lang === "tr" ? "ÜRÜN / AÇIKLAMA" : "ITEM / DESC."}</span>
                    <span>{lang === "tr" ? "MİKTAR" : "QTY"}</span>
                    <span>{lang === "tr" ? "BİRİM" : "UNIT"}</span>
                    <span></span>
                  </div>
                  {data.lines.map((l, i) => (
                    <div key={i} className="bom-row">
                      <span className="idx" style={{ width: "auto" }}>{String(i + 1).padStart(2, "0")}</span>
                      <input value={l.code} placeholder="STL-01" onChange={(e) => setLine(i, "code", e.target.value)} />
                      <input value={l.item} placeholder={lang === "tr" ? "Ürün adı" : "Item"} onChange={(e) => setLine(i, "item", e.target.value)} />
                      <input value={l.qty} placeholder="100" onChange={(e) => setLine(i, "qty", e.target.value)} />
                      <select value={l.unit} onChange={(e) => setLine(i, "unit", e.target.value)}>
                        {["adet", "kg", "ton", "m", "m²", "m³", "lt", "set", "rulo"].map((u) => <option key={u}>{u}</option>)}
                      </select>
                      <button className="bom-x" onClick={() => removeLine(i)} type="button">×</button>
                    </div>
                  ))}
                </div>
                <button className="btn ghost" style={{ marginTop: 16, alignSelf: "flex-start" }} type="button" onClick={addLine}>
                  + {lang === "tr" ? "Satır ekle" : "Add line"}
                </button>
                <div className="field" style={{ marginTop: 24 }}>
                  <label>{lang === "tr" ? "Not / dosya yükleme talebi" : "Note / file upload request"}</label>
                  <textarea rows="4" value={data.note} onChange={(e) => setData({ ...data, note: e.target.value })}
                    placeholder={lang === "tr" ? "Excel listenizi e-posta ile gönderebilirsiniz; biz formu bu nota göre dolduralım." : "You can e-mail your Excel list; we'll fill the form for you."} />
                </div>
              </div>
            )}

            {step === 3 && (
              <div className="qcol">
                <h3 className="h-display x3">{lang === "tr" ? "Özet ve onay" : "Summary & confirm"}</h3>
                <div className="qsummary">
                  <div className="qs-block">
                    <span className="idx">01 — {lang === "tr" ? "FİRMA" : "COMPANY"}</span>
                    <div className="qs-fields">
                      <div><span>{lang === "tr" ? "Firma" : "Company"}</span><b>{data.company || "—"}</b></div>
                      <div><span>{lang === "tr" ? "Yetkili" : "Contact"}</span><b>{data.contact || "—"}</b></div>
                      <div><span>{lang === "tr" ? "Telefon" : "Phone"}</span><b>{data.phone || "—"}</b></div>
                      <div><span>E-mail</span><b>{data.email || "—"}</b></div>
                    </div>
                  </div>
                  <div className="qs-block">
                    <span className="idx">02 — {lang === "tr" ? "PROJE" : "PROJECT"}</span>
                    <div className="qs-fields">
                      <div><span>{lang === "tr" ? "Proje" : "Project"}</span><b>{data.project || "—"}</b></div>
                      <div><span>{lang === "tr" ? "Sektör" : "Sector"}</span><b>{data.sector || "—"}</b></div>
                      <div><span>{lang === "tr" ? "Şehir" : "City"}</span><b>{data.city || "—"}</b></div>
                      <div><span>{lang === "tr" ? "Termin" : "Deadline"}</span><b>{data.deadline || "—"}</b></div>
                    </div>
                  </div>
                  <div className="qs-block">
                    <span className="idx">03 — {lang === "tr" ? "KALEMLER" : "ITEMS"}</span>
                    <div className="qs-lines">
                      {data.lines.filter(l => l.item || l.code).length === 0 ? (
                        <div className="qs-empty">{lang === "tr" ? "Kalem girilmedi" : "No lines"}</div>
                      ) : data.lines.filter(l => l.item || l.code).map((l, i) => (
                        <div key={i} className="qs-line">
                          <span className="idx">{String(i + 1).padStart(2, "0")}</span>
                          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-mute)" }}>{l.code || "—"}</span>
                          <span style={{ flex: 1 }}>{l.item || "—"}</span>
                          <span><b>{l.qty || "—"}</b> {l.unit}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="qnav">
            <button className="btn ghost" disabled={step === 0} onClick={() => setStep(step - 1)}>
              {t.quote.back}
            </button>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", color: "var(--text-mute)" }}>
              {t.quote.step} {String(step + 1).padStart(2, "0")} / 0{steps.length}
            </div>
            {step < steps.length - 1 ? (
              <button className="btn solid" onClick={() => setStep(step + 1)}>
                {t.quote.next} <Arr />
              </button>
            ) : (
              <button className="btn solid" onClick={handleSubmit} disabled={submitting}>
                {submitting ? "..." : t.quote.submit} {!submitting && <Arr />}
              </button>
            )}
          </div>
        </div>
      </section>
    </>
  );
}

Object.assign(window, { ContactPage, QuotePage, Field });
