// Completion screen — handles KITTING, ASSY, SHIPPING and RECEIVING work orders.
function Completion({ wo, statuses, user, onHandoff }) {
  const isAssy = wo?.type === "ASSY";
  const isShipping = wo?.type === "SHIPPING";
  const isReceiving = wo?.type === "RECEIVING";

  // Normalize numbers per type
  let unitsBuilt = 0, flaggedCount = 0, confirmedSteps = 0, shortSteps = 0;
  const kitSteps = window.KIT_STEPS;
  let shortItems = [];

  if (isShipping) {
    unitsBuilt = (statuses?.packages || []).reduce((s, p) => s + (p.units || 0), 0);
  } else if (isReceiving) {
    unitsBuilt = statuses?.totalUnits || 0;
  } else if (isAssy) {
    unitsBuilt = wo.qty;
    const matrix = statuses || {};
    Object.values(matrix).forEach((batch) => {
      (batch || []).forEach((stepArr) => {
        (stepArr || []).forEach((s) => { if (s === "flagged") flaggedCount += 1; });
      });
    });
  } else {
    const arr = Array.isArray(statuses) ? statuses : [];
    confirmedSteps = arr.filter((s) => s === "yes").length;
    shortSteps = arr.filter((s) => s === "short").length;
    unitsBuilt = wo?.qty || 0;
    shortItems = kitSteps.filter((_, i) => arr[i] === "short");
  }

  const headline =
    isShipping ? "SHIPMENT COMPLETE" :
    isReceiving ? "PO RECEIVED" :
    isAssy ? "ASSEMBLY COMPLETE" : "KITTING COMPLETE";

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 flex flex-col relative">
      <window.TopStripe />
      <div className="flex-1 flex items-center justify-center px-8 py-12 overflow-y-auto">
        <div className="w-full max-w-[1000px] flex flex-col gap-6">
          <div className="text-center">
            <div className="font-display text-[28px] tracking-[0.2em] text-emerald-400">{headline}</div>
            <div className="font-display text-[64px] tracking-tight leading-[0.95] mt-2">{wo?.name}</div>
            <div className="text-zinc-500 font-mono text-[15px] mt-1">{wo?.sku} · {wo?.id}</div>
          </div>

          {/* BIG confirmation */}
          <div className="bg-emerald-500/10 border-2 border-emerald-500/30 rounded-2xl p-7 text-center">
            <div className="text-[12px] uppercase tracking-[0.22em] text-emerald-300 font-semibold">
              {isShipping ? "Packages shipped" :
               isReceiving ? "Units added to stock" :
               isAssy ? "Units built" : "Units kitted"}
            </div>
            <div className="font-display text-[140px] leading-[0.9] tabular-nums text-emerald-300 mt-2">
              {isShipping ? (statuses?.packages || []).length : unitsBuilt}
            </div>
            <div className="text-[18px] text-zinc-300 mt-2">
              {isShipping ? `${unitsBuilt} unit${unitsBuilt !== 1 ? "s" : ""} across ${(statuses?.packages || []).length} package${(statuses?.packages || []).length !== 1 ? "s" : ""}` :
               isReceiving ? `PO ${statuses?.poId} closed ${statuses?.mode === "FULL" ? "FULL" : "PARTIAL"}` :
               isAssy ? "ready for shipping handoff" : "boxes built and sealed"}
            </div>
          </div>

          {/* Shipping-specific: tracking numbers */}
          {isShipping && (statuses?.packages || []).length > 0 && (
            <div className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
              <div className="px-5 py-3 border-b border-zinc-800 font-display text-[18px] tracking-wider text-zinc-300">TRACKING</div>
              <div className="divide-y divide-zinc-800/80">
                {(statuses.packages || []).map((p, i) => (
                  <div key={i} className="grid grid-cols-[80px_1fr_1.5fr_80px] items-center gap-3 px-5 py-3 text-[14px]">
                    <div className="font-display text-[18px] tracking-wider text-zinc-300">BOX {i + 1}</div>
                    <div className="text-zinc-400">{p.carrier}</div>
                    <div className="font-mono tabular-nums text-zinc-200">{p.tracking || "—"}</div>
                    <div className="text-right tabular-nums text-zinc-400">{p.weight?.toFixed(1)} lb</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Receiving-specific: line summary */}
          {isReceiving && (
            <div className="bg-zinc-900 border border-zinc-800 rounded-xl overflow-hidden">
              <div className="px-5 py-3 border-b border-zinc-800 font-display text-[18px] tracking-wider text-zinc-300">
                LINES RECEIVED · {(statuses?.lines || []).length}
              </div>
              <div className="divide-y divide-zinc-800/80">
                {(statuses?.lines || []).map((l, i) => (
                  <div key={i} className="grid grid-cols-[1.4fr_1fr_1fr] items-center gap-3 px-5 py-2.5 text-[14px]">
                    <div className="font-mono text-zinc-200">{l.sku}</div>
                    <div className="text-right text-zinc-400 tabular-nums">{l.receivedNow} received</div>
                    <div className="text-right text-zinc-500 tabular-nums">{l.ordered ? `of ${l.ordered}` : "extra"}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Secondary stats — kitting/assy only */}
          {!isShipping && !isReceiving && (
            <div className="grid grid-cols-3 gap-4">
              {isAssy ? (
                <>
                  <StatTile label="Batches run" value={Object.keys(statuses || {}).length || 1} />
                  <StatTile label="Flags raised" value={flaggedCount} tone={flaggedCount > 0 ? "warn" : "ok"} />
                  <StatTile label="Elapsed" value="00:48:12" mono />
                </>
              ) : (
                <>
                  <StatTile label="Steps confirmed" value={confirmedSteps} tone="ok" />
                  <StatTile label="Steps short" value={shortSteps} tone={shortSteps > 0 ? "warn" : "ok"} />
                  <StatTile label="Elapsed" value="00:14:08" mono />
                </>
              )}
            </div>
          )}

          {/* Shortages list — kitting */}
          {!isAssy && !isShipping && !isReceiving && shortItems.length > 0 && (
            <div className="rounded-xl bg-amber-500/10 border border-amber-500/40 p-5">
              <div className="font-display text-[20px] tracking-wider text-amber-200">SHORTAGES FLAGGED</div>
              <ul className="mt-2 space-y-1">
                {shortItems.map((it) => (
                  <li key={it.sku} className="text-[15px] text-amber-100 flex items-center gap-3">
                    <span className="font-mono">{it.sku}</span> · {it.part}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Handoff CTA */}
          <window.HoldButton color="emerald" holdMs={500} onComplete={onHandoff}
            className="h-[110px]" subText="press and hold to confirm and return to queue">
            <div className="font-display text-[30px] tracking-wider">
              {isShipping ? `✓ ${(statuses?.packages || []).length} PACKAGES OUT · DONE →` :
               isReceiving ? `✓ ${unitsBuilt} UNITS LOGGED · DONE →` :
               `✓ CONFIRM ${unitsBuilt} ${isAssy ? "BUILT" : "KITTED"} · HAND OFF →`}
            </div>
          </window.HoldButton>
        </div>
      </div>
    </div>
  );
}

function StatTile({ label, value, tone = "neutral", mono = false }) {
  const color =
    tone === "warn" ? "text-amber-400" :
    tone === "ok" ? "text-emerald-400" :
    "text-zinc-100";
  return (
    <div className="bg-zinc-900 border border-zinc-800 rounded-xl p-5">
      <div className="text-[12px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className={`font-display text-[48px] tabular-nums leading-none mt-1 ${color} ${mono ? "font-mono text-[32px] mt-3" : ""}`}>{value}</div>
    </div>
  );
}

window.Completion = Completion;
