// Active Shipping Session — 5 steps, multi-package as primary.
//   1. Pull units from staging
//   2. Verify customer addresses
//   3. Set up packages (split units)
//   4. Per-package: weigh → carrier → label → pack
//   5. Stage for outbound
const { useState: useStateSS, useEffect: useEffectSS } = React;

function ShippingSession({ wo, user, sessionId, onExit, onComplete }) {
  const customers = wo.customers || [];
  const defaults = window.SHIPPING_DEFAULTS?.[wo.sku] || window.SHIPPING_DEFAULTS?._default || { weight: 4, length: 10, width: 8, height: 6, boxType: "Box" };
  const hsDefault = window.HS_CODES?.[wo.sku] || window.HS_CODES?._default;

  const [stepIdx, setStepIdx] = useStateSS(0);
  const [pkgCount, setPkgCount] = useStateSS(Math.max(1, customers.length));
  // packages: array of {
  //   units, weight, length, width, height, boxType, carrierId, tracking, packed,
  //   signature, saturday, insurance, expedited, customs: {hs, value, reason}
  // }
  const [packages, setPackages] = useStateSS(() =>
    customers.map((c) => ({
      units: [c],
      weight: defaults.weight,
      length: defaults.length, width: defaults.width, height: defaults.height,
      boxType: defaults.boxType,
      carrierId: null, tracking: null, packed: false,
      signature: false, saturday: false,
      insurance: 0,
      expedited: false,
      customs: hsDefault ? { hs: hsDefault.hs, desc: hsDefault.desc, value: hsDefault.customsValue, reason: "Sale" } : null,
    }))
  );
  const [activePkg, setActivePkg] = useStateSS(0);
  const [elapsed, setElapsed] = useStateSS(0);
  const [pauseModal, setPauseModal] = useStateSS(false);

  useEffectSS(() => {
    const t = setInterval(() => setElapsed((e) => e + 1), 1000);
    return () => clearInterval(t);
  }, []);

  function elapsedFmt() {
    const m = Math.floor(elapsed / 60); const s = elapsed % 60;
    return `00:${String(m).padStart(2,"0")}:${String(s).padStart(2,"0")}`;
  }

  const steps = ["Pull units", "Verify addresses", "Set up packages", "Pack & label", "Stage for outbound"];

  function advanceStep() { setStepIdx((s) => Math.min(s + 1, steps.length - 1)); }

  function setPkgField(pkgIdx, patch) {
    setPackages((pkgs) => pkgs.map((p, i) => i === pkgIdx ? { ...p, ...patch } : p));
  }

  function changePkgCount(n) {
    n = Math.max(1, Math.min(20, n));
    setPackages((pkgs) => {
      if (n > pkgs.length) {
        const extra = Array.from({ length: n - pkgs.length }).map(() => ({
          units: [], weight: defaults.weight,
          length: defaults.length, width: defaults.width, height: defaults.height,
          boxType: defaults.boxType,
          carrierId: null, tracking: null, packed: false,
          signature: false, saturday: false, insurance: 0, expedited: false,
          customs: hsDefault ? { hs: hsDefault.hs, desc: hsDefault.desc, value: hsDefault.customsValue, reason: "Sale" } : null,
        }));
        return [...pkgs, ...extra];
      } else if (n < pkgs.length) {
        const keep = pkgs.slice(0, n);
        const cut = pkgs.slice(n).flatMap((p) => p.units);
        keep[n - 1] = { ...keep[n - 1], units: [...keep[n - 1].units, ...cut] };
        return keep;
      }
      return pkgs;
    });
    setPkgCount(n);
  }

  function moveUnit(orderRef, toPkgIdx) {
    setPackages((pkgs) => pkgs.map((p, i) => ({
      ...p,
      units: i === toPkgIdx
        ? (p.units.find((u) => u.order === orderRef.order) ? p.units : [...p.units, orderRef])
        : p.units.filter((u) => u.order !== orderRef.order),
    })));
  }

  function printLabel(pkgIdx) {
    const tracking = `1Z${Math.floor(Math.random() * 999999999).toString().padStart(9, "0")}${Math.floor(Math.random() * 999).toString().padStart(3, "0")}`;
    setPkgField(pkgIdx, { tracking });
    window.gpsToast && window.gpsToast({
      message: `Label printed · ${tracking}`,
      tone: "ok",
    });
  }

  function applyAndPack(pkgIdx) {
    setPkgField(pkgIdx, { packed: true });
    // advance to next package or to step 5
    if (pkgIdx + 1 < packages.length) {
      setTimeout(() => setActivePkg(pkgIdx + 1), 250);
    } else {
      setTimeout(() => setStepIdx(4), 250);
    }
  }

  async function finish() {
    const orderNumber = wo.orders && wo.orders[0];
    if (orderNumber) {
      try {
        const r = await fetch("/api/shipstation/mark-ready", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ order_number: orderNumber }),
        });
        const d = await r.json();
        if (r.ok) {
          window.gpsToast && window.gpsToast({ message: "ShipStation notified ✓", tone: "ok" });
        } else {
          window.gpsToast && window.gpsToast({ message: `ShipStation: ${d.error || "notify failed"}`, tone: "warn" });
        }
      } catch {
        window.gpsToast && window.gpsToast({ message: "ShipStation: connection error", tone: "warn" });
      }
    }
    onComplete({
      packages: packages.map((p) => ({
        units: p.units.length, weight: p.weight,
        carrier: window.SHIPPING_RATES.find((r) => r.id === p.carrierId)?.carrier || "—",
        tracking: p.tracking,
      })),
    });
  }

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 flex flex-col relative">
      <window.TopStripe />

      <header className="border-b border-zinc-800 bg-zinc-900/40 px-6 h-[64px] flex items-center justify-between flex-shrink-0">
        <div className="flex items-center gap-3">
          <button onClick={() => setPauseModal(true)}
            className="h-10 px-3 rounded-lg bg-amber-500/15 border border-amber-500/40 text-amber-200 text-[13px] font-medium hover:bg-amber-500/25 uppercase tracking-wider flex items-center gap-2">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
            Pause
          </button>
          <button onClick={onExit}
            className="h-10 px-3 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[13px] font-medium hover:bg-zinc-700 uppercase tracking-wider">
            ← Queue
          </button>
          <span className="font-mono text-[13px] text-zinc-500">{wo.id}</span>
          <span className="px-2 py-1 rounded text-[11px] font-bold uppercase tracking-wider bg-orange-500/10 text-orange-300 border border-orange-500/30">SHIPPING</span>
          {wo.priority === "URGENT" && (
            <span className="px-2 py-1 rounded text-[11px] font-bold uppercase tracking-wider bg-red-500 text-white">● URGENT</span>
          )}
        </div>
        <div className="flex items-center gap-5 text-[14px]">
          <div className="text-zinc-400">Elapsed <span className="font-mono text-zinc-200">{elapsedFmt()}</span></div>
          <div className="text-zinc-300">{user.name}</div>
        </div>
      </header>

      {/* Step pips */}
      <div className="px-6 pt-4 pb-3 border-b border-zinc-800/50 flex-shrink-0 space-y-2">
        <div className="flex items-end justify-between">
          <div>
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">{wo.name} · {wo.qty} units</div>
            <div className="font-mono text-[15px] text-zinc-400 mt-0.5">{wo.sku}</div>
          </div>
          <div className="text-right">
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Step</div>
            <div className="font-display text-[42px] tabular-nums leading-none mt-1">
              {stepIdx + 1}<span className="text-zinc-600"> / {steps.length}</span>
            </div>
          </div>
        </div>
        <div className="flex gap-1 h-2.5 rounded-full overflow-hidden">
          {steps.map((_, i) => (
            <div key={i} className={`flex-1 rounded-full ${i < stepIdx ? "bg-emerald-500" : i === stepIdx ? "bg-zinc-300" : "bg-zinc-800"}`} />
          ))}
        </div>
      </div>

      {/* Main */}
      <div className="flex-1 px-6 py-6 overflow-y-auto">
        <div className="w-full max-w-[1100px] mx-auto">
          {stepIdx === 0 && <StepPull wo={wo} onDone={advanceStep} />}
          {stepIdx === 1 && <StepVerify customers={customers} onDone={advanceStep} />}
          {stepIdx === 2 && <StepPackages
            pkgCount={pkgCount} changePkgCount={changePkgCount}
            packages={packages} customers={customers} moveUnit={moveUnit}
            onDone={() => { setActivePkg(0); setStepIdx(3); }} />}
          {stepIdx === 3 && <StepPackLoop
            packages={packages} activePkg={activePkg} setActivePkg={setActivePkg}
            setPkgField={setPkgField} printLabel={printLabel} applyAndPack={applyAndPack} />}
          {stepIdx === 4 && <StepStage packages={packages} onDone={finish} />}
        </div>
      </div>

      {pauseModal && (
        <window.PauseModal
          context={`Shipping · Step ${stepIdx + 1} of ${steps.length}`}
          onCancel={() => setPauseModal(false)}
          onPause={async (payload) => {
            setPauseModal(false);
            if (sessionId) {
              try {
                await fetch(`/api/sessions/${sessionId}`, {
                  method: 'PATCH', headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({
                    status: 'paused',
                    pause_reason: payload?.reason || '',
                    pause_note: payload?.note || '',
                    state: { packages, stepIdx },
                  }),
                });
              } catch {}
            }
            onExit();
          }}
          onMaterialResolved={() => setPauseModal(false)}
        />
      )}
    </div>
  );
}

