// Pause modal — three sub-flows driven by reason type:
//   "materials"  → bounce back to workflow with an inventory-update form;
//                  if worker has enough → return to workflow (no pause), else pause with snapshot
//   "describe"   → note field is REQUIRED; tells manager something is wrong
//   "simple"     → optional note, single tap to pause
//
// Any note submitted → simulated manager ping via toast.
const { useState: useStatePM, useMemo: useMemoPM } = React;

const PAUSE_REASONS = [
  { id: "materials", label: "Ran out of materials", type: "materials", icon: "⚠", color: "red" },
  { id: "time",      label: "Ran out of time / end of shift", type: "simple", icon: "⏱", color: "sky" },
  { id: "tool",      label: "Tool / equipment failure", type: "describe", icon: "🔧", color: "amber" },
  { id: "break",     label: "Break / lunch", type: "simple", icon: "☕", color: "zinc" },
  { id: "other",     label: "Other", type: "describe", icon: "•", color: "zinc" },
];

function PauseModal({
  context, reasons = PAUSE_REASONS,
  defaultMaterial,           // { sku, name, expected }  optional
  taskContext,               // { totalUnits, alreadyFinished, perUnit }  optional
  onCancel,                  // dismiss with no action
  onPause,                   // ({ reason, note, materialUpdate? }) → actually pause + exit
  onMaterialResolved,        // ({ sku, actualQty }) → worker has enough, return to workflow
}) {
  const [reason, setReason] = useStatePM(null);
  const [note, setNote] = useStatePM("");
  // material sub-form state
  const [matSku, setMatSku] = useStatePM(defaultMaterial?.sku || "");
  const [matQty, setMatQty] = useStatePM(0);
  const [finished, setFinished] = useStatePM(taskContext?.alreadyFinished ?? 0);
  const [perUnit, setPerUnit] = useStatePM(taskContext?.perUnit ?? 1);

  const inventory = window.INVENTORY || [];

  const needsNote = reason?.type === "describe";
  const isMaterials = reason?.type === "materials";
  const canSubmitGeneric = reason && (!needsNote || note.trim().length >= 4);

  function pingManager(message) {
    window.gpsToast && window.gpsToast({
      message,
      tone: "warn",
    });
  }

  function handleSimplePause() {
    const msg = note.trim()
      ? `Session paused · ${reason.label} · manager notified`
      : `Session paused · ${reason.label}`;
    onPause({ reason: reason.label, note: note.trim() });
    setTimeout(() => pingManager(msg), 50);
  }

  function handleMaterialEnough() {
    onMaterialResolved && onMaterialResolved({ sku: matSku, actualQty: matQty });
    setTimeout(() => {
      window.gpsToast && window.gpsToast({
        message: `Inventory updated · ${matSku} now ${matQty} on hand · enough to finish · resuming`,
        tone: "ok",
      });
    }, 50);
  }
  function handleMaterialPause() {
    const remaining = (taskContext?.totalUnits || 0) - finished;
    const canFinish = perUnit > 0 ? Math.floor(matQty / perUnit) : 0;
    const shortBy = Math.max(0, remaining * perUnit - matQty);
    const autoNote = `Short on ${matSku}: ${matQty} on hand, need ${remaining * perUnit} for ${remaining} units (short ${shortBy}). Already finished ${finished}/${taskContext?.totalUnits}. Can complete ${canFinish} more if continuing partial. ${note.trim() ? "— " + note.trim() : ""}`;
    onPause({ reason: reason.label, note: autoNote, materialUpdate: { sku: matSku, actualQty: matQty } });
    setTimeout(() => {
      window.gpsToast && window.gpsToast({
        message: `Paused · short on ${matSku} · manager notified`,
        tone: "warn",
      });
    }, 50);
  }

  // Suggest materials: prepend defaultMaterial's SKU, then everything in inventory.
  const skuOptions = useMemoPM(() => {
    const seen = new Set();
    const out = [];
    if (defaultMaterial?.sku) { out.push(defaultMaterial.sku); seen.add(defaultMaterial.sku); }
    inventory.forEach((it) => { if (!seen.has(it.sku)) { out.push(it.sku); seen.add(it.sku); } });
    return out;
  }, [defaultMaterial?.sku]);

  const matInventory = inventory.find((it) => it.sku === matSku);

  return (
    <div className="fixed inset-0 z-50 bg-zinc-950/85 backdrop-blur-sm flex items-center justify-center p-8 text-zinc-100" style={{ animation: "fadeIn 0.18s" }}>
      <div className="w-full max-w-[760px] bg-zinc-900 border border-zinc-800 rounded-2xl p-8 max-h-[92vh] overflow-y-auto">
        <div className="text-[12px] uppercase tracking-[0.22em] text-amber-400">Pause session</div>
        <div className="font-display text-[40px] tracking-tight mt-1">
          {!reason ? "Why are you pausing?" :
           isMaterials ? "Quick — let's update inventory" :
           needsNote ? `Describe the ${reason.id === "tool" ? "failure" : "issue"}` :
           "Confirm pause"}
        </div>

        <p className="text-[15px] text-zinc-400 mt-3">
          {!reason ? "Pick a reason. Some bring you back to work after a quick check; others end your session and notify a manager." :
           isMaterials ? "Don't pause yet. Update what you actually have on hand — if it's enough, you'll go right back to work." :
           needsNote ? "Describe what went wrong so a manager can resolve it. Submitting will ping them now." :
           "Your progress is saved. Anyone on shift can resume from the queue."}
        </p>

        <div className="mt-3 p-3 rounded-lg bg-zinc-950 border border-zinc-800 text-[13px] text-zinc-400 font-mono">
          {context}
        </div>

        {/* Stage 1 — reason picker */}
        {!reason && (
          <div className="mt-5">
            <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Reason</div>
            <div className="flex flex-col gap-2">
              {reasons.map((r) => (
                <button key={r.id} onClick={() => setReason(r)}
                  className="h-[64px] px-4 rounded-lg text-[16px] text-left font-display tracking-wider transition flex items-center gap-3 bg-zinc-950 border-2 border-zinc-800 text-zinc-200 hover:border-zinc-600">
                  <span className="text-[20px] w-8 text-center">{r.icon}</span>
                  <span className="flex-1">{r.label}</span>
                  {r.type === "materials" && (
                    <span className="text-[11px] uppercase tracking-wider text-red-300 bg-red-500/10 border border-red-500/30 rounded px-2 py-0.5">checks inventory</span>
                  )}
                  {r.type === "describe" && (
                    <span className="text-[11px] uppercase tracking-wider text-amber-300 bg-amber-500/10 border border-amber-500/30 rounded px-2 py-0.5">notifies manager</span>
                  )}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Stage 2a — materials sub-flow — live calculator */}
        {isMaterials && (() => {
          const totalUnits = taskContext?.totalUnits ?? 0;
          const remaining = Math.max(0, totalUnits - finished);
          const needed = remaining * perUnit;
          const enough = matQty >= needed && remaining > 0;
          const canFinishMore = perUnit > 0 ? Math.floor(matQty / perUnit) : 0;
          const shortBy = Math.max(0, needed - matQty);
          return (
            <div className="mt-5 space-y-4">
              {/* Inputs */}
              <div>
                <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">What are you out of?</div>
                <select value={matSku} onChange={(e) => setMatSku(e.target.value)}
                  className="w-full h-[56px] px-4 bg-zinc-950 border border-zinc-800 rounded-xl text-[15px] outline-none focus:border-zinc-600">
                  <option value="">Select SKU…</option>
                  {skuOptions.map((sku) => {
                    const it = inventory.find((x) => x.sku === sku);
                    return <option key={sku} value={sku}>{sku} — {it?.name || "—"}</option>;
                  })}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">Actual on hand</div>
                  <div className="flex items-center gap-2">
                    <button onClick={() => setMatQty(Math.max(0, matQty - 1))}
                      className="h-[60px] w-[44px] rounded-lg bg-zinc-800 border border-zinc-700 text-[22px] font-display">−</button>
                    <input type="number" value={matQty}
                      onChange={(e) => setMatQty(Math.max(0, parseInt(e.target.value || "0", 10)))}
                      className="flex-1 h-[68px] bg-zinc-950 border border-zinc-800 rounded-lg text-center font-display text-[32px] tabular-nums outline-none focus:border-zinc-600 min-w-0" />
                    <button onClick={() => setMatQty(matQty + 1)}
                      className="h-[60px] w-[44px] rounded-lg bg-zinc-800 border border-zinc-700 text-[22px] font-display">+</button>
                  </div>
                  {matInventory && matQty !== matInventory.qty && (
                    <div className="text-[11px] mt-1.5">
                      <span className={matQty < matInventory.qty ? "text-red-400" : "text-emerald-400"}>{matQty > matInventory.qty ? "+" : ""}{matQty - matInventory.qty}</span>
                      <span className="text-zinc-500"> vs system count of {matInventory.qty}</span>
                    </div>
                  )}
                </div>
                <div>
                  <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">
                    Units finished so far
                    {totalUnits > 0 && <span className="text-zinc-500 normal-case ml-1">of {totalUnits}</span>}
                  </div>
                  <div className="flex items-center gap-2">
                    <button onClick={() => setFinished(Math.max(0, finished - 1))}
                      className="h-[60px] w-[44px] rounded-lg bg-zinc-800 border border-zinc-700 text-[22px] font-display">−</button>
                    <input type="number" value={finished}
                      onChange={(e) => setFinished(Math.max(0, Math.min(totalUnits || 9999, parseInt(e.target.value || "0", 10))))}
                      className="flex-1 h-[68px] bg-zinc-950 border border-zinc-800 rounded-lg text-center font-display text-[32px] tabular-nums outline-none focus:border-zinc-600 min-w-0" />
                    <button onClick={() => setFinished(Math.min(totalUnits || 9999, finished + 1))}
                      className="h-[60px] w-[44px] rounded-lg bg-zinc-800 border border-zinc-700 text-[22px] font-display">+</button>
                  </div>
                </div>
              </div>

              {/* Per-unit (small, editable) */}
              <div className="flex items-center gap-3 bg-zinc-950/60 border border-zinc-800 rounded-lg px-4 py-2">
                <div className="text-[12px] uppercase tracking-wider text-zinc-500">Per unit</div>
                <input type="number" step="0.5" value={perUnit}
                  onChange={(e) => setPerUnit(Math.max(0, parseFloat(e.target.value || "0")))}
                  className="h-[36px] w-[80px] bg-zinc-900 border border-zinc-800 rounded text-center font-mono tabular-nums outline-none focus:border-zinc-600" />
                <div className="text-[12px] text-zinc-500">how many {matSku || "of this"} per assembled / kitted unit</div>
              </div>

              {/* Calculator result */}
              {matSku && (
                <div className={`rounded-xl border-2 p-5 space-y-3 ${
                  enough
                    ? "bg-emerald-500/10 border-emerald-500/40"
                    : "bg-amber-500/10 border-amber-500/40"
                }`}>
                  <div className="flex items-center justify-between">
                    <div className="text-[12px] uppercase tracking-[0.22em] font-semibold">
                      <span className={enough ? "text-emerald-300" : "text-amber-300"}>
                        {enough ? "✓ Enough to finish" : "⚠ Short for full run"}
                      </span>
                    </div>
                    <div className="text-[12px] text-zinc-400">
                      auto-updates inventory
                    </div>
                  </div>
                  <div className="font-display text-[36px] tabular-nums leading-none">
                    {enough ? (
                      <>Can finish all <span className="text-emerald-300">{remaining}</span> remaining</>
                    ) : (
                      <>Can finish <span className="text-amber-300">{Math.min(canFinishMore, remaining)}</span> of <span className="text-zinc-300">{remaining}</span> remaining</>
                    )}
                  </div>
                  <div className="grid grid-cols-4 gap-2 text-[12px]">
                    <Tile label="Remaining" value={`${remaining}`} />
                    <Tile label="Need" value={`${needed}`} />
                    <Tile label="Have" value={`${matQty}`} />
                    <Tile label={enough ? "Surplus" : "Short by"}
                      value={enough ? `+${matQty - needed}` : `${shortBy}`}
                      tone={enough ? "ok" : "warn"} />
                  </div>
                </div>
              )}

              {/* CTAs */}
              <div className="grid grid-cols-[1fr_2fr] gap-3 mt-2">
                <button onClick={() => { setReason(null); setMatSku(defaultMaterial?.sku || ""); setMatQty(0); }}
                  className="h-[80px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[16px] tracking-wider hover:bg-zinc-700">
                  BACK
                </button>
                {enough ? (
                  <button onClick={handleMaterialEnough} disabled={!matSku}
                    className="h-[80px] rounded-xl bg-emerald-500 text-zinc-950 font-display text-[20px] tracking-wider hover:bg-emerald-400 disabled:opacity-40 disabled:cursor-not-allowed flex flex-col items-center justify-center gap-1">
                    <span>UPDATE INVENTORY · BACK TO WORK</span>
                    <span className="text-[11px] opacity-70 normal-case tracking-normal">enough on hand to finish run</span>
                  </button>
                ) : (
                  <button onClick={handleMaterialPause} disabled={!matSku}
                    className="h-[80px] rounded-xl bg-amber-400 text-zinc-950 font-display text-[20px] tracking-wider hover:bg-amber-300 disabled:opacity-40 disabled:cursor-not-allowed flex flex-col items-center justify-center gap-1">
                    <span>UPDATE INVENTORY · PAUSE FOR RESTOCK</span>
                    <span className="text-[11px] opacity-70 normal-case tracking-normal">short by {shortBy} · manager pinged</span>
                  </button>
                )}
              </div>
            </div>
          );
        })()}

        {/* Stage 2b — describe (note required) */}
        {needsNote && (
          <div className="mt-5 space-y-4">
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">
                What happened? <span className="text-red-400">required</span>
              </div>
              <textarea value={note} onChange={(e) => setNote(e.target.value)} autoFocus
                placeholder={reason.id === "tool"
                  ? "Which tool? What failed? Last known good?"
                  : "Describe the issue for the next worker / manager"}
                className="w-full h-[160px] bg-zinc-950 border-2 border-zinc-800 rounded-xl p-3 text-[16px] text-zinc-100 outline-none focus:border-zinc-600 resize-none" />
              <div className="text-[12px] text-zinc-500 mt-2">
                A manager will be notified the moment you pause.
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <button onClick={() => { setReason(null); setNote(""); }}
                className="h-[64px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[18px] tracking-wider hover:bg-zinc-700">
                BACK
              </button>
              <button onClick={handleSimplePause} disabled={!canSubmitGeneric}
                className="h-[64px] rounded-xl bg-amber-400 text-zinc-950 font-display text-[18px] tracking-wider hover:bg-amber-300 disabled:opacity-40 disabled:cursor-not-allowed">
                PAUSE & PING MANAGER
              </button>
            </div>
          </div>
        )}

        {/* Stage 2c — simple reason (optional note) */}
        {reason && !isMaterials && !needsNote && (
          <div className="mt-5 space-y-4">
            <div>
              <div className="text-[12px] uppercase tracking-wider text-zinc-400 mb-2">
                Note for next worker (optional)
              </div>
              <textarea value={note} onChange={(e) => setNote(e.target.value)}
                placeholder="Anything they should know? Skip if not."
                className="w-full h-[100px] bg-zinc-950 border border-zinc-800 rounded-xl p-3 text-[15px] text-zinc-100 outline-none focus:border-zinc-600 resize-none" />
              {note.trim() && (
                <div className="text-[12px] text-amber-300 mt-2">
                  Adding a note will also ping a manager.
                </div>
              )}
            </div>
            <div className="grid grid-cols-2 gap-3">
              <button onClick={() => { setReason(null); setNote(""); }}
                className="h-[64px] rounded-xl bg-zinc-800 border border-zinc-700 text-zinc-100 font-display text-[18px] tracking-wider hover:bg-zinc-700">
                BACK
              </button>
              <button onClick={handleSimplePause}
                className="h-[64px] rounded-xl bg-amber-400 text-zinc-950 font-display text-[18px] tracking-wider hover:bg-amber-300">
                PAUSE SESSION
              </button>
            </div>
          </div>
        )}

        {/* Cancel always */}
        {!reason && (
          <button onClick={onCancel}
            className="mt-4 h-12 w-full rounded-lg text-zinc-400 text-[14px] hover:bg-zinc-800 uppercase tracking-wider">
            Cancel — keep working
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PauseModal, PAUSE_REASONS });

function Tile({ label, value, tone = "neutral" }) {
  const color =
    tone === "warn" ? "text-amber-300" :
    tone === "ok" ? "text-emerald-300" :
    "text-zinc-100";
  return (
    <div className="bg-zinc-950/60 border border-zinc-800 rounded-lg px-2.5 py-2">
      <div className="text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className={`font-display text-[20px] tabular-nums leading-none mt-1 ${color}`}>{value}</div>
    </div>
  );
}
