// QUOTE page — multi-section quote form
const { useState: useStateQ } = React;

function QuoteApp() {
  const [lang, setLang] = useLang();
  const t = mergeT(lang);
  const qp = t.quote_page;
  const f = qp.form;
  const [submitted, setSubmitted] = useStateQ(false);
  const [submitting, setSubmitting] = useStateQ(false);
  const [error, setError] = useStateQ("");
  const [files, setFiles] = useStateQ([]);
  const onFiles = (list) => setFiles(Array.from(list || []).map(x => x.name));

  const ICN = { Mail: Icon.Mail, Calendar: Icon.Calendar, Clipboard: Icon.Clipboard };

  return (
    <>
      <Header lang={lang} setLang={setLang} t={t} active="quote" />
      <PageHero
        crumbs={[{ label: qp.crumb }]}
        eyebrow={qp.eyebrow}
        titlePre={qp.title_pre}
        titleAccent={qp.title_accent}
        lead={qp.lead}
      />
      <section className="section">
        <div className="container">
          <div className="quote-grid">
            <form className="quote-form" onSubmit={async (e) => {
              e.preventDefault();
              setError("");
              setSubmitting(true);
              const fd = new FormData(e.target);
              const timeline = fd.get("timeline") || "";
              const budget = fd.get("budget") || "";
              const payload = {
                name: fd.get("name") || "",
                phone: fd.get("phone") || "",
                email: fd.get("email") || "",
                address: fd.get("zip") || "",
                projectType: fd.get("projectType") || "",
                message: fd.get("message") || "",
                timeline: timeline,
                budget: budget,
              };
              try {
                const res = await fetch("/api/remodeling-quote", {
                  method: "POST",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify(payload),
                });
                const j = await res.json();
                if (j.success) {
                  setSubmitted(true);
                  window.scrollTo({ top: 0, behavior: "smooth" });
                } else {
                  setError(j.error || "Submission failed.");
                }
              } catch (err) {
                setError(lang === "en" ? "Network error. Please call (737) 354-7787." : "Error de red. Llama (737) 354-7787.");
              } finally {
                setSubmitting(false);
              }
            }}>
              {submitted && (
                <div style={{ background: "#ECF6E8", border: "1px solid var(--green)", color: "var(--green-dark)", padding: 18, borderRadius: 14, marginBottom: 20, fontWeight: 600 }}>
                  ✓ {lang === 'en'
                      ? "Thanks — your request is in. Expect to hear from us within one business day."
                      : "Gracias — recibimos tu solicitud. Te contactamos en menos de un día hábil."}
                </div>
              )}
              {error && (
                <div style={{ background: "#FDECEA", border: "1px solid #e74c3c", color: "#c0392b", padding: 16, borderRadius: 14, marginBottom: 20, fontWeight: 600 }}>
                  ⚠️ {error}
                </div>
              )}

              <h3>{f.h}</h3>

              <div className="form-section">
                <h4>{f.step1}</h4>
                <div className="form-row">
                  <div className="field">
                    <label>{f.name}</label>
                    <input type="text" name="name" required />
                  </div>
                  <div className="field">
                    <label>{f.phone}</label>
                    <input type="tel" name="phone" required />
                  </div>
                </div>
                <div className="form-row">
                  <div className="field">
                    <label>{f.email}</label>
                    <input type="email" name="email" required />
                  </div>
                  <div className="field">
                    <label>{f.zip}</label>
                    <input type="text" name="zip" pattern="[0-9]{5}" maxLength="5" />
                  </div>
                </div>
              </div>

              <div className="form-section">
                <h4>{f.step2}</h4>
                <div className="field">
                  <label>{f.type}</label>
                  <select name="projectType" required>
                    {f.type_options.map((o, i) => <option key={i} value={i === 0 ? "" : o}>{o}</option>)}
                  </select>
                </div>
                <div className="field">
                  <label>{f.message}</label>
                  <textarea name="message" rows="5" placeholder={f.message_ph}></textarea>
                </div>
              </div>

              <div className="form-section">
                <h4>{f.step3}</h4>
                <div className="form-row">
                  <div className="field">
                    <label>{f.timeline}</label>
                    <div className="chip-row">
                      {f.timeline_options.map((o, i) => (
                        <label className="chip" key={i}>
                          <input type="radio" name="timeline" defaultChecked={i === 1} />
                          {o.l}
                        </label>
                      ))}
                    </div>
                  </div>
                </div>
                <div className="form-row">
                  <div className="field">
                    <label>{f.budget}</label>
                    <div className="chip-row">
                      {f.budget_options.map((o, i) => (
                        <label className="chip" key={i}>
                          <input type="radio" name="budget" defaultChecked={i === 2} />
                          {o.l}
                        </label>
                      ))}
                    </div>
                  </div>
                </div>
                <div className="field">
                  <label>{f.scheduling}</label>
                  <div className="chip-row">
                    {f.scheduling_options.map((o, i) => (
                      <label className="chip" key={i}>
                        <input type="checkbox" defaultChecked={i === 0} />
                        {o.l}
                      </label>
                    ))}
                  </div>
                </div>
              </div>

              <div className="form-section">
                <h4>{f.step4}</h4>
                <label className="dropzone" onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); onFiles(e.dataTransfer.files); }}>
                  <input type="file" multiple style={{ display: "none" }} onChange={(e) => onFiles(e.target.files)} />
                  <Icon.Upload size={28} />
                  <div className="lbl">{f.upload_lbl}</div>
                  <div className="sub">{f.upload_sub}</div>
                  {files.length > 0 && (
                    <div className="sub" style={{ marginTop: 14, color: "var(--green-dark)", fontWeight: 600 }}>
                      {files.length} {lang === 'en' ? 'file(s) selected' : 'archivo(s) seleccionado(s)'}: {files.join(", ")}
                    </div>
                  )}
                </label>
              </div>

              <button type="submit" disabled={submitting} className="btn btn-primary" style={{ width: "100%", justifyContent: "center", padding: "18px 32px", fontSize: 16 }}>
                {f.submit} <Icon.ArrowRight size={16} />
              </button>
              <p style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 12, textAlign: "center" }}>{f.consent}</p>
            </form>

            <aside className="quote-side">
              <h4>{qp.side.h}</h4>
              <div className="steps">
                {qp.side.pts.map((p, i) => {
                  const Ic = ICN[p.ic] || Icon.Sparkle;
                  return (
                    <div className="row" key={i}>
                      <div className="ic"><Ic size={18} /></div>
                      <div>
                        <h5>{p.t}</h5>
                        <p>{p.s}</p>
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="quote-side-divider"></div>
              <h4 style={{ marginTop: 8 }}>{qp.side.h2}</h4>
              <a href={`tel:${qp.side.phone.replace(/\D/g, '')}`} className="big-phone">{qp.side.phone}</a>
              <div style={{ fontSize: 13, color: "rgba(255,255,255,0.65)" }}>{qp.side.phone_sub}</div>
            </aside>
          </div>
        </div>
      </section>
      <FooterMP lang={lang} t={t} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<QuoteApp />);
