const { useState, useMemo, useEffect, useRef } = React;

// Quote engine.
// LTL formula:
//   base = pallets * perPalletRate(lane,distance) * timingMult
//   + densityAdj if cuft/100lbs > 25
//   + fuel surcharge (18.4%)
//   + accessorial fees (additive)
// E-commerce:
//   base = parcels * perParcelRate(zone, weightTier) * timingMult
//   + accessorial-like options

function laneDistance(fromZip, toZip) {
  // Pseudo-distance from zip prefixes — deterministic for demo
  const f = parseInt(fromZip || "90021", 10);
  const t = parseInt(toZip   || "92101", 10);
  const d = Math.abs(f - t);
  return Math.max(8, Math.min(620, Math.round((d / 9) + 12)));
}
function fmt(n) {
  return "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function StepDot({ n, label, active, done, onClick }) {
  return (
    <button onClick={onClick} className="flex items-center gap-2 group focus-ring rounded">
      <span className={`w-6 h-6 rounded-full border flex items-center justify-center num text-[11px] transition
        ${done ? "bg-gpx-700 border-gpx-700 text-gpx-lime" : active ? "border-ink-900 text-ink-900 bg-paper-tint" : "border-ink-200 text-ink-400"}`}>
        {done ? <ICheck size={12} stroke={2.5}/> : n}
      </span>
      <span className={`label-eyebrow ${active || done ? "text-ink-900" : "text-ink-400"}`}>{label}</span>
    </button>
  );
}

function FieldLabel({ children, hint }) {
  return (
    <div className="flex items-baseline justify-between mb-1.5">
      <label className="label-eyebrow text-ink-700">{children}</label>
      {hint && <span className="text-[11px] text-ink-400 num">{hint}</span>}
    </div>
  );
}
function Input(props) {
  return <input {...props} className={`w-full bg-paper-tint border border-ink-900/10 rounded-lg px-3.5 py-2.5 text-[15px] focus-ring focus:border-ink-900/30 num placeholder:text-ink-300 ${props.className||""}`} />;
}
function Select({ children, ...rest }) {
  return <select {...rest} className={`w-full bg-paper-tint border border-ink-900/10 rounded-lg px-3.5 py-2.5 text-[15px] focus-ring focus:border-ink-900/30 ${rest.className||""}`}>{children}</select>;
}

function TabRow({ tabs, value, onChange }) {
  return (
    <div className="grid grid-cols-2 md:grid-cols-4 gap-1.5 p-1.5 bg-paper-soft rounded-xl border border-ink-900/5">
      {tabs.map(t => {
        const Icon = window[t.icon];
        const active = value === t.id;
        return (
          <button key={t.id} onClick={() => onChange(t.id)}
            className={`px-3 py-2.5 rounded-lg text-left transition flex items-start gap-2.5 focus-ring
              ${active ? "bg-ink-900 text-paper" : "hover:bg-white text-ink-700"}`}>
            <Icon size={20} className={active ? "text-gpx-lime" : "text-ink-500"} />
            <div className="leading-tight">
              <div className="text-[13px] font-medium">{t.label}</div>
              <div className={`text-[11px] mt-0.5 ${active ? "text-paper/70" : "text-ink-400"}`}>{t.sub}</div>
            </div>
          </button>
        );
      })}
    </div>
  );
}

function Stepper({ value, onChange, min = 1, max = 99 }) {
  return (
    <div className="inline-flex items-center bg-paper-tint border border-ink-900/10 rounded-lg">
      <button onClick={() => onChange(Math.max(min, value - 1))} className="px-3 py-2.5 text-ink-700 hover:bg-ink-900/5 rounded-l-lg focus-ring"><IMinus size={16}/></button>
      <div className="num px-4 py-2.5 min-w-[3ch] text-center text-[15px]">{value}</div>
      <button onClick={() => onChange(Math.min(max, value + 1))} className="px-3 py-2.5 text-ink-700 hover:bg-ink-900/5 rounded-r-lg focus-ring"><IPlus size={16}/></button>
    </div>
  );
}

