// quote.jsx — instant quote: item-based, combined address field, saveable (14-day) with a quote number.
const { useState: useStateQ, useMemo: useMemoQ } = React;

const Q_METRO = new Set(["Sydney CBD","Surry Hills","Newtown","Bondi Junction","North Sydney","Alexandria","Mascot","Botany","Marrickville","Rhodes","Manly","Melbourne CBD","Richmond (VIC)","Brisbane CBD","South Brisbane","Perth CBD","Adelaide CBD","Canberra"]);
function quoteZoneAvail(from, to) {
  const ps = window.FX.suburbState(from), ds = window.FX.suburbState(to);
  if (ps && ds && ps !== ds) return { available: ["standard"], reason: "Interstate route — Next Flight or DC rate only for this lane." };
  if (from && to && (!Q_METRO.has(from) || !Q_METRO.has(to))) return { available: ["standard"], reason: "Out-of-area zone — DC rate only (express tiers unavailable here)." };
  return { available: ["standard", "premium", "direct"], reason: null };
}
function tierBreakdown({ vehicleId, km, serviceId, isReturn, rateMult }) {
  const base = window.FX.quote({ vehicleId, km: km || 0, serviceId, isReturn, rateMult });
  const baseEx = base.subtotal;                       // one-way + return, ex-GST
  const fuel = baseEx * window.FX.FUEL_LEVY_PCT;
  const sub = baseEx + fuel;
  const gst = sub * 0.1;
  return { baseEx, oneWay: base.oneWay, returnLeg: base.returnLeg, fuel, sub, gst, total: sub + gst };
}

function QuoteItemsEditor({ items, setItems }) {
  const setItem = (i, k, v) => setItems(prev => prev.map((it, idx) => idx === i ? { ...it, [k]: v } : it));
  const add = () => setItems(prev => [...prev, window.FX.blankItem()]);
  const rm = (i) => setItems(prev => prev.length > 1 ? prev.filter((_, idx) => idx !== i) : prev);
  return (
    <div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "54px 1.1fr 1fr 64px 26px", gap: 8, alignItems: "end", padding: 10, background: "var(--bg-mist)", borderRadius: "var(--r-md)" }}>
            <Field label={i === 0 ? "Qty" : ""}><TextInput type="number" value={it.qty} onChange={v => setItem(i, "qty", v)} mono /></Field>
            <Field label={i === 0 ? "Type" : ""}><Select value={it.type} onChange={v => setItems(prev => prev.map((x, idx) => idx === i ? { ...x, type: v, ...window.FX.typeDefaults(v) } : x))} options={window.FX.ITEM_TYPES} /></Field>
            <Field label={i === 0 ? "L×W×H (cm)" : ""}>
              <div style={{ display: "flex", alignItems: "center", gap: 3 }}>
                <TextInput type="number" value={it.l} onChange={v => setItem(i, "l", v)} placeholder="L" mono />
                <TextInput type="number" value={it.w} onChange={v => setItem(i, "w", v)} placeholder="W" mono />
                <TextInput type="number" value={it.h} onChange={v => setItem(i, "h", v)} placeholder="H" mono />
              </div>
            </Field>
            <Field label={i === 0 ? "kg" : ""}><TextInput type="number" value={it.weight} onChange={v => setItem(i, "weight", v)} placeholder="kg" mono /></Field>
            {items.length > 1 ? <button onClick={() => rm(i)} style={{ background: "var(--surface)", border: "none", borderRadius: 7, width: 26, height: 34, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-mute)" }}><Icon name="x" size={14} /></button> : <span />}
          </div>
        ))}
      </div>
      <button onClick={add} style={{ display: "inline-flex", alignItems: "center", gap: 8, marginTop: 10, padding: "9px 14px", background: "var(--surface)", border: "1px dashed var(--border-strong)", borderRadius: "var(--r-md)", color: "var(--brand)", fontSize: 13, fontWeight: 500 }}>
        <Icon name="plus" size={15} /> Add another item
      </button>
    </div>
  );
}

