// Screen 3: Queue Tab
const { useState: useStateQ, useMemo: useMemoQ } = React;

const QUEUE_TYPE_STYLE = {
  KITTING: { text: "text-sky-300", bg: "bg-sky-500/10", border: "border-sky-500/30" },
  ASSY: { text: "text-violet-300", bg: "bg-violet-500/10", border: "border-violet-500/30" },
  SHIPPING: { text: "text-orange-300", bg: "bg-orange-500/10", border: "border-orange-500/30" },
  RECEIVING: { text: "text-teal-300", bg: "bg-teal-500/10", border: "border-teal-500/30" },
  AUDIT: { text: "text-zinc-300", bg: "bg-zinc-700/30", border: "border-zinc-600/50" },
};
const QUEUE_PRIORITY = {
  URGENT: { chip: "bg-red-500 text-white", lborder: "border-l-red-500", glow: "shadow-[0_0_0_1px_rgba(239,68,68,0.2)]" },
  NORMAL: { chip: "bg-amber-400 text-zinc-950", lborder: "border-l-amber-400", glow: "" },
  PLANNED: { chip: "bg-zinc-600 text-zinc-100", lborder: "border-l-zinc-600", glow: "" },
};
const QUEUE_PRIORITY_ORDER = { URGENT: 0, NORMAL: 1, PLANNED: 2 };

