// Router shell — state machine for the whole app.
const { useState: useStateApp } = React;

function App() {
  const [screen, setScreen] = useStateApp("login");
  // login | dashboard | briefing | kitting | assembly | shipping | receiving | audit | completion | badge
  const [user, setUser] = useStateApp(null);
  const [activeWO, setActiveWO] = useStateApp(null);
  const [resumeStep, setResumeStep] = useStateApp(0);
  const [resumeState, setResumeState] = useStateApp(null);
  const [completionData, setCompletionData] = useStateApp(null);
  const [earnedBadge, setEarnedBadge] = useStateApp(null);
  const [dashboardTab, setDashboardTab] = useStateApp(null);
  const [activeSessionId, setActiveSessionId] = useStateApp(null);

  function handleLogin(u) {
    setUser(u);
    setScreen("dashboard");
  }
  function handleLogout() {
    setUser(null); setActiveWO(null); setResumeStep(0);
    setCompletionData(null); setEarnedBadge(null);
    setScreen("login");
  }
  async function handleStartWO(wo) {
    if (!["KITTING", "ASSY", "SHIPPING", "RECEIVING", "AUDIT"].includes(wo.type)) return;
    setActiveWO(wo);
    setResumeStep(0);
    // Start session in backend
    try {
      const data = await fetch(`/api/work-orders/${wo.id}/start`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_id: user?.id }),
      }).then(r => r.json());
      setActiveSessionId(data.session_id || null);
    } catch { setActiveSessionId(null); }
    if (wo.type === "ASSY") setScreen("assembly");
    else if (wo.type === "SHIPPING") setScreen("shipping");
    else if (wo.type === "RECEIVING") setScreen("receiving");
    else if (wo.type === "AUDIT") setScreen("audit");
    else setScreen("briefing");
  }
  function handleAuditDone(result) {
    setCompletionData({ statuses: result });
    setScreen("dashboard");
    window.gpsToast && window.gpsToast({
      message: `Audit complete · ${result.counts.diffs} adjustment${result.counts.diffs !== 1 ? "s" : ""} committed`,
      tone: "ok",
    });
    setActiveWO(null);
  }
  function handleResume(paused) {
    // paused is a sessions row: { id, wo_id, type, state: {stepIndex, statuses, ...}, pause_reason, ... }
    const woId = paused.wo_id || paused.woId;
    const sessionType = paused.type || 'kitting';
    const resumedState = paused.state || {};
    let wo = window.WORK_ORDERS.find((w) => w.id === woId);
    if (!wo) {
      wo = {
        id: woId,
        type: sessionType.toUpperCase(),
        priority: "URGENT",
        sku: '', name: paused.pause_note || woId,
        qty: 1, due: "resumed", location: '', orders: [],
      };
    }
    setActiveWO(wo);
    setActiveSessionId(paused.id || null);
    setResumeStep(resumedState.stepIndex || 0);
    setResumeState(resumedState);
    const t = (wo.type || sessionType).toLowerCase();
    if (t === 'assembly' || t === 'assy') setScreen("assembly");
    else if (t === 'shipping') setScreen("shipping");
    else if (t === 'receiving') setScreen("receiving");
    else setScreen("kitting");
  }
  function handleReadyToStart() { setScreen("kitting"); }
  async function handleKitComplete(payload) {
    // payload may be statuses array (kitting) or object with statuses+other data
    const statuses = Array.isArray(payload) ? payload : (payload?.statuses || []);
    const qty_built = payload?.qty_built || activeWO?.qty;
    if (activeWO) {
      try {
        await fetch(`/api/work-orders/${activeWO.id}/complete`, {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ session_id: activeSessionId, statuses, qty_built }),
        });
      } catch {}
    }
    setCompletionData({ statuses });
    setScreen("completion");
  }
  function handleHandoff() {
    const earned = window.BADGES_EARNED[user?.name] || [];
    const candidate = window.ALL_BADGES.find((b) => !earned.includes(b.id) && b.id !== "century") || window.ALL_BADGES[2];
    setEarnedBadge(candidate);
    setScreen("badge");
  }
  function handleBadgeContinue() {
    setActiveWO(null); setResumeStep(0); setCompletionData(null); setEarnedBadge(null);
    setScreen("dashboard");
  }
  function handleExitKitting() {
    setActiveWO(null); setResumeStep(0); setActiveSessionId(null); setResumeState(null);
    setScreen("dashboard");
  }

  let content = null;
  if (screen === "login") content = <window.PinLogin onLogin={handleLogin} />;
  else if (screen === "dashboard") content = (
    <window.DashboardShell user={user} onLogout={handleLogout}
      onStartWO={handleStartWO} onResume={handleResume} initialTab={dashboardTab} />
  );
  else if (screen === "briefing") content = (
    <window.Briefing wo={activeWO} user={user}
      onBack={handleExitKitting} onReady={handleReadyToStart} />
  );
  else if (screen === "kitting") content = (
    <window.KittingSession wo={activeWO} user={user} sessionId={activeSessionId}
      startStep={resumeStep} resumeState={resumeState} onExit={handleExitKitting} onComplete={handleKitComplete} />
  );
  else if (screen === "assembly") content = (
    <window.AssemblySession wo={activeWO} user={user} sessionId={activeSessionId}
      onExit={handleExitKitting} onComplete={handleKitComplete} />
  );
  else if (screen === "shipping") content = (
    <window.ShippingSession wo={activeWO} user={user} sessionId={activeSessionId}
      onExit={handleExitKitting} onComplete={handleKitComplete} />
  );
  else if (screen === "receiving") content = (
    <window.ReceivingSession wo={activeWO} user={user} sessionId={activeSessionId}
      onExit={handleExitKitting} onComplete={handleKitComplete} />
  );
  else if (screen === "audit") content = (
    <window.WorkerInventoryTab user={user}
      auditWo={activeWO}
      onCompleteAudit={handleAuditDone}
      onExitAudit={handleExitKitting} />
  );
  else if (screen === "completion") content = (
    <window.Completion wo={activeWO} user={user}
      statuses={completionData?.statuses || []} onHandoff={handleHandoff} />
  );
  else if (screen === "badge") content = (
    <window.BadgeEarned badge={earnedBadge}
      totalSessions={(window.BADGES_EARNED[user?.name] || []).length * 20 + 12}
      onContinue={handleBadgeContinue} />
  );

  return (
    <>
      {content}
      <window.ToastHost />
      {user && (
        <>
          <window.InactivityHost onLock={handleLogout} />
          <window.DevInactivityTrigger />
        </>
      )}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
