// Single-agent detail page — capabilities launchpad + composer

function RoleDetailPage({ roleId = "pm", onBack }) {
  const role = ROLES_SEED.find(r => r.id === roleId) || ROLES_SEED[0];
  const cfg = ROLE_CONFIG[roleId] || ROLE_CONFIG.pm;
  const [menuOpen, setMenuOpen] = useState(false);
  const [composer, setComposer] = useState("");
  const caps = cfg.capabilities || [];

  return (
    <div className="flex-1 min-w-0 flex flex-col bg-white overflow-hidden">
      <div className="flex-1 overflow-y-auto">
        {/* Header */}
        <RoleDetailHeader role={role} cfg={cfg} menuOpen={menuOpen} setMenuOpen={setMenuOpen} onBack={onBack} />

        {/* Capabilities */}
        <section className="border-t border-[#e8e3d8]">
          <div className="max-w-[920px] mx-auto px-8 pt-9 pb-10">
            <h2 className="text-[20px] font-medium tracking-tight text-[#0e0e10]">Capabilities</h2>
            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-3">
              {caps.map((c, i) => <CapabilityCard key={i} icon={c.icon} label={c.label} />)}
            </div>
          </div>
        </section>

        {/* Schedules */}
        <Section title="Schedules" subtitle="Recurring automated jobs." collapsible defaultOpen>
          <EventsList items={cfg.events} />
        </Section>

        {/* Recent conversations + runs */}
        <Section title="Activity" subtitle="What this agent has been doing." collapsible defaultOpen>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
            <ActivityColumn title="Recent conversations" icon="message" items={cfg.conversations} kind="chat" />
            <ActivityColumn title="Recent runs" icon="circle-dot" items={cfg.runs} kind="run" />
          </div>
        </Section>

        {/* Findings */}
        <Section title="Findings" subtitle="Insights surfaced by recent runs — jump into any to investigate.">
          <FindingsList items={cfg.findings} />
        </Section>

        <div className="h-8" />
      </div>

      {/* Chat composer */}
      <AgentComposer value={composer} setValue={setComposer} />
    </div>
  );
}

function CapabilityCard({ icon, label }) {
  return (
    <button
      className="group flex items-center gap-3.5 rounded-xl border border-[#ece7da] bg-white px-4 py-3.5 text-left hover:border-[var(--accent)] hover:shadow-[0_2px_14px_rgba(0,0,0,0.05)] transition-all">
      <span className="w-9 h-9 rounded-lg bg-[#f4f1ea] text-[#6b6b6b] flex items-center justify-center shrink-0 group-hover:text-[var(--accent)]">
        <Icon name={icon} size={16} />
      </span>
      <span className="flex-1 min-w-0 text-[13.5px] font-medium text-[#1a1a1a] leading-snug">{label}</span>
      <Icon name="chevron-right" size={15} className="text-[#c8c4b8] group-hover:text-[var(--accent)] shrink-0" />
    </button>
  );
}

