// automations.jsx — node-based workflow builder + auto-resolution agent
const { useState: useStateAU, useEffect: useEffectAU } = React;

/* ---------- workflow node card ---------- */
function FlowNode({ icon, kind, title, detail, tint, assignee, onAssigneeChange, users, canManage }) {
  const tints = {
    trigger:   { bg: "#eef2ff", ic: "#4338ca", tag: "TRIGGER",   tagc: "#4338ca" },
    condition: { bg: "#fff7ed", ic: "#c2410c", tag: "CONDITION", tagc: "#c2410c" },
    action:    { bg: "var(--accent-wash)", ic: "var(--accent)", tag: "ACTION", tagc: "var(--accent-ink)" },
  };
  const t = tints[kind];
  const [showPicker, setShowPicker] = useStateAU(false);

  return (
    <div className="bg-white rounded-xl border border-zinc-200 shadow-[0_1px_3px_rgba(0,0,0,0.04)] p-3 w-[240px]">
      <div className="flex items-center gap-2 mb-2">
        <span className="flex items-center justify-center w-7 h-7 rounded-lg shrink-0" style={{ background: t.bg, color: t.ic }}><Icon name={icon} size={15} /></span>
        <span className="text-[9.5px] font-bold tracking-wider" style={{ color: t.tagc }}>{t.tag}</span>
      </div>
      <div className="text-[12.5px] font-semibold text-zinc-800 leading-snug">{title}</div>
      {detail && !assignee && <div className="text-[11px] text-zinc-400 mt-0.5">{detail}</div>}

      {/* assignee row with picker */}
      {assignee !== undefined && (
        <div className="relative mt-2">
          <button onClick={() => canManage && setShowPicker(s => !s)}
            className={`flex items-center gap-1.5 text-[11px] font-medium px-2 py-1 rounded-md w-full text-left transition-colors ${canManage ? "hover:bg-zinc-100 cursor-pointer" : "cursor-default"}`}
            style={{ color: "var(--accent-ink)", background: "var(--accent-wash)" }}>
            {assignee ? (
              <>
                <span className="inline-flex items-center justify-center w-4 h-4 rounded-full text-white text-[8px] font-bold shrink-0"
                  style={{ background: users?.find(u => u.name === assignee)?.color || "#0d9488" }}>
                  {assignee.split(" ").map(w => w[0]).join("").slice(0,2)}
                </span>
                <span className="truncate">{assignee}</span>
                {canManage && <Icon name="chevdown" size={10} className="ml-auto shrink-0 text-zinc-400" />}
              </>
            ) : (
              <><Icon name="user" size={11} /><span>Pick assignee…</span><Icon name="chevdown" size={10} className="ml-auto text-zinc-400" /></>
            )}
          </button>
          {showPicker && users && (
            <>
              <div className="fixed inset-0 z-10" onClick={() => setShowPicker(false)} />
              <div className="absolute left-0 top-8 z-20 w-52 bg-white rounded-xl border border-zinc-200 shadow-lg py-1 max-h-52 overflow-y-auto">
                {users.filter(u => u.status === "active").map(u => (
                  <button key={u.id} onClick={() => { onAssigneeChange(u.name); setShowPicker(false); }}
                    className="w-full flex items-center gap-2 px-3 py-2 hover:bg-zinc-50 text-left">
                    <span className="inline-flex items-center justify-center w-6 h-6 rounded-full text-white text-[9px] font-bold shrink-0"
                      style={{ background: u.color }}>{u.initials}</span>
                    <div className="min-w-0">
                      <div className="text-[12.5px] font-medium text-zinc-800 truncate">{u.name}</div>
                      <div className="text-[10.5px] text-zinc-400 truncate">{u.dept} · {ROLES[u.role]?.label}</div>
                    </div>
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
}

function Connector({ vertical }) {
  if (vertical) return <div className="flex justify-center"><div className="w-px h-5 bg-zinc-300" /></div>;
  return (
    <div className="flex items-center justify-center px-1 shrink-0">
      <div className="w-6 h-px bg-zinc-300" /><Icon name="chevright" size={14} className="text-zinc-300 -ml-1" />
    </div>
  );
}

function WorkflowBuilder({ canManage, session, onToast }) {
  const [list, setList] = useStateAU(AUTOMATIONS);
  const [sel, setSel] = useStateAU(AUTOMATIONS[0].id);
  const [users, setUsers] = useStateAU([]);
  const [triggering, setTriggering] = useStateAU(false);

  useEffectAU(() => {
    sb.from("profiles").select("id, name, initials, color, role, dept, status")
      .then(({ data }) => { if (data?.length) setUsers(data); });
  }, []);

  const wf = list.find(w => w.id === sel);

  function toggle(id) {
    setList(ls => ls.map(w => w.id === id ? { ...w, enabled: !w.enabled } : w));
    const w = list.find(x => x.id === id);
    onToast(`"${w.name}" ${w.enabled ? "paused" : "activated"}`, { icon: w.enabled ? "pause" : "zap", tone: w.enabled ? "warn" : "ok" });
  }

  function setAssignee(wfId, actionIdx, name) {
    setList(ls => ls.map(w => w.id !== wfId ? w : {
      ...w,
      actions: w.actions.map((a, i) => i !== actionIdx ? a : { ...a, detail: name })
    }));
    onToast(`Assignee updated to ${name}`, { icon: "user" });
  }

  return (
    <div className="flex gap-4 flex-col lg:flex-row">
      {/* left: automation list */}
      <div className="lg:w-[280px] shrink-0 space-y-2">
        {list.map(w => {
          const on = w.id === sel;
          return (
            <button key={w.id} onClick={() => setSel(w.id)}
              className={`w-full text-left bg-white rounded-xl border p-3 transition-all ${on ? "border-transparent ring-1" : "border-zinc-200 hover:border-zinc-300"}`}
              style={on ? { boxShadow: "0 0 0 1.5px var(--accent)" } : undefined}>
              <div className="flex items-center gap-2">
                <span className="flex items-center justify-center w-7 h-7 rounded-lg shrink-0"
                  style={{ background: w.enabled ? "var(--accent-wash)" : "#f4f4f5", color: w.enabled ? "var(--accent)" : "#a1a1aa" }}>
                  <Icon name="zap" size={14} />
                </span>
                <span className="text-[13px] font-semibold text-zinc-800 flex-1 leading-tight">{w.name}</span>
                <span className={`w-1.5 h-1.5 rounded-full ${w.enabled ? "bg-emerald-500" : "bg-zinc-300"}`} />
              </div>
              <div className="flex items-center gap-2 mt-2 text-[11px] text-zinc-400">
                <span className="inline-flex items-center gap-1"><Icon name="bolt" size={11} />{w.actions.length} action{w.actions.length !== 1 ? "s" : ""}</span>
                <span>·</span>
                <span>{w.runsToday} runs today</span>
              </div>
            </button>
          );
        })}
        {canManage && (
          <Button variant="default" size="md" icon="plus" full onClick={() => onToast("New automation editor coming soon", { icon: "zap" })}>
            New automation
          </Button>
        )}
      </div>

      {/* right: canvas */}
      <div className="flex-1 bg-white rounded-xl border border-zinc-200 overflow-hidden">
        <div className="flex items-center gap-3 px-5 py-3.5 border-b border-zinc-200">
          <div>
            <h3 className="text-[14px] font-semibold text-zinc-900">{wf.name}</h3>
            <p className="text-[11.5px] text-zinc-400 leading-tight mt-0.5 max-w-md">{wf.desc}</p>
          </div>
          <div className="ml-auto flex items-center gap-2.5">
            <span className={`text-[11.5px] font-medium ${wf.enabled ? "text-emerald-600" : "text-zinc-400"}`}>
              {wf.enabled ? "Active" : "Paused"}
            </span>
            <Toggle on={wf.enabled} onChange={() => canManage ? toggle(wf.id) : onToast("Read-only — you can't edit automations", { tone: "warn", icon: "eye" })} />
          </div>
        </div>

        {/* how triggers work — info strip */}
        <div className="flex items-start gap-2 px-5 py-2.5 bg-indigo-50/60 border-b border-indigo-100 text-[11.5px] text-indigo-700">
          <Icon name="info" size={13} className="mt-0.5 shrink-0" />
          <span>
            When the <strong>WHEN</strong> event fires, conditions are checked top-to-bottom.
            If all pass, <strong>THEN</strong> actions run in sequence — the assigned person receives a task in their <em>My Tasks</em> queue instantly.
          </span>
        </div>

        {/* node canvas */}
        <div className="p-6 overflow-x-auto" style={{ backgroundImage: "radial-gradient(#e4e4e7 1px, transparent 1px)", backgroundSize: "18px 18px" }}>
          <div className="flex items-start gap-1 min-w-max">
            {/* WHEN */}
            <div>
              <div className="text-[10px] font-bold tracking-wider text-zinc-400 mb-2 pl-1">WHEN</div>
              <FlowNode kind="trigger" icon={wf.trigger.icon} title={wf.trigger.title} detail={wf.trigger.detail} />
            </div>

            {/* IF */}
            {wf.conditions.length > 0 && (
              <>
                <div className="pt-9"><Connector /></div>
                <div>
                  <div className="text-[10px] font-bold tracking-wider text-zinc-400 mb-2 pl-1">IF</div>
                  <div className="space-y-2">
                    {wf.conditions.map((c, i) => <FlowNode key={i} kind="condition" icon={c.icon} title={c.title} detail={c.detail} />)}
                  </div>
                </div>
              </>
            )}

            {/* THEN */}
            <div className="pt-9"><Connector /></div>
            <div>
              <div className="text-[10px] font-bold tracking-wider text-zinc-400 mb-2 pl-1">THEN</div>
              <div className="space-y-2">
                {wf.actions.map((a, i) => {
                  const isAssign = a.icon === "user";
                  return (
                    <div key={i}>
                      {i > 0 && <Connector vertical />}
                      <FlowNode
                        kind="action" icon={a.icon} title={a.title}
                        detail={isAssign ? undefined : a.detail}
                        assignee={isAssign ? a.detail : undefined}
                        onAssigneeChange={(name) => setAssignee(wf.id, i, name)}
                        users={users}
                        canManage={canManage}
                      />
                    </div>
                  );
                })}
                {canManage && (
                  <Button variant="default" size="sm" icon="plus" full
                    onClick={() => onToast("Action editor coming soon", { icon: "zap" })}>
                    Add action
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="flex items-center justify-between px-5 py-3 border-t border-zinc-100 bg-zinc-50/50">
          <span className="text-[12px] text-zinc-400 inline-flex items-center gap-1.5">
            <Icon name="activity" size={13} /> Ran {wf.runsToday} times today · last 12 min ago
          </span>
          {canManage && (
            <div className="flex items-center gap-2">
              <Button variant="default" size="sm" icon="check" onClick={() => onToast("Saved", { icon: "check" })}>Save changes</Button>
              <Button variant="primary" size="sm" icon="zap" onClick={() => setTriggering(true)}>Run now</Button>
            </div>
          )}
        </div>
      </div>
      {triggering && (
        <TriggerModal wf={wf} assignees={users} session={session} onClose={() => setTriggering(false)} onToast={onToast} />
      )}
    </div>
  );
}

/* ---------- Auto-Resolution Agent ---------- */
function ResolutionAgent({ canManage, onToast, onOpenOrder }) {
  const [runs] = useStateAU(() => agentRuns());
  const [threshold, setThreshold] = useStateAU(85);
  const [agentOn, setAgentOn] = useStateAU(true);
  const [sel, setSel] = useStateAU(runs[0].id);
  const [resolved, setResolved] = useStateAU({});
  const run = runs.find(r => r.id === sel);

  const autoCount = runs.filter(r => r.conf >= threshold).length;
  const avgConf = Math.round(runs.reduce((a, r) => a + r.conf, 0) / runs.length);

  function approve(r) {
    setResolved(m => ({ ...m, [r.id]: "auto" }));
    onToast(`${r.id} auto-resolved (${r.conf}% confidence)`, { icon: "resolve", tone: "ok" });
  }
  function human(r) {
    setResolved(m => ({ ...m, [r.id]: "human" }));
    onToast(`${r.id} routed to ${r.target} for review`, { icon: "user" });
  }

  return (
    <div>
      {/* control bar */}
      <div className="bg-white rounded-xl border border-zinc-200 p-4 mb-4">
        <div className="flex items-center gap-3 flex-wrap">
          <span className="flex items-center justify-center w-9 h-9 rounded-lg shrink-0"
            style={{ background: agentOn ? "var(--accent-wash)" : "#f4f4f5", color: agentOn ? "var(--accent)" : "#a1a1aa" }}>
            <Icon name="cpu" size={18} />
          </span>
          <div>
            <div className="flex items-center gap-2">
              <h3 className="text-[14px] font-semibold text-zinc-900">Auto-Resolution Agent</h3>
              <span className="inline-flex items-center gap-1 text-[11px] font-medium px-1.5 py-0.5 rounded-md"
                style={{ background: agentOn ? "#f0fdf4" : "#f4f4f5", color: agentOn ? "#15803d" : "#71717a" }}>
                <span className={`w-1.5 h-1.5 rounded-full ${agentOn ? "bg-emerald-500 animate-pulse" : "bg-zinc-400"}`} />
                {agentOn ? "Running" : "Paused"}
              </span>
            </div>
            <p className="text-[11.5px] text-zinc-400 mt-0.5">Detects, recommends, drafts &amp; scores confidence on every new exception.</p>
          </div>
          <div className="ml-auto flex items-center gap-4 flex-wrap">
            <div className="flex items-center gap-2.5">
              <span className="text-[12px] text-zinc-500">Auto-resolve at ≥</span>
              <input type="range" min="60" max="99" value={threshold} disabled={!canManage}
                onChange={e => setThreshold(+e.target.value)} className="w-28" style={{ accentColor: "var(--accent)" }} />
              <span className="text-[13px] font-semibold tabular-nums w-9" style={{ color: "var(--accent-ink)" }}>{threshold}%</span>
            </div>
            <Toggle on={agentOn} onChange={() => canManage ? setAgentOn(v => !v) : onToast("Read-only role", { tone: "warn", icon: "eye" })} />
          </div>
        </div>
        <div className="grid grid-cols-3 gap-3 mt-4 pt-4 border-t border-zinc-100">
          {[
            ["Auto-resolve eligible", autoCount, "text-emerald-600"],
            ["Avg confidence", avgConf + "%", "text-zinc-900"],
            ["Needs human review", runs.filter(r => r.conf < threshold).length, "text-orange-600"]
          ].map(([l, v, c]) => (
            <div key={l}>
              <div className="text-[11.5px] text-zinc-500">{l}</div>
              <div className={`text-[20px] font-semibold tabular-nums ${c}`}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="flex gap-4 flex-col lg:flex-row">
        {/* run list */}
        <div className="lg:w-[320px] shrink-0 space-y-2">
          {runs.map(r => {
            const on = r.id === sel;
            const dec = AGENT_DECISION[r.conf >= threshold ? "auto" : r.conf >= 60 ? "review" : "human"];
            return (
              <button key={r.id} onClick={() => setSel(r.id)}
                className={`w-full text-left bg-white rounded-xl border p-3 transition-all ${on ? "border-transparent ring-1" : "border-zinc-200 hover:border-zinc-300"}`}
                style={on ? { boxShadow: "0 0 0 1.5px var(--accent)" } : undefined}>
                <div className="flex items-center gap-3">
                  <ConfRing value={r.conf} />
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-1.5">
                      <span className="font-mono text-[11.5px] text-zinc-500">{r.id}</span>
                      {resolved[r.id] && <Icon name="check" size={12} className="text-emerald-500" />}
                    </div>
                    <div className="text-[12.5px] font-medium text-zinc-800 truncate">{r.row.customer.name}</div>
                    <div className="text-[11px] text-zinc-400 truncate">{r.row.issue}</div>
                  </div>
                </div>
                <div className="mt-2 inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium"
                  style={{ background: dec.bg, color: dec.color }}>
                  <span className="w-1.5 h-1.5 rounded-full" style={{ background: dec.dot }} />{dec.label}
                </div>
              </button>
            );
          })}
        </div>

        {/* pipeline detail */}
        <div className="flex-1 bg-white rounded-xl border border-zinc-200 overflow-hidden">
          <div className="flex items-center gap-3 px-5 py-3.5 border-b border-zinc-200">
            <Avatar person={run.row.customer} size={32} />
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <span className="text-[13.5px] font-semibold text-zinc-800">{run.row.customer.name}</span>
                <span className="font-mono text-[11px] text-zinc-400">{run.id}</span>
              </div>
              <div className="text-[11.5px] text-zinc-400">{run.row.car} · {run.row.issue}</div>
            </div>
            <Button variant="default" size="sm" icon="arrow_r" iconRight onClick={() => onOpenOrder(run.row)} className="ml-auto">
              Open order
            </Button>
          </div>

          {/* pipeline steps */}
          <div className="p-5">
            <ol className="relative space-y-3">
              {AGENT_STEPS.map((s, i) => {
                const conf = run.steps[s.key];
                const last = i === AGENT_STEPS.length - 1;
                return (
                  <li key={s.key} className="relative flex gap-3">
                    {!last && <span className="absolute left-[15px] top-8 h-[calc(100%-8px)] w-px bg-zinc-200" />}
                    <span className="relative z-10 flex items-center justify-center w-8 h-8 rounded-full shrink-0 text-white"
                      style={{ background: "var(--accent)" }}>
                      <Icon name={s.icon} size={14} />
                    </span>
                    <div className="flex-1 min-w-0 pb-1">
                      <div className="flex items-center gap-2">
                        <span className="text-[12.5px] font-semibold text-zinc-800">{s.label}</span>
                        <span className="ml-auto inline-flex items-center gap-1 text-[11px] font-semibold tabular-nums" style={{ color: confColor(conf) }}>
                          <span className="w-1.5 h-1.5 rounded-full" style={{ background: confColor(conf) }} />{conf}%
                        </span>
                      </div>
                      <p className="text-[12px] text-zinc-500 leading-snug mt-0.5">{stepText(s.key, run)}</p>
                      <div className="h-1 rounded-full bg-zinc-100 overflow-hidden mt-1.5">
                        <div className="h-full rounded-full" style={{ width: conf + "%", background: confColor(conf) }} />
                      </div>
                    </div>
                  </li>
                );
              })}
            </ol>

            {/* overall + decision */}
            <div className="mt-5 pt-4 border-t border-zinc-100 flex items-center gap-4 flex-wrap">
              <div className="flex items-center gap-3">
                <ConfRing value={run.conf} size={52} />
                <div>
                  <div className="text-[11px] text-zinc-400 uppercase tracking-wide font-medium">Overall confidence</div>
                  <div className="text-[13px] font-semibold"
                    style={{ color: AGENT_DECISION[run.conf >= threshold ? "auto" : run.conf >= 60 ? "review" : "human"].color }}>
                    {AGENT_DECISION[run.conf >= threshold ? "auto" : run.conf >= 60 ? "review" : "human"].label}
                  </div>
                  <div className="text-[11px] text-zinc-400 mt-0.5">
                    → Route to <span className="font-medium text-zinc-600">{run.target}</span>
                  </div>
                </div>
              </div>
              <div className="ml-auto flex items-center gap-2">
                {resolved[run.id] ? (
                  <span className="inline-flex items-center gap-1.5 text-[12.5px] font-medium text-emerald-600">
                    <Icon name="check" size={15} /> {resolved[run.id] === "auto" ? "Auto-resolved" : "Sent for human review"}
                  </span>
                ) : !canManage ? (
                  <span className="text-[12px] text-zinc-400 inline-flex items-center gap-1.5"><Icon name="eye" size={14} /> Read-only</span>
                ) : run.conf >= threshold ? (
                  <>
                    <Button variant="default" size="sm" icon="user" onClick={() => human(run)}>Send to human</Button>
                    <Button variant="primary" size="sm" icon="resolve" onClick={() => approve(run)}>Approve &amp; auto-resolve</Button>
                  </>
                ) : (
                  <>
                    <Button variant="default" size="sm" onClick={() => approve(run)}>Override &amp; resolve</Button>
                    <Button variant="primary" size="sm" icon="user" onClick={() => human(run)}>Route to {run.target}</Button>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function stepText(key, run) {
  const r = run.row;
  switch (key) {
    case "detect":    return `Classified as "${r.issue}" from order signals and customer messages.`;
    case "recommend": return r.action;
    case "draft":     return `Drafted a ${r.priority === "high" ? "apologetic" : "professional"} reply for ${r.customer.name.split(" ")[0]} via ${signalsFor(r.id).channelPref === "email" ? "email" : "WhatsApp"}.`;
    case "escalate":  return `Best escalation target: ${run.target}${r.waitH >= 48 ? " — SLA already breached." : "."}`;
    default:          return "";
  }
}

/* ---------- Manual trigger modal ---------- */
function TriggerModal({ wf, assignees, session, onClose, onToast }) {
  const [q, setQ] = useStateAU("");
  const [picked, setPicked] = useStateAU(null); // exception row
  const [busy, setBusy] = useStateAU(false);

  const filtered = EXCEPTIONS.filter(e =>
    !q || (e.id + e.customer.name + e.issue).toLowerCase().includes(q.toLowerCase())
  ).slice(0, 8);

  async function run() {
    if (!picked) return;
    setBusy(true);

    // resolve each "Assign to" action → look up profile UUID by name
    const tasks = [];
    for (const a of wf.actions) {
      if (a.icon === "user" && a.detail) {
        const { data: profile } = await sb.from("profiles").select("id").eq("name", a.detail).single();
        if (profile) {
          tasks.push({
            id: `auto-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,
            title: `[Auto] ${a.title} — ${picked.id}`,
            note: `Triggered by automation "${wf.name}". ${picked.issue}`,
            order_id: picked.id,
            priority: picked.priority,
            due: "Due in 24h",
            status: "todo",
            assigned_to: profile.id,
            assigned_by: session?.user?.id || null,
          });
        }
      }
    }

    if (tasks.length === 0) {
      // no "Assign to" actions configured — just toast
      onToast(`Automation triggered on ${picked.id}`, { icon: "zap", tone: "ok" });
      setBusy(false); onClose(); return;
    }

    const { error } = await sb.from("tasks").insert(tasks);
    setBusy(false);
    if (error) { onToast("Failed to create tasks: " + error.message, { tone: "danger", icon: "alert" }); return; }
    const names = [...new Set(tasks.map(t => wf.actions.find(a => a.icon === "user")?.detail).filter(Boolean))];
    onToast(`${tasks.length} task${tasks.length > 1 ? "s" : ""} assigned to ${names.join(", ")}`, { icon: "check", tone: "ok" });
    onClose();
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-900/40 backdrop-blur-[1px] animate-[toastin_0.15s_ease]" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl border border-zinc-200 w-full max-w-[480px] overflow-hidden" onClick={e => e.stopPropagation()}>
        {/* header */}
        <div className="flex items-start gap-3 px-5 pt-5 pb-4 border-b border-zinc-100">
          <div className="flex items-center justify-center w-9 h-9 rounded-lg shrink-0" style={{ background: "var(--accent-wash)", color: "var(--accent)" }}><Icon name="zap" size={18} /></div>
          <div className="flex-1 min-w-0">
            <h3 className="text-[15px] font-semibold text-zinc-900">Trigger automation</h3>
            <p className="text-[12.5px] text-zinc-500 mt-0.5 truncate">{wf.name}</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 -mr-1 -mt-1 flex items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-100"><Icon name="x" size={18} /></button>
        </div>

        <div className="p-5 space-y-4">
          {/* actions preview */}
          <div>
            <p className="text-[12px] font-medium text-zinc-500 mb-2">Actions that will run:</p>
            <div className="space-y-1.5">
              {wf.actions.map((a, i) => (
                <div key={i} className="flex items-center gap-2 px-3 py-2 rounded-lg bg-zinc-50 border border-zinc-100">
                  <Icon name={a.icon} size={13} className="text-zinc-400 shrink-0" />
                  <span className="text-[12.5px] text-zinc-700 flex-1">{a.title}</span>
                  {a.icon === "user" && (
                    <span className="text-[11.5px] font-medium px-2 py-0.5 rounded-md" style={{ background: "var(--accent-wash)", color: "var(--accent-ink)" }}>
                      → {a.detail || <span className="text-red-500">No assignee set</span>}
                    </span>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* exception picker */}
          <div>
            <p className="text-[12px] font-medium text-zinc-500 mb-2">Select exception to run on:</p>
            <div className="flex items-center gap-2 h-9 px-3 rounded-lg border border-zinc-300 focus-within:border-zinc-900 mb-2 bg-white">
              <Icon name="search" size={14} className="text-zinc-400" />
              <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search order ID or customer…"
                className="flex-1 bg-transparent outline-none text-[13px] text-zinc-700 placeholder:text-zinc-400" />
            </div>
            <div className="space-y-1 max-h-48 overflow-y-auto">
              {filtered.map(e => (
                <button key={e.id} onClick={() => setPicked(e)}
                  className={`w-full text-left flex items-center gap-3 px-3 py-2.5 rounded-lg border transition-all ${picked?.id === e.id ? "border-transparent ring-2" : "border-zinc-200 hover:bg-zinc-50"}`}
                  style={picked?.id === e.id ? { boxShadow: "0 0 0 2px var(--accent)", background: "var(--accent-wash)" } : undefined}>
                  <span className="font-mono text-[11.5px] text-zinc-500 shrink-0 w-20">{e.id}</span>
                  <div className="min-w-0 flex-1">
                    <div className="text-[12.5px] font-medium text-zinc-800 truncate">{e.customer.name}</div>
                    <div className="text-[11px] text-zinc-400 truncate">{e.issue}</div>
                  </div>
                  <PriorityBadge level={e.priority} />
                </button>
              ))}
              {filtered.length === 0 && <p className="text-[12.5px] text-zinc-400 px-3 py-2">No exceptions found.</p>}
            </div>
          </div>
        </div>

        <div className="flex items-center justify-end gap-2 px-5 py-3.5 border-t border-zinc-100 bg-zinc-50/50">
          <Button variant="default" size="md" onClick={onClose}>Cancel</Button>
          <Button variant="primary" size="md" icon={busy ? "refresh" : "zap"} disabled={!picked || busy} onClick={run}>
            {busy ? "Running…" : "Run automation"}
          </Button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Automations page shell (tabs) ---------- */
function AutomationsPage({ canManage, session, onToast, onOpenOrder }) {
  const [tab, setTab] = useStateAU("builder");
  return (
    <div className="p-6">
      <div className="flex items-start gap-3 mb-4 flex-wrap">
        <div>
          <h2 className="text-[15px] font-semibold text-zinc-900 tracking-tight">Automations</h2>
          <p className="text-[12.5px] text-zinc-500 mt-0.5">Rules that run themselves, and an AI agent that resolves what it can.</p>
        </div>
        <div className="ml-auto inline-flex items-center gap-0.5 p-0.5 rounded-lg bg-zinc-100 border border-zinc-200">
          {[["builder", "Workflow Builder", "gitbranch"], ["agent", "Auto-Resolution Agent", "cpu"]].map(([k, l, ic]) => {
            const on = tab === k;
            return (
              <button key={k} onClick={() => setTab(k)}
                className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[12.5px] font-medium transition-all ${on ? "bg-white text-zinc-800 shadow-sm" : "text-zinc-500 hover:text-zinc-700"}`}>
                <Icon name={ic} size={14} />{l}
              </button>
            );
          })}
        </div>
      </div>

      {tab === "builder"
        ? <WorkflowBuilder canManage={canManage} session={session} onToast={onToast} />
        : <ResolutionAgent canManage={canManage} onToast={onToast} onOpenOrder={onOpenOrder} />}
    </div>
  );
}

Object.assign(window, { AutomationsPage, WorkflowBuilder, ResolutionAgent, FlowNode });