function QuoteEngine() {
  const [service, setService]   = useState("ltl");
  const [step, setStep]         = useState(1);
  const [fromZip, setFromZip]   = useState("90021");
  const [toZip, setToZip]       = useState("92101");
  const [timing, setTiming]     = useState("nextday");
  const [pallets, setPallets]   = useState(2);
  const [palletL, setPL]        = useState(48);
  const [palletW, setPW]        = useState(40);
  const [palletH, setPH]        = useState(52);
  const [palletWt, setWt]       = useState(850);
  const [parcels, setParcels]   = useState(35);
  const [parcelWt, setPWt]      = useState("1-5");
  const [accs, setAccs]         = useState(["liftgate"]);
  const [scheduleDate, setSD]   = useState("");

  const distance = laneDistance(fromZip, toZip);
  const timingObj = TIMING.find(t => t.id === timing) || TIMING[1];

  // pricing
  const quote = useMemo(() => {
    const lines = [];
    let subtotal = 0;
    if (service === "ltl") {
      const perPallet = 78 + Math.round(distance * 1.85);
      const palBase = pallets * perPallet;
      lines.push({ label: `${pallets} pallet${pallets>1?"s":""} × ${fmt(perPallet)} (${distance} mi lane)`, amt: palBase });
      const timed = palBase * timingObj.mult;
      if (timingObj.mult !== 1) lines.push({ label: `${timingObj.label} timing × ${timingObj.mult.toFixed(2)}`, amt: timed - palBase });
      subtotal = timed;

      // density adjustment
      const cuft = (palletL * palletW * palletH) / 1728;
      const ratio = palletWt > 0 ? (cuft / (palletWt / 100)) : 0;
      if (ratio > 25) {
        const adj = subtotal * 0.08;
        lines.push({ label: `Low-density adjustment (${ratio.toFixed(1)} ft³/cwt)`, amt: adj });
        subtotal += adj;
      }
      // fuel
      const fuel = subtotal * 0.184;
      lines.push({ label: "Fuel surcharge (18.4%)", amt: fuel });
      subtotal += fuel;
    } else if (service === "ecom") {
      const tierAdj = parcelWt === "0-1" ? 0.85 : parcelWt === "1-5" ? 1 : parcelWt === "5-15" ? 1.35 : 1.85;
      const perParcel = (6.4 + distance * 0.018) * tierAdj;
      const pBase = parcels * perParcel;
      lines.push({ label: `${parcels} parcels × ${fmt(perParcel)} (${parcelWt} lb tier)`, amt: pBase });
      const timed = pBase * timingObj.mult;
      if (timingObj.mult !== 1) lines.push({ label: `${timingObj.label} timing × ${timingObj.mult.toFixed(2)}`, amt: timed - pBase });
      subtotal = timed;
      // volume discount
      if (parcels >= 100) {
        const disc = -subtotal * 0.07;
        lines.push({ label: "Volume tier discount (100+)", amt: disc });
        subtotal += disc;
      }
      const fuel = subtotal * 0.12;
      lines.push({ label: "Fuel surcharge (12.0%)", amt: fuel });
      subtotal += fuel;
    } else if (service === "warehouse") {
      const palletMonths = pallets;
      const inOut = pallets * 18;
      lines.push({ label: `${pallets} pallet position × $42/mo storage`, amt: pallets * 42 });
      lines.push({ label: `Receiving + put-away × $9.50`, amt: pallets * 9.5 });
      lines.push({ label: `Outbound pick & ship × $8.50`, amt: pallets * 8.5 });
      subtotal = pallets * (42 + 9.5 + 8.5);
    } else if (service === "glove") {
      const perStop = 185 + Math.round(distance * 1.2);
      lines.push({ label: `${pallets} stop${pallets>1?"s":""} × ${fmt(perStop)} (2-person crew)`, amt: pallets * perStop });
      lines.push({ label: `Furniture pad + blanket wrap`, amt: pallets * 28 });
      lines.push({ label: `Debris removal + recycle`, amt: pallets * 35 });
      subtotal = pallets * (perStop + 28 + 35);
    }

    // accessorials (LTL + glove)
    if (service === "ltl" || service === "glove") {
      for (const id of accs) {
        const a = ACCESSORIALS.find(x => x.id === id);
        if (a) { lines.push({ label: a.label, amt: a.fee }); subtotal += a.fee; }
      }
    }
    return { lines, total: subtotal };
  }, [service, distance, timing, pallets, palletL, palletW, palletH, palletWt, parcels, parcelWt, accs, timingObj]);

  const toggleAcc = (id) => setAccs(a => a.includes(id) ? a.filter(x => x !== id) : [...a, id]);
  const STEPS = service === "ltl" ? ["Lane", "Freight", "Accessorials"] : service === "ecom" ? ["Lane", "Volume", "Options"] : ["Lane", "Details", "Review"];
  const goNext = () => setStep(s => Math.min(3, s + 1));
  const goPrev = () => setStep(s => Math.max(1, s - 1));

  return (
    <div id="quote" className="grid lg:grid-cols-[1.15fr_1fr] gap-0 bg-white rounded-3xl border border-ink-900/10 overflow-hidden shadow-[0_30px_80px_-40px_rgba(11,20,16,0.25)]">
      {/* LEFT: form */}
      <div className="p-6 md:p-8 border-r border-ink-900/10">
        <div className="flex items-center justify-between mb-4">
          <Eyebrow>Instant Quote · ttq {"<"} 60s</Eyebrow>
          <div className="flex items-center gap-1.5 text-[11px] num text-ink-400">
            <span className="w-1.5 h-1.5 rounded-full bg-gpx-500 animate-pulse"></span>
            LIVE
          </div>
        </div>
        <h3 className="font-display text-[28px] md:text-[34px] leading-[1.05] tracking-tight mb-5">Price your load.</h3>

        <TabRow tabs={SERVICE_TABS} value={service} onChange={(v) => { setService(v); setStep(1); }} />

        {/* Stepper */}
        <div className="flex items-center gap-5 mt-6 mb-5">
          {STEPS.map((s, i) => (
            <React.Fragment key={s}>
              <StepDot n={i+1} label={s} active={step===i+1} done={step>i+1} onClick={() => setStep(i+1)} />
              {i < STEPS.length - 1 && <div className="flex-1 h-px hairline text-ink-200" />}
            </React.Fragment>
          ))}
        </div>

        {/* STEP 1: Lane */}
        {step === 1 && (
          <div className="space-y-4">
            <div className="grid sm:grid-cols-2 gap-3">
              <div>
                <FieldLabel hint="5-digit zip">From</FieldLabel>
                <div className="relative">
                  <Input value={fromZip} onChange={e => setFromZip(e.target.value.slice(0,5))} placeholder="90021" />
                  <IPin size={16} className="absolute right-3 top-3 text-ink-400" />
                </div>
              </div>
              <div>
                <FieldLabel hint="5-digit zip">To</FieldLabel>
                <div className="relative">
                  <Input value={toZip} onChange={e => setToZip(e.target.value.slice(0,5))} placeholder="92101" />
                  <IPin size={16} className="absolute right-3 top-3 text-ink-400" />
                </div>
              </div>
            </div>
            <div className="flex items-center justify-between px-4 py-3 bg-gpx-50 border border-gpx-200 rounded-lg">
              <div className="flex items-center gap-2 text-[13px] text-gpx-800">
                <IRoute size={18}/>
                <span>Lane distance</span>
              </div>
              <div className="num text-[15px] text-ink-900">{distance} mi · est. {Math.round(distance/52)} hr drive</div>
            </div>

            <div>
              <FieldLabel>Timing</FieldLabel>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                {TIMING.map(t => (
                  <button key={t.id} onClick={() => setTiming(t.id)}
                    className={`px-3 py-3 rounded-lg text-left border transition
                      ${timing===t.id ? "bg-ink-900 text-paper border-ink-900" : "border-ink-900/10 hover:border-ink-900/30 bg-paper-tint"}`}>
                    <div className="text-[11px] num uppercase tracking-wider opacity-70">{t.badge}</div>
                    <div className="text-[14px] font-medium mt-0.5">{t.label}</div>
                    <div className={`text-[11px] mt-0.5 ${timing===t.id ? "text-paper/60" : "text-ink-400"}`}>{t.sub}</div>
                  </button>
                ))}
              </div>
            </div>
            {timing === "scheduled" && (
              <div>
                <FieldLabel>Delivery date</FieldLabel>
                <Input type="date" value={scheduleDate} onChange={e => setSD(e.target.value)} />
              </div>
            )}
          </div>
        )}

        {/* STEP 2 */}
        {step === 2 && service === "ltl" && (
          <div className="space-y-4">
            <div className="flex items-end justify-between gap-4">
              <div className="flex-1">
                <FieldLabel hint="1–12 pallets">Pallet count</FieldLabel>
                <Stepper value={pallets} onChange={setPallets} min={1} max={12} />
              </div>
              <div className="flex-1">
                <FieldLabel hint="lbs per pallet">Weight</FieldLabel>
                <Input type="number" value={palletWt} onChange={e => setWt(+e.target.value || 0)} />
              </div>
            </div>
            <div>
              <FieldLabel hint="inches, L × W × H">Pallet dimensions</FieldLabel>
              <div className="grid grid-cols-3 gap-2">
                <Input type="number" value={palletL} onChange={e => setPL(+e.target.value || 0)} placeholder="L" />
                <Input type="number" value={palletW} onChange={e => setPW(+e.target.value || 0)} placeholder="W" />
                <Input type="number" value={palletH} onChange={e => setPH(+e.target.value || 0)} placeholder="H" />
              </div>
              <div className="mt-2 flex items-center justify-between text-[12px] text-ink-400 num">
                <span>Volume: {((palletL*palletW*palletH)/1728).toFixed(1)} ft³</span>
                <span>Density: {palletWt>0 ? ((palletWt/((palletL*palletW*palletH)/1728)).toFixed(1)) : "—"} lbs/ft³</span>
              </div>
            </div>
            <div className="p-3 rounded-lg bg-paper-soft text-[12.5px] text-ink-500 flex gap-2.5">
              <IInfo size={16} className="text-ink-400 shrink-0 mt-0.5"/>
              <span>Loads under 12 lbs/ft³ trigger a low-density adjustment. We'll surface this transparently on the right.</span>
            </div>
          </div>
        )}

        {step === 2 && service === "ecom" && (
          <div className="space-y-4">
            <div>
              <FieldLabel hint="parcels per drop">Parcel count</FieldLabel>
              <div className="flex items-center gap-3">
                <input type="range" min="1" max="500" value={parcels} onChange={e => setParcels(+e.target.value)} className="flex-1 accent-gpx-700" />
                <div className="num bg-paper-tint border border-ink-900/10 rounded-lg px-3 py-2 min-w-[5ch] text-center">{parcels}</div>
              </div>
              <div className="grid grid-cols-4 mt-1.5 text-[10.5px] num text-ink-400">
                <span>1</span><span className="text-center">50</span><span className="text-center">250</span><span className="text-right">500</span>
              </div>
            </div>
            <div>
              <FieldLabel>Avg parcel weight</FieldLabel>
              <div className="grid grid-cols-4 gap-2">
                {[["0-1","< 1 lb"],["1-5","1–5 lb"],["5-15","5–15 lb"],["15+","15+ lb"]].map(([id,label]) => (
                  <button key={id} onClick={() => setPWt(id)}
                    className={`px-3 py-2.5 rounded-lg text-[13px] border transition
                      ${parcelWt===id ? "bg-ink-900 text-paper border-ink-900" : "border-ink-900/10 hover:border-ink-900/30 bg-paper-tint"}`}>{label}</button>
                ))}
              </div>
            </div>
            <div className="p-3 rounded-lg bg-gpx-50 border border-gpx-200 text-[12.5px] text-gpx-800 flex gap-2.5">
              <IBolt size={16} className="shrink-0 mt-0.5"/>
              <span>Orders of 100+ parcels per drop unlock a 7% volume discount, applied automatically.</span>
            </div>
          </div>
        )}

        {step === 2 && service === "warehouse" && (
          <div className="space-y-4">
            <div>
              <FieldLabel hint="40×48 standard">Pallet positions / month</FieldLabel>
              <div className="flex items-center gap-3">
                <input type="range" min="1" max="200" value={pallets} onChange={e => setPallets(+e.target.value)} className="flex-1 accent-gpx-700" />
                <div className="num bg-paper-tint border border-ink-900/10 rounded-lg px-3 py-2 min-w-[5ch] text-center">{pallets}</div>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-2">
              <button className="p-3 rounded-lg border border-ink-900/10 bg-paper-tint text-left">
                <div className="label-eyebrow text-ink-400">Climate</div>
                <div className="text-[14px] mt-0.5">Ambient (default)</div>
              </button>
              <button className="p-3 rounded-lg border border-ink-900/10 bg-paper-tint text-left">
                <div className="label-eyebrow text-ink-400">Climate</div>
                <div className="text-[14px] mt-0.5">Temp-controlled +$18</div>
              </button>
            </div>
            <div className="p-3 rounded-lg bg-paper-soft text-[12.5px] text-ink-500 flex gap-2.5">
              <IInfo size={16} className="text-ink-400 shrink-0 mt-0.5"/>
              <span>Storage billed monthly. Receiving + outbound billed per touch. 30-day minimum.</span>
            </div>
          </div>
        )}

        {step === 2 && service === "glove" && (
          <div className="space-y-4">
            <div>
              <FieldLabel hint="One crew per stop">Stop count</FieldLabel>
              <Stepper value={pallets} onChange={setPallets} min={1} max={20} />
            </div>
            <div className="grid grid-cols-2 gap-2">
              {["Lift to floor","Unpack + position","Light assembly","Debris removal"].map(s => (
                <div key={s} className="p-3 rounded-lg border border-ink-900/10 bg-paper-tint text-[13px] flex items-center gap-2">
                  <ICheck size={14} className="text-gpx-700"/>{s}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* STEP 3 */}
        {step === 3 && (service === "ltl" || service === "glove") && (
          <div className="space-y-2.5">
            <FieldLabel hint={`${accs.length} selected`}>Accessorials</FieldLabel>
            {ACCESSORIALS.map(a => {
              const on = accs.includes(a.id);
              return (
                <button key={a.id} onClick={() => toggleAcc(a.id)}
                  className={`w-full flex items-start gap-3 px-3.5 py-3 rounded-lg border text-left transition
                    ${on ? "border-gpx-700 bg-gpx-50" : "border-ink-900/10 bg-paper-tint hover:border-ink-900/25"}`}>
                  <span className={`mt-0.5 w-5 h-5 rounded-md border flex items-center justify-center shrink-0
                    ${on ? "bg-gpx-700 border-gpx-700 text-gpx-lime" : "border-ink-300"}`}>
                    {on && <ICheck size={12} stroke={3} />}
                  </span>
                  <div className="flex-1">
                    <div className="flex items-center justify-between">
                      <div className="text-[14px] text-ink-900">{a.label}</div>
                      <div className="num text-[13px] text-ink-700">+${a.fee}</div>
                    </div>
                    <div className="text-[12px] text-ink-400 mt-0.5">{a.note}</div>
                  </div>
                </button>
              );
            })}
          </div>
        )}

        {step === 3 && service === "ecom" && (
          <div className="space-y-3">
            <FieldLabel>Service options</FieldLabel>
            {[
              {l:"Signature required", n:"All deliveries require signature capture"},
              {l:"Photo proof of delivery", n:"Geotagged image on every drop (free)"},
              {l:"Re-attempt schedule", n:"Up to 2 redeliveries before return"},
              {l:"Return reverse-logistics", n:"Pickup, scan, re-stock at your DC"},
            ].map((o,i) => (
              <div key={i} className="px-3.5 py-3 rounded-lg border border-ink-900/10 bg-paper-tint flex items-start gap-3">
                <span className="mt-0.5 w-5 h-5 rounded-md border border-gpx-700 bg-gpx-700 text-gpx-lime flex items-center justify-center shrink-0"><ICheck size={12} stroke={3}/></span>
                <div>
                  <div className="text-[14px]">{o.l}</div>
                  <div className="text-[12px] text-ink-400 mt-0.5">{o.n}</div>
                </div>
              </div>
            ))}
          </div>
        )}

        {step === 3 && service === "warehouse" && (
          <div className="space-y-3 text-[14px] text-ink-700">
            <FieldLabel>Integrations included</FieldLabel>
            <div className="grid grid-cols-2 gap-2">
              {["Shopify","BigCommerce","ShipStation","Extensiv","Netsuite","Custom EDI"].map(p => (
                <div key={p} className="px-3 py-2.5 rounded-lg border border-ink-900/10 bg-paper-tint flex items-center gap-2">
                  <ICheck size={14} className="text-gpx-700"/>{p}
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="flex items-center justify-between mt-7 pt-5 border-t border-ink-900/10">
          <Btn variant="ghost" onClick={goPrev} className={step===1?"opacity-40 pointer-events-none":""}><IArrowL size={16}/>Back</Btn>
          {step < 3 ? (
            <Btn variant="primary" onClick={goNext}>Continue<IArrowR size={16}/></Btn>
          ) : (
            <Btn variant="lime" onClick={() => alert("Quote locked. A dispatcher will follow up.")}>Lock this rate<IArrowR size={16}/></Btn>
          )}
        </div>
      </div>

      {/* RIGHT: live quote */}
      <div className="bg-ink-900 text-paper p-6 md:p-8 relative overflow-hidden">
        <div className="absolute inset-0 opacity-[0.06] pointer-events-none"
          style={{backgroundImage: "radial-gradient(circle at 20% 10%, #C6F37A 0, transparent 50%), radial-gradient(circle at 80% 90%, #5BAE7C 0, transparent 60%)"}}></div>

        <div className="relative">
          <div className="flex items-center justify-between mb-5">
            <Eyebrow color="text-gpx-300">Your live quote</Eyebrow>
            <Pill tone="lime">{SERVICE_TABS.find(s=>s.id===service).label}</Pill>
          </div>

          <div className="flex items-baseline gap-2">
            <div className="num text-[64px] leading-none tracking-tight text-gpx-lime">{fmt(quote.total).replace(".00","")}</div>
          </div>
          <div className="text-[13px] text-ink-300 mt-2 num">
            {fromZip} → {toZip} · {distance} mi · {timingObj.label}
          </div>

          <div className="mt-7 space-y-2.5">
            {quote.lines.map((l, i) => (
              <div key={i} className="flex items-baseline justify-between gap-4 text-[13px]">
                <div className="text-ink-300 flex-1 truncate pr-2">{l.label}</div>
                <div className="hairline text-ink-700 flex-shrink-0 w-12 h-px self-center"></div>
                <div className={`num tabular-nums ${l.amt<0?"text-signal-amber":"text-paper"}`}>{l.amt<0?"−":""}{fmt(Math.abs(l.amt))}</div>
              </div>
            ))}
          </div>

          <div className="mt-7 pt-5 border-t border-paper/15 flex items-baseline justify-between">
            <div>
              <div className="label-eyebrow text-gpx-300">Total · all-in</div>
              <div className="text-[11px] text-ink-400 mt-1 num">No fuel-card surprises · billed exactly as quoted</div>
            </div>
            <div className="num text-[32px] text-gpx-lime">{fmt(quote.total)}</div>
          </div>

          <div className="mt-6 grid grid-cols-3 gap-2">
            <div className="bg-paper/5 border border-paper/10 rounded-lg p-3">
              <div className="label-eyebrow text-gpx-300">ETA</div>
              <div className="text-[14px] mt-1">{timingObj.label}</div>
            </div>
            <div className="bg-paper/5 border border-paper/10 rounded-lg p-3">
              <div className="label-eyebrow text-gpx-300">Cover</div>
              <div className="text-[14px] mt-1">$1.50/lb incl.</div>
            </div>
            <div className="bg-paper/5 border border-paper/10 rounded-lg p-3">
              <div className="label-eyebrow text-gpx-300">Lock</div>
              <div className="text-[14px] mt-1">14 days</div>
            </div>
          </div>

          <div className="mt-6 flex items-center gap-2 text-[12px] text-ink-300">
            <IShield size={14} className="text-gpx-300"/>
            Rate locked the moment you book. Re-confirmation SMS sent within 4 minutes.
          </div>
        </div>
      </div>
    </div>
  );
}

window.QuoteEngine = QuoteEngine;