// ----- Step components -----
function StepPull({ wo, onDone }) {
  return (
    <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-8 space-y-6 max-w-[820px] mx-auto">
      <div>
        <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Step 1</div>
        <div className="font-display text-[48px] leading-[1.0] tracking-tight mt-1">Pull units from staging</div>
      </div>
      <div className="text-[19px] text-zinc-200 leading-relaxed">
        Pull <span className="font-display text-emerald-400 text-[28px]">{wo.qty}× {wo.name}</span> from{" "}
        <span className="font-mono bg-zinc-800 text-zinc-100 border border-zinc-700 rounded px-2 py-0.5">{wo.location}</span>.
      </div>
      <div className="text-[14px] text-zinc-400">Verify each unit has its quick-start card, foam insert, and outer carton intact before bringing to packing table.</div>
      <window.HoldButton color="emerald" holdMs={500} onComplete={onDone}
        className="h-[120px]" subText="press and hold once units are at the table">
        <div className="font-display text-[30px] tracking-wider">✓ UNITS AT TABLE</div>
      </window.HoldButton>
    </div>
  );
}

function StepVerify({ customers, onDone }) {
  return (
    <div className="space-y-5">
      <div>
        <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Step 2</div>
        <div className="font-display text-[48px] leading-[1.0] tracking-tight mt-1">Verify addresses</div>
        <div className="text-[15px] text-zinc-400 mt-2">Check each Shopify order's ship-to address looks correct. Flag and stop if anything looks wrong.</div>
      </div>
      <div className="grid grid-cols-2 gap-3">
        {customers.map((c) => (
          <div key={c.order} className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
            <div className="font-mono text-[12px] text-zinc-500">{c.order}</div>
            <div className="font-display text-[22px] tracking-tight mt-1">{c.name}</div>
            <div className="text-[14px] text-zinc-300 mt-2 leading-snug">{c.address}</div>
            <div className="text-[12px] text-zinc-500 mt-2 uppercase tracking-wider">{c.units} unit{c.units > 1 ? "s" : ""}</div>
          </div>
        ))}
      </div>
      <div className="grid grid-cols-[1fr_2fr] gap-3 max-w-[820px] mx-auto">
        <button className="h-[96px] rounded-xl bg-red-500/15 border border-red-500/40 text-red-300 font-display text-[18px] tracking-wider hover:bg-red-500/25">
          FLAG ADDRESS ISSUE
        </button>
        <window.HoldButton color="emerald" holdMs={500} onComplete={onDone}
          className="h-[96px]" subText="all addresses confirmed">
          <div className="font-display text-[26px] tracking-wider">✓ ADDRESSES OK</div>
        </window.HoldButton>
      </div>
    </div>
  );
}