function Quote({ currency, rateMult, nav, onSaveQuote, account }) {
  const [from, setFrom] = useStateQ("");
  const [fromPc, setFromPc] = useStateQ("");
  const [to, setTo] = useStateQ("");
  const [toPc, setToPc] = useStateQ("");
  const [items, setItems] = useStateQ([window.FX.blankItem()]);
  const [isReturn, setIsReturn] = useStateQ(false);
  const [tier, setTier] = useStateQ("standard");
  const [emailOpen, setEmailOpen] = useStateQ(false);
  const [emailTo, setEmailTo] = useStateQ((account && account.email) || "");
  const [saved, setSaved] = useStateQ(null);

  const km = useMemoQ(() => (from && to) ? window.FX.distanceKm(from, to) : null, [from, to]);
  const totals = useMemoQ(() => window.FX.itemTotals(items), [items]);
  const auto = useMemoQ(() => window.FX.autoVehicleForItems(items), [items]);
  const vehicleId = auto.vehicleId;
  const v = window.FX.VEHICLES.find(x => x.id === vehicleId);
  const avail = useMemoQ(() => quoteZoneAvail(from, to), [from, to]);
  React.useEffect(() => { if (!avail.available.includes(tier)) setTier(avail.available[0]); }, [avail.available.join(",")]);
  const hasItems = totals.count > 0 && totals.kg > 0;
  const ready = from && to && km != null && hasItems;
  const bd = useMemoQ(() => ready ? tierBreakdown({ vehicleId, km, serviceId: tier, isReturn, rateMult }) : null, [ready, vehicleId, km, tier, isReturn, rateMult]);

  function doSave() {
    const now = new Date().toISOString();
    const q = {
      no: window.FX.genQuoteNo(), from, fromPc, to, toPc, items, vehicleId, isReturn, serviceId: tier,
      total: bd.total, km, accountId: account && account.id, accountName: account && account.name,
      createdAt: now, expiresAt: window.FX.quoteExpiryISO(now), status: "active",
    };
    onSaveQuote && onSaveQuote(q);
    setSaved(q);
  }
  function doEmail() { setEmailOpen(false); setSaved(s => s); if (onSaveQuote && !saved) doSave(); }

  return (
    <div className="fade-up">
      <PageHeader eyebrow="Instant quote" title="Get a quote" sub="Enter pickup and drop-off, then what you're sending. We size the vehicle and price it — all inclusive." />
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1.1fr)", gap: 24, alignItems: "start" }}>
        {/* form */}
        <Card pad={26}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 18 }}>
            <Field label="Pickup — suburb or postcode"><SuburbPostcodeField suburb={from} postcode={fromPc} onPick={(s, p) => { setFrom(s); setFromPc(p); }} /></Field>
            <Field label="Drop-off — suburb or postcode"><SuburbPostcodeField suburb={to} postcode={toPc} onPick={(s, p) => { setTo(s); setToPc(p); }} /></Field>
          </div>

          <div style={{ fontSize: 13, fontWeight: 700, color: "var(--fg-strong)", marginBottom: 4 }}>What are you sending?</div>
          <div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginBottom: 12 }}>Add each item with its dimensions and weight — we work out the right vehicle for you.</div>
          <ItemsEditor items={items} setItems={setItems} />

          {/* auto vehicle */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 14, padding: "11px 13px", borderRadius: "var(--r-md)", background: auto.over ? "var(--warn-soft)" : "var(--brand-soft)" }}>
            <span style={{ width: 34, height: 34, borderRadius: 9, flex: "none", background: auto.over ? "var(--warn)" : "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name={auto.over ? "truck-big" : (v ? v.icon : "package")} size={17} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 10, fontFamily: "var(--font-mono)", letterSpacing: "0.6px", textTransform: "uppercase", color: auto.over ? "#8a5a00" : "var(--brand)" }}>Vehicle · selected for you</div>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>{auto.over ? "Taxi truck (we'll call you)" : (v ? v.name : "—")} <span style={{ fontWeight: 400, color: "var(--fg-mute)", fontSize: 12 }}>· {totals.kg} kg · {totals.m3} m³</span></div>
            </div>
          </div>

          <button onClick={() => setIsReturn(!isReturn)} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", textAlign: "left", background: "transparent", border: "none", padding: "14px 0 2px" }}>
            <span style={{ width: 38, height: 22, borderRadius: 999, flex: "none", background: isReturn ? "var(--brand)" : "var(--bg-mist-2)", position: "relative", transition: "all 160ms ease" }}>
              <span style={{ position: "absolute", top: 2, left: isReturn ? 18 : 2, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "all 160ms ease" }} />
            </span>
            <span style={{ fontSize: 14, color: "var(--fg-strong)", fontWeight: 500 }}>Include return trip <span style={{ color: "var(--fg-mute)", fontWeight: 400 }}>(15% off the return leg)</span></span>
          </button>
        </Card>

        {/* result */}
        <div>
          {!ready ? (
            <Card pad={40} style={{ textAlign: "center", borderStyle: "dashed", background: "var(--bg-mist)" }}>
              <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--surface)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 14px", color: "var(--fg-faint)" }}><Icon name="calculator" size={26} /></div>
              <div style={{ fontSize: 15.5, fontWeight: 600, color: "var(--fg-strong)" }}>Your quote will appear here</div>
              <div style={{ fontSize: 13.5, color: "var(--fg-mute)", marginTop: 5 }}>Add both suburbs and at least one item with a weight to see live pricing.</div>
            </Card>
          ) : (
            <div className="fade-up">
              {avail.reason && (
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, padding: "9px 12px", background: "var(--warn-soft)", borderRadius: "var(--r-sm)", fontSize: 12.5, color: "#8a5a00" }}>
                  <Icon name="info" size={14} color="#a36a00" /> {avail.reason}
                </div>
              )}
              {/* tier selector */}
              <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 14 }}>
                {window.FX.SERVICES.map(s => {
                  const ok = avail.available.includes(s.id);
                  const on = tier === s.id && ok;
                  const t = tierBreakdown({ vehicleId, km, serviceId: s.id, isReturn, rateMult });
                  return (
                    <button key={s.id} disabled={!ok} onClick={() => ok && setTier(s.id)} style={{ display: "flex", alignItems: "center", gap: 14, textAlign: "left", padding: "13px 15px", borderRadius: "var(--r-md)", border: "1.5px solid " + (on ? "var(--accent)" : "var(--border)"), background: on ? "var(--accent-soft)" : "var(--surface)", opacity: ok ? 1 : 0.4, cursor: ok ? "pointer" : "not-allowed" }}>
                      <span style={{ width: 20, height: 20, borderRadius: "50%", flex: "none", border: "2px solid " + (on ? "var(--accent)" : "var(--border-strong)"), display: "inline-flex", alignItems: "center", justifyContent: "center" }}>{on && <span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--accent)" }} />}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          <span style={{ fontWeight: 700, fontSize: 14.5, color: "var(--fg-strong)" }}>{s.name} {v.name}</span>
                          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 600, color: "var(--brand)", background: "var(--brand-soft)", padding: "2px 6px", borderRadius: 5 }}>{window.FX.serviceCode(s.id, v.id)}</span>
                        </div>
                        <div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginTop: 2 }}>{ok ? s.eta : "Unavailable for this zone"}</div>
                      </div>
                      <div style={{ fontSize: 19, fontWeight: 800, letterSpacing: "-0.5px", color: "var(--fg-strong)" }}>{window.FX.money(t.total, currency)}</div>
                    </button>
                  );
                })}
              </div>

              {/* breakdown (item 36 — same buildup as CE) */}
              <Card pad={0} style={{ overflow: "hidden", marginBottom: 14 }}>
                <div style={{ background: "var(--brand)", color: "#fff", padding: "14px 18px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "1px", opacity: 0.75 }}>{from} → {to}</div>
                    <div style={{ fontSize: 14, fontWeight: 600, marginTop: 3 }}>{window.FX.SERVICES.find(s => s.id === tier).name} · {km} km{isReturn ? " · return" : ""}</div>
                  </div>
                  <div style={{ fontSize: 26, fontWeight: 900, letterSpacing: "-1px" }}>{window.FX.money(bd.total, currency)}</div>
                </div>
                <div style={{ padding: "12px 18px" }}>
                  <QLine label="Base rate" value={window.FX.money(bd.oneWay, currency)} />
                  {isReturn && <QLine label="Return leg (−15%)" value={window.FX.money(bd.returnLeg, currency)} />}
                  <QLine label={`Fuel levy (${Math.round(window.FX.FUEL_LEVY_PCT * 100)}%)`} value={window.FX.money(bd.fuel, currency)} small />
                  <div style={{ borderTop: "1px dashed var(--border)", margin: "8px 0" }} />
                  <QLine label="Subtotal" value={window.FX.money(bd.sub, currency)} />
                  <QLine label="GST (10%)" value={window.FX.money(bd.gst, currency)} small />
                </div>
              </Card>

              {saved ? (
                <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", background: "color-mix(in srgb, var(--success, #1f8a5b), white 92%)", border: "1px solid var(--success, #1f8a5b)", borderRadius: "var(--r-md)", marginBottom: 12 }}>
                  <Icon name="check-circle" size={20} color="var(--success, #1f8a5b)" />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>Quote saved · <span style={{ fontFamily: "var(--font-mono)" }}>{saved.no}</span></div>
                    <div style={{ fontSize: 12, color: "var(--fg-mute)" }}>Valid {window.FX.SAVED_QUOTE_VALID_DAYS} days · find it on your home page under Saved quotes.</div>
                  </div>
                  <Button variant="primary" size="sm" icon="plus" onClick={() => nav("book", { fromQuote: saved })}>Book</Button>
                </div>
              ) : (
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                  <Button variant="primary" size="lg" icon="plus" onClick={() => nav("book", { fromQuote: { from, fromPc, to, toPc, items, vehicleId, isReturn, serviceId: tier } })}>Book this delivery</Button>
                  <Button variant="secondary" icon="history" onClick={doSave}>Save quote</Button>
                  <Button variant="secondary" icon="mail" onClick={() => setEmailOpen(true)}>Email quote</Button>
                </div>
              )}

              {/* T&Cs (item 12 — OPEN wording placeholder) */}
              <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 6 }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.7px", textTransform: "uppercase", color: "var(--fg-faint)" }}>Terms &amp; conditions</div>
                <p style={{ margin: 0, fontSize: 11.5, lineHeight: 1.55, color: "var(--fg-mute)" }}>Prices are indicative and include GST. Quote valid for {window.FX.SAVED_QUOTE_VALID_DAYS} days from the date issued. Final charges are based on actual weight and dimensions measured at pickup and may differ; additional handling, waiting time and surcharges may apply. This quote is for business use. <span style={{ fontStyle: "italic" }}>Full T&amp;C wording to be supplied.</span></p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Email quote modal */}
      <Modal open={emailOpen} onClose={() => setEmailOpen(false)} title="Email this quote" width={440}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ fontSize: 13.5, color: "var(--fg-body)", lineHeight: 1.5 }}>Send this quote to your own address so you can route it internally for approval.</div>
          <Field label="Email address"><TextInput value={emailTo} onChange={setEmailTo} placeholder="you@company.com.au" type="email" /></Field>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
            <Button variant="ghost" onClick={() => setEmailOpen(false)}>Cancel</Button>
            <Button variant="primary" icon="mail" disabled={!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(emailTo)} onClick={doEmail}>Send quote</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

function QLine({ label, value, small }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: small ? "3px 0" : "4px 0" }}>
      <span style={{ fontSize: small ? 12 : 13, color: "var(--fg-mute)" }}>{label}</span>
      <span style={{ fontSize: small ? 12 : 13, fontWeight: 600, color: "var(--fg-strong)" }}>{value}</span>
    </div>
  );
}

Object.assign(window, { Quote });
