// Screen 5: Active Kitting Session — step view
const { useState: useStateKS, useEffect: useEffectKS } = React;

function KittingSession({ wo, user, sessionId, startStep = 0, resumeState = null, onExit, onComplete }) {
  const pickSteps = (Array.isArray(window.KIT_STEPS) ? window.KIT_STEPS : (window.KIT_STEPS[wo.sku] || []));
  const extraSteps = ((window.ASSY_STEPS_DB || {})[wo.sku] || []).map(s => ({
    qty: null, part: s.title, sku: '', bin: s.detail || '', _isInstruction: true,
    critical: s.critical, tools: s.tools, image_url: s.image_url || '',
  }));
  const steps = [...pickSteps, ...extraSteps];
  const [idx, setIdx] = useStateKS(startStep);
  const [statuses, setStatuses] = useStateKS(() => {
    if (resumeState?.statuses?.length) return resumeState.statuses;
    return steps.map((_, i) => i < startStep ? "yes" : null);
  });
  const [shortageModal, setShortageModal] = useStateKS(false);
  const [partialMode, setPartialMode] = useStateKS(false);
  const [partialQty, setPartialQty] = useStateKS(0);
  const [pauseModal, setPauseModal] = useStateKS(false);
  const [largeQty, setLargeQty] = useStateKS(0);
  const [elapsed, setElapsed] = useStateKS(6 * 60 + 42);

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

  const step = steps[idx];
  const total = steps.length;
  const isLargeQty = step && step.qty >= 10;

  useEffectKS(() => { setLargeQty(step ? step.qty : 0); }, [idx]);

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

  function nextOrFinish() {
    if (idx + 1 < total) setIdx(idx + 1);
    else onComplete(statuses);
  }

  function handleYes() {
    if (isLargeQty && largeQty !== step.qty) {
      // confirm exact qty for large counts
      if (largeQty < step.qty) { setShortageModal(true); return; }
    }
    const next = [...statuses]; next[idx] = "yes"; setStatuses(next);
    setTimeout(nextOrFinish, 180);
  }
  function handleNo() { setShortageModal(true); }
  function shortageMiscount() { setShortageModal(false); setPartialMode(false); }
  function shortagePartial() { setPartialMode(true); setPartialQty(Math.max(0, Math.floor(step.qty/2))); }
  function shortageConfirmPartial() {
    const next = [...statuses]; next[idx] = "short"; setStatuses(next);
    setShortageModal(false); setPartialMode(false);
    setTimeout(nextOrFinish, 150);
  }
  function shortagePause() {
    setShortageModal(false);
    setPauseModal(true);
  }

  async function handlePause(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: { stepIndex: idx, statuses },
          }),
        });
      } catch {}
    }
    onExit();
  }
  function handleMaterialResolved() {
    setPauseModal(false);
  }

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

      {/* Compact top bar */}
      <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-sky-500/10 text-sky-300 border border-sky-500/30">KITTING</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">Started <span className="font-mono text-zinc-200">07:18</span></div>
          <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>

      {/* Progress + context */}
      <div className="px-6 pt-4 pb-3 border-b border-zinc-800/50 flex-shrink-0">
        <div className="flex items-end justify-between mb-3">
          <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">
              {idx + 1}<span className="text-zinc-600"> / {total}</span>
            </div>
          </div>
        </div>
        <div className="flex gap-1.5 h-3 rounded-full overflow-hidden">
          {steps.map((_, i) => {
            const s = statuses[i];
            const bg = s === "yes" ? "bg-emerald-500" : s === "short" ? "bg-amber-400" : i === idx ? "bg-zinc-300" : "bg-zinc-800";
            return <div key={i} className={`flex-1 rounded-full transition-colors ${bg}`} />;
          })}
        </div>
      </div>

      {/* Main step body */}
      <div className="flex-1 px-6 py-6 flex items-center justify-center overflow-y-auto">
        <div className="w-full max-w-[1100px] bg-zinc-900 border border-zinc-800 rounded-2xl p-10 flex flex-col gap-7">

          {step._isInstruction ? (
            /* ── Instruction step (from kit steps) ── */
            <>
              <div className="flex items-center gap-3">
                <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Step</div>
                {step.critical && (
                  <div className="text-[11px] uppercase tracking-wider bg-red-900/40 border border-red-700 text-red-400 px-2 py-0.5 rounded">Critical</div>
                )}
              </div>
              <div className="font-display text-[52px] leading-[1.1] tracking-tight">{step.part}</div>
              {step.bin && <div className="text-[18px] text-zinc-400">{step.bin}</div>}
              {step.image_url && (
                <div className="rounded-xl overflow-hidden border border-zinc-800 bg-zinc-950 flex items-center justify-center" style={{maxHeight:'320px'}}>
                  <img src={step.image_url} alt="" className="max-h-[320px] w-auto object-contain" />
                </div>
              )}
              {step.tools && step.tools.length > 0 && (
                <div className="flex gap-2 flex-wrap">
                  {step.tools.map((t, i) => (
                    <span key={i} className="px-3 py-1 rounded-full bg-zinc-800 border border-zinc-700 text-[13px] text-zinc-300">{t}</span>
                  ))}
                </div>
              )}
            </>
          ) : (['consumable','packaging materials'].includes(step.partType) ? (
            /* ── Consumable / packaging step — apply an amount, no shortage ── */
            <>
              <div className="flex items-center gap-3">
                <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Apply</div>
                <div className="px-2 py-0.5 rounded text-[11px] font-bold uppercase tracking-wider bg-green-500/15 text-green-300 border border-green-500/30">
                  {step.partType}
                </div>
              </div>
              <div className="font-display text-[52px] leading-[1.1] tracking-tight">
                <span className="text-amber-400 tabular-nums">{step.qty}</span>
                <span className="ml-3">{step.part}</span>
              </div>
              {step.bin && (
                <div className="flex items-center gap-3">
                  <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Location</div>
                  <div className="font-mono text-[16px] bg-zinc-800 border border-zinc-700 text-zinc-100 rounded-lg px-3 py-1">{step.bin}</div>
                </div>
              )}
            </>
          ) : (
            /* ── Pick step (BOM line — discrete hardware) ── */
            <>
          <div className="flex items-center gap-4">
            <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Pick from bin</div>
            <div className="font-mono text-[20px] bg-zinc-800 border border-zinc-700 text-zinc-100 rounded-lg px-4 py-1.5">
              BIN {step.bin}
            </div>
          </div>

          <div className="h-[200px] rounded-xl bg-zinc-950 border border-zinc-800 flex items-center justify-center text-zinc-600">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2">
              <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>
            </svg>
          </div>

          <div>
            <div className="font-display text-[64px] leading-[1.0] tracking-tight">
              Do you have{" "}
              <span className="text-emerald-400 tabular-nums">{step.qty}×</span>{" "}
              <span className="block mt-2">{step.part}?</span>
            </div>
            <div className="font-mono text-[18px] text-zinc-400 mt-3">{step.sku}</div>
          </div>
          </>
          ))}

          {!step._isInstruction && !['consumable','packaging materials'].includes(step.partType) && isLargeQty && (
            <div className="bg-zinc-950 border border-zinc-800 rounded-xl p-5 flex items-center gap-4">
              <div className="flex-1">
                <div className="text-[12px] uppercase tracking-[0.22em] text-zinc-500">Count says</div>
                <div className="text-[15px] text-zinc-300 mt-1">Confirm exact qty for ≥10. Enter what you actually have:</div>
              </div>
              <button onClick={() => setLargeQty(Math.max(0, largeQty - 1))}
                className="h-[60px] w-[60px] rounded-lg bg-zinc-800 border border-zinc-700 text-[28px] font-display">−</button>
              <input type="number" value={largeQty} onChange={(e) => setLargeQty(parseInt(e.target.value || "0", 10))}
                className="font-display text-[56px] tabular-nums text-center w-[140px] h-[80px] bg-zinc-950 border border-zinc-800 rounded-lg outline-none focus:border-emerald-500" />
              <button onClick={() => setLargeQty(largeQty + 1)}
                className="h-[60px] w-[60px] rounded-lg bg-zinc-800 border border-zinc-700 text-[28px] font-display">+</button>
            </div>
          )}

          {/* Confirm button — instruction/consumable/packaging: single DONE; hardware: YES/NO */}
          {(step._isInstruction || ['consumable','packaging materials'].includes(step.partType)) ? (
            <window.HoldButton color="emerald" holdMs={step.critical ? 1500 : 500} onComplete={handleYes}
              className="h-[180px]"
              subText="hold to confirm">
              <div className="font-display text-[56px] tracking-wider">DONE</div>
            </window.HoldButton>
          ) : (
          <div className="grid grid-cols-2 gap-5">
            <window.HoldButton color="emerald" holdMs={500} onComplete={handleYes}
              className="h-[180px]"
              subText={`all ${step.qty} present`}>
              <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12" />
              </svg>
              <div className="font-display text-[56px] tracking-wider">YES</div>
            </window.HoldButton>
            <button onClick={handleNo}
              className="h-[180px] rounded-2xl bg-red-500 hover:bg-red-400 text-white active:scale-[0.99] transition flex flex-col items-center justify-center gap-1">
              <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
              </svg>
              <div className="font-display text-[56px] tracking-wider">NO</div>
              <div className="text-[15px] font-medium opacity-90">shortage / missing</div>
            </button>
          </div>
          )}
        </div>
      </div>

      {/* Step nav footer */}
      <div className="px-6 py-3 border-t border-zinc-800/50 flex items-center justify-between flex-shrink-0 text-[13px]">
        <button disabled={idx === 0} onClick={() => setIdx(Math.max(0, idx - 1))}
          className="h-10 px-4 rounded-lg bg-zinc-900 border border-zinc-800 text-zinc-400 hover:bg-zinc-800 disabled:opacity-40 uppercase tracking-wider">
          ← Previous
        </button>
        <div className="text-zinc-500">
          <span className="text-emerald-400">{statuses.filter((s)=>s==="yes").length} confirmed</span>
          <span className="text-zinc-600"> · </span>
          <span className="text-amber-400">{statuses.filter((s)=>s==="short").length} short</span>
        </div>
        <button disabled={!statuses[idx] || idx === total - 1} onClick={() => setIdx(Math.min(total - 1, idx + 1))}
          className="h-10 px-4 rounded-lg bg-zinc-900 border border-zinc-800 text-zinc-400 hover:bg-zinc-800 disabled:opacity-40 uppercase tracking-wider">
          Skip →
        </button>
      </div>

      {/* SHORTAGE MODAL */}
      {shortageModal && (
        <ModalKS>
          <div className="text-[13px] uppercase tracking-[0.22em] text-red-400 mb-3">Shortage reported</div>
          <h3 className="font-display text-[48px] leading-tight tracking-tight">Short on {step.part}</h3>
          <p className="text-zinc-400 text-[17px] mt-4 leading-relaxed">
            We'll flag this to your supervisor and auto-generate a replenishment request for{" "}
            <span className="font-mono text-zinc-200">{step.sku}</span>.
          </p>

          <div className="flex flex-col gap-3 mt-7">
            <button onClick={shortageMiscount}
              className="h-[110px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 hover:bg-zinc-700 active:scale-[0.99] transition flex flex-col items-center justify-center">
              <div className="font-display text-[28px] tracking-wider">I MISCOUNTED — GO BACK</div>
              <div className="text-[14px] text-zinc-400 mt-1">dismiss and recount</div>
            </button>

            {!partialMode ? (
              <button onClick={shortagePartial}
                className="h-[90px] rounded-xl bg-amber-400 text-zinc-950 hover:bg-amber-300 active:scale-[0.99] transition flex flex-col items-center justify-center">
                <div className="font-display text-[24px] tracking-wider">I HAVE SOME — ENTER QTY</div>
                <div className="text-[14px] font-medium opacity-70 mt-1">mark partial, continue kitting</div>
              </button>
            ) : (
              <div className="rounded-xl bg-amber-400/10 border border-amber-400/40 p-5 flex items-center gap-4">
                <div className="flex-1 text-amber-100 text-[15px]">How many do you have of {step.qty}?</div>
                <button onClick={() => setPartialQty(Math.max(0, partialQty - 1))}
                  className="h-[60px] w-[60px] rounded-lg bg-zinc-800 border border-zinc-700 text-amber-100 text-[28px] font-display">−</button>
                <input type="number" value={partialQty} onChange={(e) => setPartialQty(parseInt(e.target.value || "0", 10))}
                  className="font-display text-[44px] tabular-nums text-center w-[110px] h-[68px] bg-zinc-950 border border-amber-400/40 rounded-lg outline-none text-amber-100" />
                <button onClick={() => setPartialQty(Math.min(step.qty - 1, partialQty + 1))}
                  className="h-[60px] w-[60px] rounded-lg bg-zinc-800 border border-zinc-700 text-amber-100 text-[28px] font-display">+</button>
                <button onClick={shortageConfirmPartial}
                  className="h-[68px] px-6 rounded-lg bg-amber-400 text-zinc-950 font-display text-[18px] tracking-wider hover:bg-amber-300">
                  CONFIRM →
                </button>
              </div>
            )}

            <button onClick={shortagePause}
              className="h-[70px] rounded-xl bg-zinc-700 text-zinc-200 hover:bg-zinc-600 active:scale-[0.99] transition flex flex-col items-center justify-center">
              <div className="font-display text-[20px] tracking-wider">I HAVE NONE — PAUSE SESSION</div>
              <div className="text-[13px] text-zinc-400 mt-0.5">stop until restocked · supervisor paged</div>
            </button>
          </div>
        </ModalKS>
      )}

      {/* PAUSE MODAL */}
      {pauseModal && (
        <window.PauseModal
          context={`Kitting · Step ${idx + 1} of ${total} · ${statuses.filter((s)=>s==="yes").length} confirmed`}
          defaultMaterial={{ sku: step.sku, name: step.part, expected: step.qty }}
          taskContext={{
            totalUnits: wo.qty,
            alreadyFinished: 0,
            perUnit: step.qty / wo.qty,
          }}
          onCancel={() => setPauseModal(false)}
          onPause={handlePause}
          onMaterialResolved={handleMaterialResolved}
        />
      )}
    </div>
  );
}

function ModalKS({ children }) {
  return (
    <div className="fixed inset-0 z-50 bg-zinc-950/85 backdrop-blur-sm flex items-center justify-center p-8" style={{ animation: "fadeIn 0.18s ease-out" }}>
      <div className="w-full max-w-[820px] bg-zinc-900 border border-zinc-800 rounded-2xl p-10 shadow-2xl" style={{ animation: "slideUp 0.22s ease-out" }}>
        {children}
      </div>
      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
    </div>
  );
}

window.KittingSession = KittingSession;