function StepPackages({ pkgCount, changePkgCount, packages, customers, moveUnit, onDone }) {
  return (
    <div className="space-y-5 max-w-[1000px] mx-auto">
      <div>
        <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Step 3</div>
        <div className="font-display text-[48px] leading-[1.0] tracking-tight mt-1">Set up packages</div>
        <div className="text-[15px] text-zinc-400 mt-2">Multi-package is normal. One box per Shopify order is the default — combine when it makes sense.</div>
      </div>

      <div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-5 flex items-center gap-4">
        <div className="flex-1">
          <div className="text-[12px] uppercase tracking-wider text-zinc-400">How many boxes?</div>
          <div className="text-[14px] text-zinc-500">Defaults to one per Shopify order. Adjust if you're combining or splitting.</div>
        </div>
        <button onClick={() => changePkgCount(pkgCount - 1)}
          className="h-[68px] w-[68px] rounded-lg bg-zinc-800 border border-zinc-700 text-[28px] font-display">−</button>
        <input type="number" value={pkgCount}
          onChange={(e) => changePkgCount(parseInt(e.target.value || "1", 10))}
          className="h-[80px] w-[120px] bg-zinc-950 border border-zinc-800 rounded-lg text-center font-display text-[48px] tabular-nums outline-none focus:border-zinc-600" />
        <button onClick={() => changePkgCount(pkgCount + 1)}
          className="h-[68px] w-[68px] rounded-lg bg-zinc-800 border border-zinc-700 text-[28px] font-display">+</button>
      </div>

      {/* Package preview */}
      <div className={`grid gap-3`} style={{ gridTemplateColumns: `repeat(${Math.min(pkgCount, 4)}, minmax(0, 1fr))` }}>
        {packages.map((p, i) => (
          <div key={i} className="bg-zinc-900 border-2 border-zinc-800 rounded-xl p-4 min-h-[160px]">
            <div className="font-display text-[20px] tracking-wider text-zinc-300">BOX {i + 1}</div>
            <div className="text-[12px] text-zinc-500 mb-3">{p.units.length} unit{p.units.length !== 1 ? "s" : ""}</div>
            <div className="space-y-1.5">
              {p.units.map((u) => (
                <div key={u.order} className="text-[12px] bg-zinc-800/60 border border-zinc-700 rounded px-2 py-1.5 flex items-center justify-between gap-2">
                  <div className="min-w-0">
                    <div className="font-mono text-zinc-300 truncate">{u.order}</div>
                    <div className="text-zinc-400 truncate">{u.name}</div>
                  </div>
                  {pkgCount > 1 && (
                    <select value={i} onChange={(e) => moveUnit(u, parseInt(e.target.value))}
                      className="bg-zinc-900 border border-zinc-700 rounded text-[11px] text-zinc-300 px-1 h-7">
                      {packages.map((_, j) => <option key={j} value={j}>Box {j + 1}</option>)}
                    </select>
                  )}
                </div>
              ))}
              {p.units.length === 0 && (
                <div className="text-[12px] text-zinc-600 italic">(empty — drag units here or assign via dropdown)</div>
              )}
            </div>
          </div>
        ))}
      </div>

      <window.HoldButton color="emerald" holdMs={500} onComplete={onDone}
        className="h-[96px]" disabled={packages.some((p) => p.units.length === 0)}
        subText={packages.some((p) => p.units.length === 0) ? "every box must have at least one unit" : "confirm package plan and start packing"}>
        <div className="font-display text-[26px] tracking-wider">✓ PACKAGES SET · START PACKING →</div>
      </window.HoldButton>
    </div>
  );
}

