/* Quote Connect — Quote request flow */

function Field({ f, value, onChange }) {
  const id = "f-" + f.name;
  return (
    <label className="qf-field" htmlFor={id}>
      <span className="qf-label">{f.label}{f.required && <i className="qf-req">required</i>}</span>
      {f.type === "textarea" ? (
        <textarea id={id} rows={3} value={value || ""} placeholder={f.placeholder || ""} onChange={(e) => onChange(f.name, e.target.value)} />
      ) : f.type === "select" ? (
        <div className="qf-select-wrap">
          <select id={id} value={value || ""} onChange={(e) => onChange(f.name, e.target.value)}>
            <option value="" disabled>Select…</option>
            {f.options.map((o) => <option key={o} value={o}>{o}</option>)}
          </select>
          <Icon name="chevron-down" size={16} />
        </div>
      ) : (
        <input id={id} type="text" value={value || ""} placeholder={f.placeholder || ""} onChange={(e) => onChange(f.name, e.target.value)} />
      )}
    </label>
  );
}

function QuoteScreen({ nav, t, catId }) {
  const { byId, fieldsFor, SUPPLIERS } = window.QC_DATA;
  const cat = byId(catId) || window.QC_DATA.CATEGORIES[0];
  const hasSubs = cat.subs.length > 0;
  const fields = fieldsFor(cat);

  const stepDefs = [
    hasSubs && { key: "brand", label: "Brand / Type" },
    { key: "spec", label: "Specifications" },
    { key: "contact", label: "Contact & delivery" },
  ].filter(Boolean);

  const [step, setStep] = React.useState(0);
  const [sub, setSub] = React.useState("");
  const [subQ, setSubQ] = React.useState("");
  const [form, setForm] = React.useState({});
  const [contact, setContact] = React.useState({ region: "" });
  const [phase, setPhase] = React.useState("form"); // form | sending | done

  const cur = stepDefs[step];
  const total = stepDefs.length;
  const onForm = (k, v) => setForm((p) => ({ ...p, [k]: v }));
  const onContact = (k, v) => setContact((p) => ({ ...p, [k]: v }));

  const canNext = () => {
    if (cur.key === "brand") return !!sub;
    if (cur.key === "spec") { const req = fields.filter((f) => f.required); return req.every((f) => (form[f.name] || "").trim()); }
    if (cur.key === "contact") return contact.first && contact.email && contact.region;
    return true;
  };

  const submit = () => {
    setPhase("sending");
    setTimeout(() => setPhase("done"), 2600);
  };

  const subList = cat.subs.filter((s) => !subQ || s.toLowerCase().includes(subQ.toLowerCase()));

  if (phase === "done") {
    return (
      <div className="screen quote-screen">
        <div className="qc-wrap-narrow qf-done">
          <div className="qf-done-mark"><Icon name="check" size={34} stroke={2.5} /></div>
          <div className="eyebrow">Enquiry QC-{4900 + cat.code.length} · received</div>
          <h1 className="display qf-done-h">Thanks — your enquiry is with the Quote Connect team.</h1>
          <p className="qf-done-sub">No account needed. We’ve received your {cat.name.toLowerCase()} enquiry and our team is matching it to the right verified suppliers now. We’ll be in touch by email or phone — usually within {cat.eta}.</p>
          <div className="qf-done-card card">
            {[["inbox", "Your enquiry reached us", "It’s landed with the Quote Connect team for review."],
              ["users", "We find the right suppliers", "We match your enquiry to verified suppliers who can deliver."],
              ["phone-call", "We come back to you", "You’ll hear from us directly with quotes — nothing to chase."]].map(([ic, h, d]) => (
              <div key={h} className="qf-done-row"><span className="qf-done-ic"><Icon name={ic} size={18} /></span><div><b>{h}</b><span>{d}</span></div></div>
            ))}
          </div>
          <div className="qf-done-actions">
            <Btn variant="primary" size="lg" onClick={() => nav.go("browse")}>Send another enquiry <Icon name="arrow-right" size={17} /></Btn>
            <Btn variant="outline" size="lg" onClick={() => nav.go("home")}>Back to home</Btn>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="screen quote-screen">
      <div className="qc-wrap qf-layout">
        {/* MAIN */}
        <div className="qf-main">
          <button className="qf-back" onClick={() => nav.go("browse")}><Icon name="arrow-left" size={15} /> All categories</button>
          <div className="qf-head">
            <CatVisual cat={cat} iconStyle="photo" size={52} radius={10} />
            <div>
              <div className="eyebrow">{cat.code} · Quote enquiry</div>
              <h1 className="display qf-title">{cat.name}</h1>
            </div>
          </div>

          {/* progress */}
          <div className="qf-prog">
            {stepDefs.map((s, i) => (
              <div key={s.key} className={"qf-prog-step" + (i === step ? " on" : "") + (i < step ? " done" : "")}>
                <span className="qf-prog-dot mono">{i < step ? "✓" : i + 1}</span>
                <span className="qf-prog-label">{s.label}</span>
              </div>
            ))}
            <span className="qf-prog-count mono">{step + 1}/{total}</span>
          </div>

          {phase === "sending" ? (
            <div className="qf-sending card">
              <div className="qf-sending-ring"><span /><span /><span /></div>
              <h3 className="display">Sending your enquiry…</h3>
              <p className="mono">Delivering to the Quote Connect team</p>
              <div className="qf-sending-avatars">
                {SUPPLIERS.map((s, i) => (
                  <span key={s.id} className="qf-sending-av" style={{ animationDelay: i * 0.18 + "s" }}>
                    <SupAvatar sup={s} size={34} />
                  </span>
                ))}
              </div>
            </div>
          ) : (
            <div className="qf-card card">
              {cur.key === "brand" && (
                <div>
                  <h3 className="qf-step-title">Which brand or type?</h3>
                  <p className="qf-step-sub">Pick one — or the closest. Suppliers will quote alternatives too.</p>
                  <div className="qf-subsearch"><Icon name="search" size={15} />
                    <input value={subQ} onChange={(e) => setSubQ(e.target.value)} placeholder={"Search " + cat.subs.length + " options"} />
                  </div>
                  <div className="qf-subs">
                    {subList.map((s) => (
                      <button key={s} className={"qf-sub" + (sub === s ? " on" : "")} onClick={() => setSub(s)}>{s}</button>
                    ))}
                    <button className={"qf-sub other" + (sub === "Not sure / other" ? " on" : "")} onClick={() => setSub("Not sure / other")}>Not sure / other</button>
                  </div>
                </div>
              )}
              {cur.key === "spec" && (
                <div>
                  <h3 className="qf-step-title">Tell us the spec</h3>
                  <p className="qf-step-sub">Only what you know. The more detail, the sharper the quotes.</p>
                  <div className="qf-fields">{fields.map((f) => <Field key={f.name} f={f} value={form[f.name]} onChange={onForm} />)}</div>
                  <label className="qf-upload"><Icon name="paperclip" size={16} /> Attach a list or drawing <span className="mono">optional</span></label>
                </div>
              )}
              {cur.key === "contact" && (
                <div>
                  <h3 className="qf-step-title">How should we reach you?</h3>
                  <p className="qf-step-sub">No sign-up needed — just your details so our team can come back to you with quotes. Stays private; never sold.</p>
                  <div className="qf-fields two">
                    <label className="qf-field"><span className="qf-label">First name<i className="qf-req">required</i></span>
                      <input value={contact.first || ""} onChange={(e) => onContact("first", e.target.value)} /></label>
                    <label className="qf-field"><span className="qf-label">Last name</span>
                      <input value={contact.last || ""} onChange={(e) => onContact("last", e.target.value)} /></label>
                    <label className="qf-field"><span className="qf-label">Email<i className="qf-req">required</i></span>
                      <input value={contact.email || ""} onChange={(e) => onContact("email", e.target.value)} /></label>
                    <label className="qf-field"><span className="qf-label">Phone</span>
                      <input value={contact.phone || ""} onChange={(e) => onContact("phone", e.target.value)} /></label>
                    <label className="qf-field full"><span className="qf-label">Region<i className="qf-req">required</i></span>
                      <div className="qf-select-wrap">
                        <select value={contact.region} onChange={(e) => onContact("region", e.target.value)}>
                          <option value="" disabled>Select your region…</option>
                          {window.QC_DATA.STATES.map((s) => <option key={s} value={s}>{s}</option>)}
                        </select>
                        <Icon name="chevron-down" size={16} />
                      </div></label>
                  </div>
                </div>
              )}
            </div>
          )}

          {phase === "form" && (
            <div className="qf-nav">
              <Btn variant="ghost" onClick={() => (step === 0 ? nav.go("browse") : setStep((s) => s - 1))}>
                <Icon name="arrow-left" size={16} /> {step === 0 ? "Cancel" : "Back"}
              </Btn>
              {step < total - 1 ? (
                <Btn variant="dark" size="lg" disabled={!canNext()} onClick={() => setStep((s) => s + 1)}>Continue <Icon name="arrow-right" size={17} /></Btn>
              ) : (
                <Btn variant="primary" size="lg" disabled={!canNext()} onClick={submit}>Send enquiry <Icon name="send" size={16} /></Btn>
              )}
            </div>
          )}
        </div>

        {/* TRUST RAIL */}
        <aside className="qf-rail">
          <div className="qf-rail-card card">
            <div className="qf-rail-h">
              <span className="qf-rail-pulse" />
              <span className="mono">{cat.suppliers} suppliers in network</span>
            </div>
            <p className="qf-rail-lead">Our team matches your {cat.name.toLowerCase()} enquiry to verified suppliers who can deliver — no account, no chasing.</p>
            <div className="qf-rail-avatars">
              {SUPPLIERS.slice(0, 4).map((s) => <SupAvatar key={s.id} sup={s} size={36} />)}
              <span className="qf-rail-more mono">+{cat.suppliers - 4}</span>
            </div>
            <hr className="rule-dot" />
            <div className="qf-rail-specs">
              <Spec k="Typical response" v={cat.eta} accent />
              <Spec k="Cost to you" v="$0 — always free" />
              <Spec k="Account needed" v="None — just enquire" />
            </div>
          </div>
          <div className="qf-rail-note">
            <Icon name="lock" size={14} /> <span>We never sell your data. Your enquiry goes only to the Quote Connect team.</span>
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { QuoteScreen });