function AgentComposer({ value, setValue }) {
  return (
    <div className="border-t border-[#e8e3d8] bg-white px-8 py-4">
      <div className="max-w-[920px] mx-auto">
        <div className="flex items-end gap-2 rounded-2xl border border-[#e0dccf] bg-[#faf8f3] pl-4 pr-2 py-2 focus-within:border-[var(--accent)] focus-within:bg-white transition-colors">
          <textarea
            rows={1}
            value={value}
            onChange={e => setValue(e.target.value)}
            placeholder="Start any conversation…"
            className="flex-1 resize-none bg-transparent text-[14px] text-[#1a1a1a] placeholder:text-[#9aa0a6] outline-none py-1.5 max-h-32 leading-relaxed" />
          <button
            title="Send"
            className="w-9 h-9 rounded-full bg-[var(--accent)] text-white flex items-center justify-center hover:brightness-110 shrink-0 disabled:opacity-40"
            disabled={!value.trim()}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 19V5M5 12l7-7 7 7" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function Section({ title, subtitle, children, collapsible = false, defaultOpen = true }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <section className="border-t border-[#e8e3d8]">
      <div className="max-w-[1180px] mx-auto px-8 pt-8 pb-2">
        <div className={`flex items-start ${collapsible ? "cursor-pointer select-none group" : ""}`}
          onClick={() => collapsible && setOpen(o => !o)}>
          {collapsible && (
            <div className="mr-2 mt-1.5 text-[#9aa0a6] group-hover:text-[#0e0e10]">
              <Icon name={open ? "chevron-down" : "chevron-right"} size={14} />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <h2 className="text-[20px] font-medium tracking-tight text-[#0e0e10]">{title}</h2>
            {subtitle && <p className="text-[12.5px] text-[#6b6b6b] mt-1">{subtitle}</p>}
          </div>
        </div>
      </div>
      {(!collapsible || open) && (
        <div className="max-w-[1180px] mx-auto px-8 pb-8">
          {children}
        </div>
      )}
    </section>
  );
}

function RoleDetailHeader({ role, cfg, menuOpen, setMenuOpen, onBack }) {
  return (
    <div className="bg-white">
      <div className="max-w-[1180px] mx-auto px-8 pt-6 pb-8">
        {/* Breadcrumb */}
        <button onClick={onBack} className="flex items-center gap-1 text-[12px] text-[#6b6b6b] hover:text-[#0e0e10] mb-4">
          <Icon name="chevron-left" size={12} />
          Agents
        </button>
        <div className="flex items-start gap-6">
          <RoleAvatar role={role} size={120} />
          <div className="flex-1 min-w-0 pt-2">
            <div className="text-[11px] font-semibold tracking-[0.08em] text-[#9aa0a6] uppercase mb-1.5">Agent</div>
            <h1 className="text-[32px] font-medium tracking-tight text-[#0e0e10] leading-tight">{role.title}</h1>
            <p className="text-[14px] text-[#3a3a3a] mt-3 max-w-[720px] leading-relaxed">{cfg.description}</p>
          </div>
          <div className="relative" onClick={e => e.stopPropagation()}>
            <button onClick={() => setMenuOpen(!menuOpen)}
              className="p-2 rounded-md text-[#6b6b6b] hover:bg-black/[0.06] hover:text-[#0e0e10] border border-[#ece7da]"
              title="Agent actions">
              <Icon name="more-v" size={16} />
            </button>
            {menuOpen && <RoleDetailMenu onClose={() => setMenuOpen(false)} />}
          </div>
        </div>
      </div>
    </div>
  );
}

function Pill({ icon, tint, children }) {
  return (
    <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md border border-[#ece7da] bg-white text-[11.5px] text-[#1a1a1a]">
      <Icon name={icon} size={11} style={{ color: tint }} />
      {children}
    </span>
  );
}

function RoleDetailMenu({ onClose }) {
  const items = [
    { id: "start-chat", label: "Start a chat", icon: "message", primary: true },
    { id: "edit-agent", label: "Edit agent", icon: "edit" },
    { id: "add-schedule", label: "Add scheduled job", icon: "clock" },
    { id: "add-event", label: "Add event", icon: "circle-dot" },
    { id: "sep" },
    { id: "rename", label: "Rename", icon: "edit-line" },
    { id: "avatar", label: "Change avatar", icon: "user" },
    { id: "duplicate", label: "Duplicate agent", icon: "copy" },
    { id: "delete", label: "Delete agent", icon: "trash", danger: true },
  ];
  return (
    <>
      <div className="fixed inset-0 z-20" onClick={onClose} />
      <div className="absolute right-0 top-full mt-1 w-[210px] bg-white rounded-lg border border-[#ece7da] shadow-xl z-30 py-1">
        {items.map(it => {
          if (it.id === "sep") return <div key="sep" className="my-1 h-px bg-[#ece7da]" />;
          return (
            <button key={it.id} onClick={onClose}
              className={`w-full flex items-center gap-2.5 px-3 py-1.5 text-[12.5px] text-left hover:bg-black/[0.04] ${it.danger ? "text-[#c2410c] hover:bg-[#fdecea] hover:text-[#a83228]" : it.primary ? "text-[var(--accent)] font-medium" : "text-[#1a1a1a]"}`}>
              <Icon name={it.icon} size={13} />
              {it.label}
            </button>
          );
        })}
      </div>
    </>
  );
}

// ---------- PROCESS FLOW ----------
function ProcessFlow({ steps, active, onSelect, scrollerRef, stepRefs }) {
  return (
    <div className="relative">
      <div ref={scrollerRef} className="overflow-x-auto scroll-smooth -mx-2 px-2">
        <div className="flex items-stretch gap-0 min-w-max py-2">
          {steps.map((s, i) => (
            <div key={s.id} className="flex items-stretch">
              <div ref={el => stepRefs.current[i] = el}>
                <ProcessStepCard step={s} idx={i + 1} active={i === active} onClick={() => onSelect(i)} />
              </div>
              {i < steps.length - 1 && <ProcessConnector />}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ProcessStepCard({ step, idx, active, onClick }) {
  return (
    <button onClick={onClick}
      className={`w-[240px] shrink-0 text-left rounded-xl border bg-white p-4 transition-all flex flex-col gap-2.5 ${active ? "border-[var(--accent)] shadow-[0_0_0_3px_rgba(31,61,246,0.12),0_4px_18px_rgba(0,0,0,0.05)]" : "border-[#ece7da] hover:border-[#cdcdcd]"}`}>
      <div className="flex items-center gap-2.5">
        <div className="w-11 h-11 rounded-lg flex items-center justify-center" style={{ background: `${step.accent}18`, color: step.accent }}>
          <ProcessIcon name={step.icon} />
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-[10px] font-semibold tracking-[0.08em] text-[#9aa0a6] uppercase">Step {idx}</div>
          <div className="text-[14px] font-semibold text-[#0e0e10] truncate">{step.title}</div>
        </div>
      </div>
      <p className="text-[12px] text-[#3a3a3a] leading-relaxed line-clamp-3">{step.desc}</p>
    </button>
  );
}

function ProcessConnector() {
  return (
    <div className="flex items-center self-stretch px-1">
      <svg width="28" height="20" viewBox="0 0 28 20" className="text-[#cbc6b8]" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
        <path d="M2 10h20" />
        <path d="M18 5l5 5-5 5" />
      </svg>
    </div>
  );
}

function ProcessIcon({ name }) {
  const sw = 1.6;
  const common = { width: 22, height: 22, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: sw, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "discover": return <svg {...common}><circle cx="11" cy="11" r="5"/><circle cx="11" cy="11" r="1.4" fill="currentColor"/><path d="M15 15l5 5"/></svg>;
    case "prioritize": return <svg {...common}><path d="M4 6h12M4 12h9M4 18h6"/><path d="M17 14l4 4-4 4"/></svg>;
    case "orchestrate": return <svg {...common}><circle cx="5" cy="6" r="2"/><circle cx="19" cy="6" r="2"/><circle cx="5" cy="18" r="2"/><circle cx="19" cy="18" r="2"/><path d="M7 6h10M5 8v8M19 8v8M7 18h10"/></svg>;
    case "measure": return <svg {...common}><path d="M4 20V4M4 20h16"/><rect x="7" y="13" width="3" height="5"/><rect x="12" y="9" width="3" height="9"/><rect x="17" y="5" width="3" height="13"/></svg>;
    case "align": return <svg {...common}><circle cx="7" cy="9" r="3"/><circle cx="17" cy="9" r="3"/><path d="M2 20c0-2.5 2-4.5 5-4.5s5 2 5 4.5M12 20c0-2.5 2-4.5 5-4.5s5 2 5 4.5"/></svg>;
    default: return null;
  }
}

function ProcessStepDetail({ step }) {
  return (
    <div className="mt-6 rounded-xl border border-[#ece7da] bg-[#faf8f3] p-5">
      <div className="flex items-center gap-2 mb-1">
        <div className="w-2 h-2 rounded-full" style={{ background: step.accent }} />
        <span className="text-[10.5px] font-semibold tracking-[0.08em] uppercase" style={{ color: step.accent }}>{step.title}</span>
      </div>
      <p className="text-[13px] text-[#3a3a3a] leading-relaxed max-w-[760px]">{step.desc}</p>

      <div className="mt-5 grid grid-cols-1 md:grid-cols-2 gap-2">
        {step.actions.map((a, i) => (
          <ActionCard key={`a-${i}`} icon={a.icon} accent={step.accent} content={a.label} parentStep={step}>{a.label}</ActionCard>
        ))}
        {step.entityActions.map((a, i) => (
          <ActionCard key={`e-${i}`} icon="wand" accent={step.accent} entity={a} content={a.label} parentStep={step}>{a.label}</ActionCard>
        ))}
      </div>
    </div>
  );
}

const ENTITY_PICKERS = {
  idea: ["TEK-201 · Inline reasoning preview", "TEK-204 · Cross-org search", "TEK-209 · Voice composer"],
  doneStory: ["TEK-123 · Agent cards in overview", "TEK-345 · New chat frontend", "TEK-411 · Sources expander", "TEK-388 · Multi-tenant roles"],
  story: ["TEK-388 · Multi-tenant roles", "TEK-411 · Sources expander", "TEK-204 · Cross-org search"],
  interview: ["Acme Corp · 2026-05-14", "ContosoBank · 2026-05-09", "Northwind · 2026-05-02"],
  epic: ["TEK-518 · Onboarding v3", "TEK-522 · Multi-tenant SSO", "TEK-530 · Reporting overhaul"],
  release: ["2026.5 · GA", "2026.6 · in flight", "2026.4 · GA"],
  team: ["Squad · Composer", "Squad · Retrieval", "Squad · Platform"],
  metric: ["Inline Comments adoption", "Time-to-first-message", "Free→Paid conversion"],
  theme: ["Onboarding", "Reporting", "Enterprise readiness"],
  sprint: ["Sprint 42 · in flight", "Sprint 41 · closed", "Sprint 43 · planned"],
  ticket: ["TKT-9120 · Acme · composer paste", "TKT-9105 · Contoso · widget resize", "TKT-9077 · Northwind · export"],
  customer: ["Acme Corp", "ContosoBank", "Northwind", "Initech"],
  account: ["Acme Corp · enterprise", "ContosoBank · enterprise", "Northwind · mid-market"],
  component: ["Composer", "Retrieval", "Widget Panel", "Auth"],
  persona: ["ICP-1 · Power admin", "ICP-2 · Casual creator", "ICP-3 · Buyer"],
  channel: ["Email · top accounts", "Blog · product", "LinkedIn · brand", "Docs · changelog"],
  asset: ["Launch blog draft", "Sales deck Q2", "One-pager · Inline Reasoning"],
  process: ["Onboarding v3", "Quote-to-cash", "Incident response"],
  requirement: ["REQ-118 · Audit log retention", "REQ-127 · SSO mapping", "REQ-130 · Export limits"],
  page: ["Confluence · Onboarding v3", "Confluence · Architecture · Composer", "Confluence · API · Export"],
};

function ActionCard({ icon, accent, children, entity, skill, content, parentStep }) {
  const [open, setOpen] = useState(false);
  const [pick, setPick] = useState(null);
  const opts = entity ? (ENTITY_PICKERS[entity.picker] || []) : [];
  const launch = (e) => {
    e?.stopPropagation?.();
    const payload = {
      content: content || (typeof children === "string" ? children : null),
      story: pick || null,
      skill: skill || (parentStep ? parentStep.title : null),
    };
    // In a real app this would route to the chat with these params.
    window.dispatchEvent(new CustomEvent("teklens:launch-chat", { detail: payload }));
    console.log("Launch chat with:", payload);
  };
  return (
    <div className="group rounded-lg border border-[#ece7da] bg-white hover:border-[var(--accent)] hover:bg-[#fafaff]">
      <button onClick={launch} className="w-full flex items-center gap-2.5 px-3 py-2 text-left">
        <div className="w-7 h-7 rounded-md flex items-center justify-center shrink-0" style={{ background: `${accent}18`, color: accent }}>
          <Icon name={icon} size={13} />
        </div>
        <div className="flex-1 min-w-0 flex items-center gap-1.5 flex-wrap text-[12.5px] text-[#0e0e10]">
          <span>{children}</span>
          {entity && (
            <span className="relative inline-flex" onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}>
              <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md border border-[#cbcbcb] bg-[#faf8f3] text-[12px] text-[#3a3a3a] hover:border-[var(--accent)] cursor-pointer">
                {pick || entity.placeholder}
                <Icon name="chevron-down" size={11} className="text-[#9aa0a6]" />
              </span>
              {open && (
                <>
                  <div className="fixed inset-0 z-20" onClick={(e) => { e.stopPropagation(); setOpen(false); }} />
                  <div className="absolute left-0 top-full mt-1 w-[260px] bg-white rounded-lg border border-[#ece7da] shadow-xl z-30 py-1">
                    {opts.map(o => (
                      <button key={o} onClick={(e) => { e.stopPropagation(); setPick(o); setOpen(false); }}
                        className="w-full text-left px-3 py-1.5 text-[12px] hover:bg-black/[0.04]">{o}</button>
                    ))}
                  </div>
                </>
              )}
            </span>
          )}
        </div>
        <Icon name="chevron-right" size={13} className="text-[#9aa0a6] group-hover:text-[var(--accent)]" />
      </button>
    </div>
  );
}

// ---------- EVENTS ----------
function EventsList({ items }) {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
      {items.map(it => (
        <div key={it.id} className="rounded-xl border border-[#ece7da] bg-white p-4">
          <div className="flex items-center gap-2 mb-1.5">
            <Icon name={it.icon} size={13} style={{ color: it.color }} />
            <span className="text-[10.5px] font-semibold tracking-[0.06em] uppercase" style={{ color: it.color }}>{it.kind === "event" ? "Event" : "Schedule"}</span>
            <div className="flex-1" />
            <button className="p-1 rounded hover:bg-black/[0.05] text-[#9aa0a6]"><Icon name="more-v" size={13} /></button>
          </div>
          <div className="text-[13.5px] font-semibold text-[#0e0e10]">{it.title}</div>
          <p className="text-[12px] text-[#3a3a3a] mt-1 leading-relaxed">{it.desc}</p>
          <div className="text-[11px] text-[#9aa0a6] mt-2">Last run · {it.lastRun}</div>
        </div>
      ))}
      <button className="rounded-xl border border-dashed border-[#d4cdba] bg-[#faf8f3] hover:bg-white hover:border-[var(--accent)] hover:text-[var(--accent)] text-[#6b6b6b] p-4 flex items-center justify-center gap-2 text-[12.5px]">
        <Icon name="plus" size={14} /> Add schedule
      </button>
    </div>
  );
}

// ---------- ACTIVITY ----------
function ActivityColumn({ title, icon, items, kind }) {
  return (
    <div className="rounded-xl border border-[#ece7da] bg-white">
      <div className="flex items-center gap-2 px-4 py-2.5 border-b border-[#ece7da]">
        <Icon name={icon} size={13} className="text-[#6b6b6b]" />
        <div className="text-[12.5px] font-semibold text-[#0e0e10]">{title}</div>
        <div className="flex-1" />
        <span className="text-[11px] text-[#9aa0a6]">{items.length}</span>
      </div>
      <div>
        {items.map((it, i) => (
          <button key={it.id} className={`w-full flex items-start gap-3 px-4 py-3 text-left hover:bg-[#faf7f0] ${i < items.length - 1 ? "border-b border-[#f0ebdd]" : ""}`}>
            {kind === "run" ? (
              <span className={`mt-1 w-1.5 h-1.5 rounded-full shrink-0 ${it.status === "attention" ? "bg-[#d97706]" : "bg-[#1f8a5b]"}`} />
            ) : (
              <Icon name="message" size={13} className="text-[#9aa0a6] mt-0.5 shrink-0" />
            )}
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-1.5">
                {kind === "run" && (
                  <span className="text-[9.5px] font-semibold tracking-wider uppercase px-1.5 py-[1px] rounded bg-[#f4f1ea] text-[#6b6b6b]">{it.trigger}</span>
                )}
                <div className="text-[13px] font-medium text-[#0e0e10] truncate">{it.title}</div>
              </div>
              <div className="text-[11.5px] text-[#6b6b6b] mt-0.5 truncate">{it.subtitle}</div>
            </div>
            <div className="text-[11px] text-[#9aa0a6] shrink-0">{it.time}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ---------- FINDINGS ----------
function FindingsList({ items }) {
  return (
    <div className="flex flex-col gap-3">
      {items.map(f => <FindingCard key={f.id} f={f} />)}
    </div>
  );
}

function FindingCard({ f }) {
  const sev = {
    high: { bg: "#fdecea", color: "#a83228", label: "High" },
    medium: { bg: "#fef0d9", color: "#a05a00", label: "Medium" },
    low: { bg: "#e8f6ec", color: "#1f7a3a", label: "Low" },
  }[f.severity];
  return (
    <div className="rounded-xl border border-[#ece7da] bg-white p-4 hover:border-[var(--accent)]/40 hover:shadow-[0_4px_18px_rgba(0,0,0,0.04)] transition-all">
      <div className="flex items-start gap-3">
        <div className="px-2 py-[1px] rounded-full text-[10.5px] font-medium shrink-0 mt-0.5" style={{ background: sev.bg, color: sev.color }}>{sev.label}</div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1.5 text-[11px] text-[#6b6b6b]">
            <Icon name="circle-dot" size={11} className="text-[#9aa0a6]" />
            <span>{f.source}</span>
            <span className="text-[#cbcbcb]">·</span>
            <span>{f.time}</span>
          </div>
          <div className="text-[14px] font-semibold text-[#0e0e10] mt-1 leading-snug">{f.title}</div>
          <p className="text-[12.5px] text-[#3a3a3a] mt-1.5 leading-relaxed">{f.body}</p>
          <div className="mt-3 flex items-center gap-1.5 flex-wrap">
            {f.actions.map((a, i) => (
              <button key={i}
                className={`px-2.5 py-1 rounded-md text-[12px] ${a.primary ? "bg-[var(--accent)] text-white hover:brightness-110" : "border border-[#ece7da] text-[#1a1a1a] hover:border-[#cdcdcd]"}`}>
                {a.label}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