function StepPackLoop({ packages, activePkg, setActivePkg, setPkgField, printLabel, applyAndPack }) {
  const p = packages[activePkg];
  const rates = window.SHIPPING_RATES;
  const isIntl = (p.units || []).some((u) => u.country && u.country !== "US");
  const showExpedited = p.expedited;
  const visibleRates = showExpedited ? rates : rates.filter((r) => !r.expedited || r.recommended);
  // Filter out intl-only rates for domestic
  const filteredRates = visibleRates.filter((r) => isIntl ? true : !r.international);

  return (
    <div className="space-y-4 max-w-[1100px] mx-auto">
      <div className="flex items-end justify-between">
        <div>
          <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Step 4 · pack & label</div>
          <div className="font-display text-[44px] leading-[1.0] tracking-tight mt-1">
            Box {activePkg + 1} <span className="text-zinc-500">of</span> {packages.length}
          </div>
        </div>
        <div className="flex gap-1.5">
          {packages.map((pkg, i) => {
            const isCurrent = i === activePkg;
            const done = pkg.packed;
            const bg = done ? "bg-emerald-500 border-emerald-500 text-zinc-900" :
              isCurrent ? "bg-zinc-300 border-zinc-300 text-zinc-900" :
              "bg-zinc-900 border-zinc-700 text-zinc-500";
            return (
              <button key={i} onClick={() => setActivePkg(i)}
                className={`h-9 min-w-[44px] px-2 rounded-md border-2 font-mono text-[12px] ${bg}`}>
                #{i + 1}{done ? " ✓" : ""}
              </button>
            );
          })}
        </div>
      </div>

      {/* Box contents + destination */}
      <div className="grid grid-cols-[1.4fr_1fr] gap-3">
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-4">
          <div className="text-[12px] uppercase tracking-wider text-zinc-500 mb-2">Contents · {p.units.length} unit{p.units.length !== 1 ? "s" : ""}</div>
          <div className="flex flex-wrap gap-2">
            {p.units.map((u) => (
              <span key={u.order} className="font-mono text-[12px] text-zinc-300 bg-zinc-800/60 border border-zinc-700 rounded px-2 py-1">
                {u.order} · {u.name}
              </span>
            ))}
          </div>
        </div>
        <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-4">
          <div className="flex items-center justify-between">
            <div className="text-[12px] uppercase tracking-wider text-zinc-500">Destination</div>
            {isIntl && (
              <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider border bg-violet-500/15 text-violet-300 border-violet-500/40">✈ INTERNATIONAL</span>
            )}
          </div>
          {p.units[0] && (
            <div className="mt-1">
              <div className="text-[13px] text-zinc-200">{p.units[0].name}</div>
              <div className="text-[12px] text-zinc-400 leading-snug">{p.units[0].address}</div>
            </div>
          )}
        </div>
      </div>

      {/* Package: box type + dims + weight */}
      <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <div className="font-display text-[20px] tracking-wider text-zinc-300">PACKAGE</div>
            <div className="text-[12px] text-zinc-500">Defaults pulled from product profile — edit if needed.</div>
          </div>
          <span className="text-[11px] uppercase tracking-wider text-emerald-400">defaults loaded</span>
        </div>
        <div className="grid grid-cols-[2fr_1fr] gap-3">
          <div>
            <div className="text-[11px] uppercase tracking-wider text-zinc-500 mb-1">Box type</div>
            <select value={p.boxType} onChange={(e) => setPkgField(activePkg, { boxType: e.target.value })}
              className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] outline-none focus:border-zinc-600">
              <option>{p.boxType}</option>
              <option>Small box</option>
              <option>Medium box</option>
              <option>Large box</option>
              <option>Custom — oversized</option>
              <option>Custom — long</option>
              <option>GPS-PKG-OC-S</option>
              <option>GPS-PKG-OC-M</option>
              <option>GPS-PKG-OC-L</option>
            </select>
          </div>
          <div>
            <div className="text-[11px] uppercase tracking-wider text-zinc-500 mb-1">Weight (lb)</div>
            <div className="flex items-center gap-1">
              <button onClick={() => setPkgField(activePkg, { weight: Math.max(0, parseFloat((p.weight - 0.5).toFixed(1))) })}
                className="h-[48px] w-[40px] rounded-lg bg-zinc-800 border border-zinc-700 text-[18px] font-display">−</button>
              <input type="number" step="0.1" value={p.weight}
                onChange={(e) => setPkgField(activePkg, { weight: parseFloat(e.target.value || "0") })}
                className="h-[48px] flex-1 min-w-0 bg-zinc-950 border border-zinc-800 rounded-lg text-center font-display text-[20px] tabular-nums outline-none focus:border-zinc-600" />
              <button onClick={() => setPkgField(activePkg, { weight: parseFloat((p.weight + 0.5).toFixed(1)) })}
                className="h-[48px] w-[40px] rounded-lg bg-zinc-800 border border-zinc-700 text-[18px] font-display">+</button>
            </div>
          </div>
        </div>
        <div className="mt-3">
          <div className="text-[11px] uppercase tracking-wider text-zinc-500 mb-1">Dimensions (in)</div>
          <div className="grid grid-cols-[1fr_auto_1fr_auto_1fr] items-center gap-2">
            <DimInput value={p.length} label="L" onChange={(v) => setPkgField(activePkg, { length: v })} />
            <div className="text-zinc-600 text-[18px]">×</div>
            <DimInput value={p.width} label="W" onChange={(v) => setPkgField(activePkg, { width: v })} />
            <div className="text-zinc-600 text-[18px]">×</div>
            <DimInput value={p.height} label="H" onChange={(v) => setPkgField(activePkg, { height: v })} />
          </div>
        </div>
      </div>

      {/* Carrier */}
      <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
        <div className="flex items-center justify-between mb-3">
          <div>
            <div className="font-display text-[20px] tracking-wider text-zinc-300">CARRIER · ShipStation rates</div>
            <div className="text-[12px] text-zinc-500">{isIntl ? "International — only carriers offering customs are shown." : "Cheapest acceptable rate is pre-selected."}</div>
          </div>
          <button onClick={() => setPkgField(activePkg, { expedited: !p.expedited })}
            className={`h-10 px-4 rounded-lg text-[12px] font-display tracking-wider transition flex items-center gap-2 ${
              p.expedited ? "bg-amber-400 text-zinc-950" : "bg-zinc-800 border border-zinc-700 text-amber-300 hover:bg-zinc-700"
            }`}>
            ⚡ {p.expedited ? "SHOWING EXPEDITED" : "NEED IT QUICKER?"}
          </button>
        </div>
        <div className="grid grid-cols-2 gap-2">
          {filteredRates.map((r) => {
            const selected = p.carrierId === r.id;
            return (
              <button key={r.id} onClick={() => setPkgField(activePkg, { carrierId: r.id })}
                className={`h-[64px] px-3 rounded-lg border-2 text-left transition flex items-center justify-between gap-2 ${
                  selected ? "bg-emerald-500/15 border-emerald-500/60" : "bg-zinc-950 border-zinc-800 hover:border-zinc-600"
                }`}>
                <div className="min-w-0">
                  <div className="font-display text-[15px] tracking-wider truncate">{r.carrier}</div>
                  <div className="text-[11px] text-zinc-500">{r.days}d · {r.expedited ? "expedited" : "standard"}</div>
                </div>
                <div className="text-right flex-shrink-0">
                  <div className="font-mono text-[16px] tabular-nums">${r.price.toFixed(2)}</div>
                  {r.recommended && !selected && <div className="text-[10px] text-emerald-400 uppercase tracking-wider">recommended</div>}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Options */}
      <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
        <div className="font-display text-[20px] tracking-wider text-zinc-300 mb-3">OPTIONS</div>
        <div className="grid grid-cols-3 gap-2">
          <OptionToggle
            label="Signature required"
            sub="recipient must sign"
            checked={p.signature}
            onChange={() => setPkgField(activePkg, { signature: !p.signature })} />
          <OptionToggle
            label="Saturday delivery"
            sub="weekend pickup"
            checked={p.saturday}
            onChange={() => setPkgField(activePkg, { saturday: !p.saturday })} />
          <div className="bg-zinc-950 border border-zinc-800 rounded-lg p-3">
            <div className="text-[11px] uppercase tracking-wider text-zinc-400">Insurance (USD)</div>
            <div className="flex items-center gap-1 mt-1">
              <span className="text-zinc-500 text-[14px]">$</span>
              <input type="number" value={p.insurance}
                onChange={(e) => setPkgField(activePkg, { insurance: parseFloat(e.target.value || "0") })}
                placeholder="0"
                className="h-[36px] flex-1 min-w-0 bg-zinc-900 border border-zinc-800 rounded text-right font-mono tabular-nums outline-none focus:border-zinc-600 px-2" />
            </div>
            <div className="text-[10px] text-zinc-500 mt-1">0 = no insurance</div>
          </div>
        </div>
      </div>

      {/* International / customs */}
      {isIntl && p.customs && (
        <div className="bg-violet-500/5 border-2 border-violet-500/30 rounded-xl p-5">
          <div className="flex items-center justify-between mb-3">
            <div>
              <div className="font-display text-[20px] tracking-wider text-violet-200">✈ INTERNATIONAL · CUSTOMS</div>
              <div className="text-[12px] text-zinc-400">HS code + customs value required for the destination country.</div>
            </div>
            <span className="text-[11px] uppercase tracking-wider text-emerald-400">defaults loaded</span>
          </div>
          <div className="grid grid-cols-[1fr_1fr_1.2fr] gap-3">
            <div>
              <div className="text-[11px] uppercase tracking-wider text-zinc-400 mb-1">HS code</div>
              <input value={p.customs.hs}
                onChange={(e) => setPkgField(activePkg, { customs: { ...p.customs, hs: e.target.value } })}
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg font-mono text-[14px] outline-none focus:border-zinc-600" />
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-wider text-zinc-400 mb-1">Customs value (USD)</div>
              <div className="flex items-center gap-1">
                <span className="text-zinc-500 text-[14px] pl-2">$</span>
                <input type="number" value={p.customs.value}
                  onChange={(e) => setPkgField(activePkg, { customs: { ...p.customs, value: parseFloat(e.target.value || "0") } })}
                  className="h-[48px] flex-1 min-w-0 bg-zinc-950 border border-zinc-800 rounded-lg font-mono tabular-nums outline-none focus:border-zinc-600 px-2" />
              </div>
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-wider text-zinc-400 mb-1">Reason for export</div>
              <select value={p.customs.reason}
                onChange={(e) => setPkgField(activePkg, { customs: { ...p.customs, reason: e.target.value } })}
                className="w-full h-[48px] px-3 bg-zinc-950 border border-zinc-800 rounded-lg text-[14px] outline-none focus:border-zinc-600">
                <option>Sale</option>
                <option>Sample / Promo</option>
                <option>Warranty replacement</option>
                <option>Return / Repair</option>
                <option>Gift</option>
              </select>
            </div>
          </div>
          <div className="mt-3 text-[12px] text-zinc-400 leading-snug">
            <span className="text-zinc-300">Description on commercial invoice:</span> {p.customs.desc}
          </div>
        </div>
      )}

      {/* Print + apply CTAs */}
      {p.tracking ? (
        <div className="bg-emerald-500/10 border-2 border-emerald-500/40 rounded-xl p-5 flex items-center gap-4">
          <div className="text-emerald-300 text-[32px]">🏷</div>
          <div className="flex-1">
            <div className="text-[12px] uppercase tracking-[0.22em] text-emerald-300 font-semibold">Label printed</div>
            <div className="font-mono text-[18px] tabular-nums mt-1">{p.tracking}</div>
            <div className="text-[12px] text-zinc-400 mt-1">
              {window.SHIPPING_RATES.find((r) => r.id === p.carrierId)?.carrier} · {p.weight.toFixed(1)} lb · {p.length}×{p.width}×{p.height} in
              {p.signature && " · signature"} {p.saturday && " · saturday"} {p.insurance > 0 && ` · ins $${p.insurance}`}
              {isIntl && p.customs && ` · HS ${p.customs.hs}`}
            </div>
          </div>
          <button onClick={() => printLabel(activePkg)}
            className="h-10 px-4 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[12px] font-display tracking-wider hover:bg-zinc-700">REPRINT</button>
        </div>
      ) : (
        <window.HoldButton color="emerald" holdMs={500}
          disabled={!p.carrierId} onComplete={() => printLabel(activePkg)}
          className="h-[96px]" subText={p.carrierId ? "press and hold to print label" : "pick a carrier first"}>
          <div className="font-display text-[26px] tracking-wider">🏷 PRINT LABEL</div>
        </window.HoldButton>
      )}

      <window.HoldButton color="emerald" holdMs={500}
        disabled={!p.tracking}
        onComplete={() => applyAndPack(activePkg)}
        className="h-[110px]"
        subText={p.tracking ? "label applied, box sealed" : "print the label first"}>
        <div className="font-display text-[28px] tracking-wider">✓ PACKED & LABELED · NEXT →</div>
      </window.HoldButton>
    </div>
  );
}

function DimInput({ value, label, onChange }) {
  return (
    <div className="relative">
      <input type="number" value={value}
        onChange={(e) => onChange(parseFloat(e.target.value || "0"))}
        className="w-full h-[48px] bg-zinc-950 border border-zinc-800 rounded-lg text-center font-display text-[20px] tabular-nums outline-none focus:border-zinc-600" />
      <div className="absolute top-1 left-2 text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
    </div>
  );
}

function OptionToggle({ label, sub, checked, onChange }) {
  return (
    <button onClick={onChange}
      className={`bg-zinc-950 border-2 rounded-lg p-3 text-left transition ${
        checked ? "border-emerald-500/60 bg-emerald-500/10" : "border-zinc-800 hover:border-zinc-600"
      }`}>
      <div className="flex items-center gap-2">
        <div className={`h-5 w-5 rounded border-2 flex items-center justify-center ${checked ? "bg-emerald-400 border-emerald-400" : "border-zinc-600"}`}>
          {checked && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#09090b" strokeWidth="4"><polyline points="20 6 9 17 4 12"/></svg>}
        </div>
        <div className="font-display text-[14px] tracking-wider">{label}</div>
      </div>
      <div className="text-[11px] text-zinc-500 mt-1 ml-7">{sub}</div>
    </button>
  );
}

function StepStage({ packages, onDone }) {
  return (
    <div className="space-y-5 max-w-[820px] mx-auto">
      <div>
        <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Step 5 · stage for outbound</div>
        <div className="font-display text-[48px] leading-[1.0] tracking-tight mt-1">Move {packages.length} package{packages.length > 1 ? "s" : ""} to outbound dock</div>
      </div>
      <div className="bg-zinc-900 border border-zinc-800 rounded-xl divide-y divide-zinc-800">
        {packages.map((p, i) => (
          <div key={i} className="flex items-center gap-3 px-5 py-3">
            <div className="font-display text-[18px] tracking-wider text-zinc-300 w-[64px]">BOX {i + 1}</div>
            <div className="flex-1 font-mono text-[14px] text-zinc-300">{p.tracking}</div>
            <div className="text-[13px] text-zinc-400">{window.SHIPPING_RATES.find((r) => r.id === p.carrierId)?.carrier}</div>
            <div className="text-[13px] text-zinc-400 tabular-nums w-[60px] text-right">{p.weight.toFixed(1)} lb</div>
          </div>
        ))}
      </div>
      <window.HoldButton color="emerald" holdMs={500} onComplete={onDone}
        className="h-[110px]" subText="staged at outbound dock · ready for carrier pickup">
        <div className="font-display text-[28px] tracking-wider">✓ STAGED · COMPLETE SESSION →</div>
      </window.HoldButton>
    </div>
  );
}

window.ShippingSession = ShippingSession;