function QueueTab({ user, onStartWO, onResume }) {
  const [filter, setFilter] = useStateQ("ALL");
  const [filterOpen, setFilterOpen] = useStateQ(false);

  const orders = useMemoQ(() => {
    const list = [...window.WORK_ORDERS].sort((a, b) => QUEUE_PRIORITY_ORDER[a.priority] - QUEUE_PRIORITY_ORDER[b.priority]);
    return filter === "ALL" ? list : list.filter((o) => o.type === filter);
  }, [filter]);

  const counts = useMemoQ(() => {
    const c = { URGENT: 0, NORMAL: 0, PLANNED: 0 };
    window.WORK_ORDERS.forEach((o) => (c[o.priority] += 1));
    return c;
  }, []);

  const pausedSessions = window.PAUSED_SESSIONS || [];

  const REASON_STYLES = {
    "Ran out of materials": { color: "text-red-300 bg-red-500/10 border-red-500/30", icon: "⚠" },
    "Waiting for supervisor approval": { color: "text-violet-300 bg-violet-500/10 border-violet-500/30", icon: "✋" },
    "Ran out of time / end of shift": { color: "text-sky-300 bg-sky-500/10 border-sky-500/30", icon: "⏱" },
    "Tool / equipment failure": { color: "text-amber-300 bg-amber-500/10 border-amber-500/30", icon: "🔧" },
    "Break / lunch": { color: "text-zinc-300 bg-zinc-700/40 border-zinc-700", icon: "☕" },
    "Other": { color: "text-zinc-300 bg-zinc-700/40 border-zinc-700", icon: "•" },
  };

  return (
    <div className="flex-1 flex flex-col">
      {/* Sub-header */}
      <div className="px-8 py-6 border-b border-zinc-800 flex items-end justify-between flex-wrap gap-6">
        <div>
          <div className="text-[13px] uppercase tracking-[0.22em] text-zinc-500">Today · Tue 19 May</div>
          <h1 className="font-display text-[56px] tracking-tight leading-none mt-1">
            <span className="text-red-400">{counts.URGENT} urgent</span>
            <span className="text-zinc-600"> · </span>
            <span className="text-zinc-400">{counts.NORMAL + counts.PLANNED} more in queue</span>
          </h1>
        </div>
        <div className="flex items-center gap-2 relative">
          <button onClick={() => setFilterOpen((o) => !o)}
            className="h-12 px-4 rounded-lg bg-zinc-900 border border-zinc-800 text-zinc-200 text-[14px] font-medium hover:bg-zinc-800 flex items-center gap-2 uppercase tracking-wider">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>
            Filter · {filter}
          </button>
          {filterOpen && (
            <div className="absolute right-0 top-14 z-20 bg-zinc-900 border border-zinc-800 rounded-xl p-2 flex flex-col gap-1 min-w-[200px]">
              {["ALL", "KITTING", "ASSY", "SHIPPING", "RECEIVING"].map((f) => (
                <button key={f} onClick={() => { setFilter(f); setFilterOpen(false); }}
                  className={`h-11 px-4 text-left rounded-md text-[14px] font-display tracking-wider transition ${
                    f === filter ? "bg-zinc-100 text-zinc-950" : "text-zinc-300 hover:bg-zinc-800"
                  }`}>
                  {f}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Cards */}
      <div className="flex-1 px-8 py-6 space-y-5">
        {/* Paused sessions section */}
        {pausedSessions.length > 0 && (
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <div className="text-[12px] uppercase tracking-[0.22em] text-amber-400 font-semibold">
                ● Paused sessions — {pausedSessions.length}
              </div>
              <div className="text-[12px] text-zinc-500">Anyone on shift can resume.</div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              {pausedSessions.map((p) => {
                const reasonStyle = REASON_STYLES[p.reason] || REASON_STYLES.Other;
                return (
                  <div key={p.id}
                    className="bg-amber-500/5 rounded-xl border border-amber-500/30 border-l-[6px] border-l-amber-400 p-4 flex flex-col gap-3">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="px-2 py-1 rounded text-[11px] font-bold uppercase tracking-wider bg-zinc-900 text-zinc-300 border border-zinc-700">
                          {p.woType}
                        </span>
                        <span className={`px-2 py-1 rounded text-[11px] font-bold uppercase tracking-wider border ${reasonStyle.color}`}>
                          <span className="mr-1">{reasonStyle.icon}</span>{p.reason}
                        </span>
                      </div>
                      <span className="font-mono text-[12px] text-zinc-500">{p.woId}</span>
                    </div>
                    <div>
                      <div className="font-display text-[24px] tracking-tight leading-tight">{p.name}</div>
                      <div className="font-mono text-[13px] text-zinc-400 mt-1">{p.progress}</div>
                    </div>
                    {p.note && (
                      <div className="text-[13px] text-zinc-300 bg-zinc-900/60 border border-zinc-800 rounded-lg p-2.5 leading-snug">
                        “{p.note}”
                      </div>
                    )}
                    <div className="flex items-center justify-between gap-3 pt-1">
                      <div className="text-[12px] text-zinc-500">
                        Paused by <span className="text-zinc-300">{p.pausedBy}</span> · {p.pausedAt}
                      </div>
                      <button onClick={() => onResume(p)}
                        className="h-[52px] px-5 rounded-lg bg-amber-400 text-zinc-950 font-display text-[18px] tracking-wider hover:bg-amber-300 active:scale-[0.99] transition">
                        RESUME →
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* New work orders */}
        <div className="grid grid-cols-2 gap-5">
          {orders.map((o) => <WOCard key={o.id} o={o} onStartWO={onStartWO} />)}
        </div>
      </div>
    </div>
  );
}

function WOCard({ o, onStartWO }) {
  const t = QUEUE_TYPE_STYLE[o.type];
  const p = QUEUE_PRIORITY[o.priority];
  const startable = ["KITTING", "ASSY", "SHIPPING", "RECEIVING", "AUDIT"].includes(o.type);
  const colorByType = { KITTING: "emerald", ASSY: "violet", SHIPPING: "orange", RECEIVING: "teal", AUDIT: "amber" };

  return (
    <div className={`relative bg-zinc-900 rounded-xl border border-zinc-800 ${p.glow} border-l-[6px] ${p.lborder} p-6 flex flex-col gap-4`}>
      {/* Top row */}
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2 flex-wrap">
          <span className={`px-2.5 py-1 rounded-md text-[12px] font-bold uppercase tracking-wider ${t.bg} ${t.text} border ${t.border}`}>
            {o.type}
          </span>
          <span className={`px-2.5 py-1 rounded-md text-[12px] font-bold uppercase tracking-wider ${p.chip}`}>
            {o.priority === "URGENT" && "● "}{o.priority}
          </span>
        </div>
        <div className="text-zinc-500 text-[13px] font-mono">{o.id}</div>
      </div>

      {/* Thumbnail + body */}
      <div className="flex gap-4">
        <div className="h-[80px] w-[80px] flex-shrink-0 rounded-lg bg-zinc-800 border border-zinc-700/50 flex items-center justify-center text-zinc-600">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
            <polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" />
          </svg>
        </div>
        <div className="flex-1 min-w-0">
          <div className="font-display text-[30px] leading-tight tracking-tight">{o.name}</div>
          <div className="text-zinc-400 text-[14px] font-mono mt-1">{o.sku}</div>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-3 py-3 border-y border-zinc-800">
        <div>
          <div className="text-[11px] uppercase tracking-wider text-zinc-500">Qty</div>
          <div className="font-display text-[34px] tabular-nums leading-none mt-1">{o.qty}</div>
        </div>
        <div>
          <div className="text-[11px] uppercase tracking-wider text-zinc-500">Due</div>
          <div className="text-[17px] font-medium leading-none mt-2">{o.due}</div>
        </div>
        <div>
          <div className="text-[11px] uppercase tracking-wider text-zinc-500">Where</div>
          <div className="text-[15px] font-medium leading-tight mt-1.5">{o.location}</div>
        </div>
      </div>

      {/* Orders */}
      <div className="flex items-center gap-1.5 flex-wrap min-h-[28px]">
        {o.orders.slice(0, 3).map((ord) => (
          <span key={ord} className="font-mono text-[12px] text-zinc-400 bg-zinc-800/60 border border-zinc-800 rounded px-2 py-1">
            {ord}
          </span>
        ))}
        {o.orders.length > 3 && <span className="text-[12px] text-zinc-500">+{o.orders.length - 3} more</span>}
      </div>

      {/* Hold-to-start button */}
      <window.HoldButton
        disabled={!startable}
        color={colorByType[o.type] || "zinc"}
        onComplete={() => onStartWO(o)}
        className="h-[88px] text-[26px]"
        subText={startable ? "press and hold to start" : null}>
        {startable ? "START →" : `START (${o.type.toLowerCase()})`}
      </window.HoldButton>
    </div>
  );
}

window.QueueTab = QueueTab;
