// Teklens.AI — Initiatives extension (data + WorkflowStrip + InitiativesBoard)
// Reuses the global `Icon`, fonts and palette from app.jsx. Pure add-on: changes nothing in v1.

// ---------- MODEL ----------
const INIT_METHODOLOGY = "BMAD";
const INIT_STEPS = [
  { id: "discovery",    name: "Discovery",     short: "Discovery",    role: "Business Analyst", layer: "definition" },
  { id: "prd",          name: "PRD",           short: "PRD",          role: "PM",               layer: "definition" },
  { id: "architecture", name: "Architecture",  short: "Architecture", role: "Architect",        layer: "definition" },
  { id: "planning",     name: "Planning",      short: "Planning",     role: "Product Owner",    layer: "definition" },
  { id: "delivery",     name: "Delivery",      short: "Delivery",     role: "Tech Lead",        layer: "runtime" },
  { id: "gtm",          name: "GTM & Support", short: "GTM",          role: "PMM",              layer: "runtime" },
];
const initStepIndex = (id) => INIT_STEPS.findIndex((s) => s.id === id);

const INIT_STATUS = {
  completed: { color: "#16A34A", label: "Completed" },
  active:    { color: "var(--accent)", label: "Active" },
  gated:     { color: "#D97706", label: "Awaiting decision" },
  pending:   { color: "#98A2B3", label: "Pending" },
  skipped:   { color: "#C0C4CC", label: "Not applicable" },
};
const INIT_LIFECYCLE = {
  Draft:       { dot: "#98A2B3", bg: "#f1f1ee", text: "#5a5a5a", border: "#e2ddd0" },
  "In-Review": { dot: "#D97706", bg: "#fdf3e3", text: "#9a6516", border: "#f2dfbe" },
  Promoted:    { dot: "#16A34A", bg: "#e9f6ed", text: "#15803d", border: "#cdead5" },
  Archived:    { dot: "#C0C4CC", bg: "#f4f4f2", text: "#9aa0a6", border: "#e6e2d6" },
};
const INIT_SYSTEM = {
  confluence: { icon: "confluence", color: "#1c4f9c", label: "Confluence" },
  jira:       { icon: "jira", color: "#2563eb", label: "Jira" },
  git:        { icon: "repo", color: "#0e0e10", label: "Git" },
  teklens:    { icon: "sparkles", color: "#8b5cf6", label: "Teklens" },
};
const INIT_LAYER_COLOR = { definition: "#3b5cf6", runtime: "#16A34A", knowledge: "#d97706", binding: "#8b5cf6" };

const INITIATIVES = [
  {
    id: "usr", name: "Unified Search Revamp", owner: { initials: "SS", tint: "#b6892e" }, active: "planning",
    cells: {
      discovery:    { collaterals: [{ type: "Discovery brief", lifecycle: "Promoted", system: "confluence" }, { type: "Opportunity canvas", lifecycle: "Promoted", system: "confluence" }] },
      prd:          { collaterals: [{ type: "PRD", lifecycle: "Promoted", system: "confluence" }] },
      architecture: { collaterals: [{ type: "ADR", lifecycle: "Promoted", system: "confluence" }, { type: "System diagram", lifecycle: "Promoted", system: "git" }] },
      planning:     { collaterals: [{ type: "Epic set", lifecycle: "In-Review", system: "jira" }, { type: "Story map", lifecycle: "Draft", system: "teklens" }] },
      delivery:     { collaterals: [] },
      gtm:          { collaterals: [] },
    },
  },
  {
    id: "billing", name: "Billing 2.0", owner: { initials: "MC", tint: "#3b5cf6" }, active: "prd",
    cells: {
      discovery:    { collaterals: [{ type: "Discovery brief", lifecycle: "Promoted", system: "confluence" }] },
      prd:          { gated: true, collaterals: [{ type: "PRD", lifecycle: "In-Review", system: "confluence" }] },
      architecture: { collaterals: [] }, planning: { collaterals: [] }, delivery: { collaterals: [] }, gtm: { collaterals: [] },
    },
  },
  {
    id: "offline", name: "Mobile Offline Mode", owner: { initials: "TB", tint: "#0e7c66" }, active: "architecture",
    cells: {
      discovery:    { collaterals: [{ type: "Discovery brief", lifecycle: "Promoted", system: "confluence" }] },
      prd:          { collaterals: [{ type: "PRD", lifecycle: "Promoted", system: "confluence" }] },
      architecture: { collaterals: [{ type: "Arch RFC", lifecycle: "Draft", system: "teklens" }, { type: "Sync model spec", lifecycle: "In-Review", system: "confluence" }] },
      planning:     { collaterals: [] }, delivery: { collaterals: [] }, gtm: { collaterals: [] },
    },
  },
  {
    id: "sso", name: "SSO Rollout", owner: { initials: "LH", tint: "#c2410c" }, active: "delivery",
    cells: {
      discovery:    { collaterals: [{ type: "Discovery brief", lifecycle: "Promoted", system: "confluence" }] },
      prd:          { collaterals: [{ type: "PRD", lifecycle: "Promoted", system: "confluence" }] },
      architecture: { skipped: true, collaterals: [] },
      planning:     { collaterals: [{ type: "Epic set", lifecycle: "Promoted", system: "jira" }] },
      delivery:     { collaterals: [{ type: "Release plan", lifecycle: "In-Review", system: "jira" }, { type: "Runbook", lifecycle: "Draft", system: "teklens" }, { type: "Deploy checklist", lifecycle: "Promoted", system: "confluence", broken: true }] },
      gtm:          { collaterals: [] },
    },
  },
  {
    id: "onboarding", name: "Onboarding Redesign", owner: { initials: "MC", tint: "#3b5cf6" }, active: "discovery",
    cells: {
      discovery:    { collaterals: [{ type: "Discovery brief", lifecycle: "Draft", system: "teklens" }] },
      prd:          { collaterals: [] }, architecture: { collaterals: [] }, planning: { collaterals: [] }, delivery: { collaterals: [] }, gtm: { collaterals: [] },
    },
  },
];
const initById = (id) => INITIATIVES.find((i) => i.id === id) || INITIATIVES[0];

function initCellStatus(initiative, stepId) {
  const cell = initiative.cells[stepId] || {};
  if (cell.skipped) return "skipped";
  const ai = initStepIndex(initiative.active), si = initStepIndex(stepId);
  if (si < ai) return "completed";
  if (si === ai) return cell.gated ? "gated" : "active";
  return "pending";
}
const INIT_LAST_ACTIVITY = {
  "usr.planning": "2h ago · Simon", "billing.prd": "yesterday · Maya", "offline.architecture": "4h ago · Tomas",
  "sso.delivery": "1h ago · Lena", "onboarding.discovery": "30m ago · Maya",
};

// ---------- ATOMS ----------
function InitAvatar({ owner, size = 24 }) {
  return (
    <span className="inline-flex items-center justify-center rounded-full text-white font-medium shrink-0"
      style={{ width: size, height: size, background: owner.tint, fontSize: size * 0.4 }}>{owner.initials}</span>
  );
}
function InitDot({ status, size = 8, pulse = false }) {
  return <span className={`inline-block rounded-full shrink-0 ${pulse ? "init-pulse" : ""}`} style={{ width: size, height: size, background: INIT_STATUS[status]?.color || "#98A2B3" }} />;
}
function InitLifecycle({ lifecycle, sm = false }) {
  const l = INIT_LIFECYCLE[lifecycle] || INIT_LIFECYCLE.Draft;
  return (
    <span className="inline-flex items-center gap-1 rounded-full border font-medium"
      style={{ background: l.bg, borderColor: l.border, color: l.text, fontSize: sm ? 10 : 11, padding: sm ? "1px 6px 1px 5px" : "2px 8px 2px 6px" }}>
      <span className="rounded-full" style={{ width: sm ? 5 : 6, height: sm ? 5 : 6, background: l.dot }} />{lifecycle}
    </span>
  );
}
function InitSystemGlyph({ system, size = 13 }) {
  const s = INIT_SYSTEM[system];
  return s ? <Icon name={s.icon} size={size} className="" /> : null;
}
function InitCollateralChip({ c, onClick }) {
  const s = INIT_SYSTEM[c.system];
  const promoted = c.lifecycle === "Promoted";
  const l = INIT_LIFECYCLE[c.lifecycle] || INIT_LIFECYCLE.Draft;
  return (
    <button onClick={onClick}
      className="group/chip w-full flex items-center gap-1.5 pl-1.5 pr-1.5 py-1 rounded-md border bg-white hover:bg-[#faf8f3] transition-colors text-left"
      style={{ borderColor: "#ece7da" }} title={`${c.type} · ${c.lifecycle}${promoted ? " · opens in " + s.label : ""}`}>
      <span className="rounded-full shrink-0" style={{ width: 6, height: 6, background: l.dot }} />
      <span className="text-[12px] text-[#0e0e10] truncate flex-1 leading-none">{c.type}</span>
      {c.broken ? (
        <span className="inline-flex items-center text-[#c2410c]" title="Link broken — re-authorise"><Icon name="link" size={12} /></span>
      ) : (
        <span className="inline-flex items-center shrink-0" style={{ color: s.color }} title={promoted ? `Open in ${s.label}` : s.label}>
          <Icon name={s.icon} size={12} />
          {promoted && <Icon name="external" size={9} className="ml-0.5 text-[#9aa0a6] opacity-0 group-hover/chip:opacity-100 transition-opacity" />}
        </span>
      )}
    </button>
  );
}

// ---------- SCREEN A — WORKFLOW STRIP (chat header) ----------
function WorkflowStrip({ pinned, onGoStep, onOpenBoard, onSwitchInitiative, onUnpin }) {
  const initiative = initById(pinned.initiativeId);
  const currentStep = pinned.stepId || initiative.active;
  const [menuOpen, setMenuOpen] = useState(false);
  const scrollRef = useRef(null);
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const active = el.querySelector("[data-active-node]");
    if (active) {
      const elRect = el.getBoundingClientRect();
      const aRect = active.getBoundingClientRect();
      const target = el.scrollLeft + (aRect.left - elRect.left) - el.clientWidth / 2 + aRect.width / 2;
      el.scrollTo({ left: Math.max(0, target), behavior: "auto" });
    }
  }, [currentStep, initiative.id]);
  return (
    <div className="shrink-0 border-b border-[#e8e3d8] bg-white">
      <div className="w-full flex items-center gap-4 px-5" style={{ minHeight: 56 }}>
        {/* LEFT — initiative dropdown */}
        <div className="relative shrink-0">
          <button onClick={() => setMenuOpen((o) => !o)}
            className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md border border-[#ece7da] bg-white hover:bg-[#faf8f3] max-w-[260px]">
            <Icon name="pin" size={13} className="text-[var(--accent)]" />
            <span className="text-[10px] uppercase tracking-[0.07em] text-[#9aa0a6] font-semibold">Initiative</span>
            <span className="text-[13px] font-semibold text-[#0e0e10] truncate">{initiative.name}</span>
            <Icon name="chevron-down" size={13} className="text-[#9aa0a6]" />
          </button>
          {menuOpen && (
            <>
              <div className="fixed inset-0 z-30" onClick={() => setMenuOpen(false)} />
              <div className="absolute left-0 top-full mt-1.5 w-[280px] bg-white rounded-xl border border-[#ece7da] shadow-2xl z-40 overflow-hidden">
                <div className="px-3 py-2 border-b border-[#f0ebdd] text-[10.5px] uppercase tracking-[0.06em] text-[#9aa0a6] font-semibold">Switch initiative</div>
                <div className="py-1 max-h-[260px] overflow-y-auto">
                  {INITIATIVES.map((it) => (
                    <button key={it.id} onClick={() => { onSwitchInitiative(it.id); setMenuOpen(false); }}
                      className={`w-full flex items-center gap-2.5 px-3 py-2 text-left hover:bg-[#faf7f0] ${it.id === initiative.id ? "bg-[#faf7f0]" : ""}`}>
                      <InitAvatar owner={it.owner} size={22} />
                      <div className="flex-1 min-w-0">
                        <div className="text-[12.5px] font-medium text-[#0e0e10] truncate">{it.name}</div>
                        <div className="text-[11px] text-[#9aa0a6] truncate flex items-center gap-1"><InitDot status={initCellStatus(it, it.active)} size={6} /> {INIT_STEPS[initStepIndex(it.active)].name}</div>
                      </div>
                      {it.id === initiative.id && <Icon name="check" size={14} className="text-[var(--accent)]" />}
                    </button>
                  ))}
                </div>
                <div className="border-t border-[#f0ebdd] p-1">
                  <button onClick={() => { onUnpin(); setMenuOpen(false); }} className="w-full flex items-center gap-2 px-2.5 py-1.5 rounded-md text-[12px] text-[#6b6b6b] hover:bg-black/[0.04] hover:text-[#0e0e10]">
                    <Icon name="x" size={12} /> Unpin — return chat to unscoped
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
        {/* CENTER — stepper (compact: dots + only active labelled, always fits) */}
        <div ref={scrollRef} className="flex items-center flex-1 min-w-0 overflow-x-auto overflow-y-hidden justify-center init-strip-scroll">
          <div className="flex items-center py-1 px-1">
            {INIT_STEPS.map((step, i) => (
              <div key={step.id} className="flex items-center" {...(step.id === currentStep ? { "data-active-node": "" } : {})}>
                <StripNode initiative={initiative} step={step} isCurrent={step.id === currentStep} onGo={onGoStep} compact />
                {i < INIT_STEPS.length - 1 && (
                  <span className="shrink-0" style={{ width: 14, height: 2, background: initCellStatus(initiative, step.id) === "completed" ? "#16A34A" : "#e2ddd0" }} />
                )}
              </div>
            ))}
          </div>
        </div>
        {/* RIGHT — open workspace (board) */}
        <button onClick={onOpenBoard} className="shrink-0 flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-[12.5px] text-[#5a5a5a] hover:text-[var(--accent)] hover:bg-[var(--accent)]/[0.06]">
          Open board <Icon name="external" size={13} />
        </button>
      </div>
    </div>
  );
}

function StripNode({ initiative, step, isCurrent, onGo, compact = false }) {
  const status = initCellStatus(initiative, step.id);
  const count = (initiative.cells[step.id]?.collaterals || []).length;
  const color = INIT_STATUS[status].color;
  const interactive = status !== "skipped";
  const [hover, setHover] = useState(false);
  let inner;
  if (status === "completed") inner = <span className="flex items-center justify-center rounded-full text-white" style={{ width: 22, height: 22, background: color }}><Icon name="check" size={13} stroke={2.4} /></span>;
  else if (status === "active" || status === "gated") inner = <span className={`flex items-center justify-center rounded-full text-white ${isCurrent ? "ring-[3px] ring-[var(--accent)]/20" : ""} ${status === "gated" ? "init-pulse" : ""}`} style={{ width: 22, height: 22, background: color }}><span className="rounded-full bg-white" style={{ width: 7, height: 7 }} /></span>;
  else if (status === "skipped") inner = <span className="rounded-full init-hatch" style={{ width: 22, height: 22, border: "1.5px dashed #c0c4cc" }} />;
  else inner = <span className="rounded-full bg-white" style={{ width: 22, height: 22, border: "2px solid #d6dae0" }} />;
  return (
    <div className={`relative flex items-center ${compact ? "" : "flex-col"}`} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      <button onClick={() => interactive && onGo(step.id)} disabled={!interactive} className={`relative flex items-center justify-center ${interactive ? "cursor-pointer" : "cursor-not-allowed"}`}>
        {inner}
        {count > 0 && <span className="absolute -top-1 -right-1.5 min-w-[14px] h-[14px] px-[3px] rounded-full bg-white border border-[#e8e3d8] text-[9.5px] font-semibold text-[#5a5a5a] flex items-center justify-center tabular-nums">{count}</span>}
      </button>
      {compact ? (
        isCurrent && <span className="ml-1.5 mr-0.5 text-[12px] font-semibold text-[#0e0e10] whitespace-nowrap">{step.name}</span>
      ) : (
        <span className={`mt-1.5 text-[11px] leading-none whitespace-nowrap ${isCurrent ? "font-semibold text-[#0e0e10]" : "text-[#6b6b6b]"}`}>{step.short}</span>
      )}
      {hover && (
        <div className="absolute top-full mt-2 left-1/2 -translate-x-1/2 z-40 w-[220px] bg-white rounded-lg border border-[#ece7da] shadow-xl p-3 text-left">
          <div className="flex items-center gap-2"><InitDot status={status} size={9} /><span className="text-[13px] font-semibold text-[#0e0e10]">{step.name}</span></div>
          <div className="mt-1 text-[11.5px] font-medium" style={{ color: color === "var(--accent)" ? "var(--accent)" : color }}>{INIT_STATUS[status].label}</div>
          <div className="mt-2.5 flex flex-col gap-1.5 text-[12px]">
            <div className="flex items-center gap-2 text-[#5a5a5a]"><Icon name="user" size={12} className="text-[#9aa0a6]" /><span>Accountable</span><span className="ml-auto font-medium text-[#0e0e10]">{step.role}</span></div>
            <div className="flex items-center gap-2 text-[#5a5a5a]"><Icon name="file" size={12} className="text-[#9aa0a6]" /><span>Collateral</span><span className="ml-auto font-medium text-[#0e0e10] tabular-nums">{count}</span></div>
          </div>
          {interactive && <button onClick={() => onGo(step.id)} className="mt-2.5 w-full flex items-center justify-center gap-1.5 py-1.5 rounded-md bg-[var(--accent)] text-white text-[12px] font-medium hover:brightness-110">Go to step <Icon name="chevron-right" size={12} /></button>}
        </div>
      )}
    </div>
  );
}

// ---------- SCREEN B — INITIATIVES BOARD ----------
function InitiativesBoard({ onOpenStep }) {
  const [hoverCell, setHoverCell] = useState(null);
  const [search, setSearch] = useState("");
  const visible = INITIATIVES.filter((it) => it.name.toLowerCase().includes(search.toLowerCase()));
  return (
    <div className="flex-1 min-w-0 flex flex-col bg-white">
      {/* top bar */}
      <div className="shrink-0 border-b border-[#e8e3d8] px-6 py-3 flex items-center gap-3">
        <h1 className="text-[18px] font-semibold text-[#0e0e10]">Initiatives</h1>
        <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md border border-[#ece7da] bg-white text-[12px] text-[#3a3a3a]">
          <Icon name="grid" size={12} className="text-[var(--accent)]" /><span className="font-medium text-[#0e0e10]">{INIT_METHODOLOGY}</span><span className="text-[#9aa0a6]">methodology</span>
        </span>
        <div className="flex-1" />
        <div className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md border border-[#ece7da] bg-white text-[12.5px] text-[#6b6b6b] w-[200px] focus-within:border-[var(--accent)]">
          <Icon name="search" size={13} />
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search initiatives…" className="bg-transparent outline-none flex-1 text-[#0e0e10] placeholder:text-[#9aa0a6]" />
        </div>
        <InitFilter label="Status" options={["All statuses", "Active", "Awaiting decision", "Completed"]} />
        <InitFilter label="Role" options={["All roles", ...INIT_STEPS.map((s) => s.role)]} />
        <InitFilter label="Lifecycle" options={["All lifecycles", "Draft", "In-Review", "Promoted"]} />
        <button className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-[var(--accent)] text-white text-[13px] font-medium hover:brightness-110 shadow-[0_1px_0_rgba(0,0,0,0.08)]"><Icon name="plus" size={15} /> New initiative</button>
      </div>
      {/* matrix */}
      <div className="flex-1 overflow-auto">
        <table className="border-collapse" style={{ minWidth: 1100 }}>
          <thead>
            <tr>
              <th className="sticky left-0 top-0 z-30 bg-[#faf8f3] border-b border-r border-[#e8e3d8] text-left align-bottom px-4 py-3" style={{ width: 248, minWidth: 248 }}>
                <span className="text-[11px] uppercase tracking-[0.06em] text-[#9aa0a6] font-semibold">Initiative</span>
              </th>
              {INIT_STEPS.map((s) => (
                <th key={s.id} className="sticky top-0 z-20 bg-[#faf8f3] border-b border-r border-[#e8e3d8] text-left align-bottom px-3 pt-3 pb-0" style={{ width: 200, minWidth: 200 }}>
                  <div className="text-[12.5px] font-semibold text-[#0e0e10]">{s.name}</div>
                  <div className="text-[11px] text-[#9aa0a6] mt-0.5">{s.role}</div>
                  <div className="mt-2 h-[3px] rounded-full" style={{ background: INIT_LAYER_COLOR[s.layer], opacity: 0.85 }} />
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {visible.map((it) => (
              <tr key={it.id} className="group/row">
                <td className="sticky left-0 z-10 bg-white border-b border-r border-[#e8e3d8] px-4 py-3 align-top group-hover/row:bg-[#fcfbf8]" style={{ width: 248, minWidth: 248 }}>
                  <button onClick={() => onOpenStep(it.id, it.active)} className="w-full text-left">
                    <div className="flex items-start gap-2.5">
                      <InitAvatar owner={it.owner} size={28} />
                      <div className="flex-1 min-w-0">
                        <div className="text-[13.5px] font-semibold text-[#0e0e10] leading-tight">{it.name}</div>
                        <div className="mt-1 inline-flex items-center gap-1.5 text-[11px]"><InitDot status={initCellStatus(it, it.active)} size={6} pulse={initCellStatus(it, it.active) === "gated"} /><span className="text-[#6b6b6b]">{INIT_STEPS[initStepIndex(it.active)].name}</span></div>
                      </div>
                      <Icon name="chevron-right" size={15} className="text-[#cbcbcb] opacity-0 group-hover/row:opacity-100 transition-opacity mt-0.5" />
                    </div>
                  </button>
                </td>
                {INIT_STEPS.map((s) => {
                  const key = `${it.id}.${s.id}`;
                  const status = initCellStatus(it, s.id);
                  const cell = it.cells[s.id] || {};
                  const cols = cell.collaterals || [];
                  const isCurrent = it.active === s.id;
                  return (
                    <td key={s.id} onMouseEnter={() => setHoverCell(key)} onMouseLeave={() => setHoverCell((k) => (k === key ? null : k))}
                      className="relative border-b border-r border-[#f0ebdd] align-top p-0 group-hover/row:bg-[#fdfcfa]" style={{ width: 200, minWidth: 200 }}>
                      <div className="relative px-2.5 py-2.5 h-full min-h-[72px]" style={isCurrent ? { boxShadow: "inset 3px 0 0 var(--accent)" } : undefined}>
                        {status === "skipped" ? (
                          <div className="init-hatch rounded-md h-full min-h-[52px] flex items-center justify-center text-[11px] text-[#9aa0a6] border border-dashed border-[#d6dae0]">Not applicable</div>
                        ) : cols.length === 0 ? (
                          <button onClick={() => onOpenStep(it.id, s.id)} className="w-full h-full min-h-[52px] rounded-md border border-dashed border-[#ddd8c9] text-[11.5px] text-[#9aa0a6] hover:border-[var(--accent)]/50 hover:text-[var(--accent)] hover:bg-[var(--accent)]/[0.04] flex items-center justify-center gap-1 transition-colors"><Icon name="plus" size={13} /> Start working</button>
                        ) : (
                          <div className="flex flex-col gap-1.5">
                            {cell.gated && <div className="flex items-center gap-1 text-[10.5px] font-medium text-[#9a6516]"><InitDot status="gated" size={6} pulse /> Awaiting decision</div>}
                            {cols.map((c, i) => <InitCollateralChip key={i} c={c} onClick={() => onOpenStep(it.id, s.id)} />)}
                          </div>
                        )}
                      </div>
                      {hoverCell === key && status !== "skipped" && cols.length > 0 && (
                        <div className="absolute z-40 top-2 left-full ml-1 w-[252px] bg-white rounded-xl border border-[#ece7da] shadow-2xl p-3 text-left">
                          <div className="flex items-center gap-2"><InitDot status={status} size={9} pulse={status === "gated"} /><span className="text-[12.5px] font-semibold text-[#0e0e10]">{s.name}</span><span className="ml-auto text-[11px] font-medium" style={{ color: INIT_STATUS[status].color === "var(--accent)" ? "var(--accent)" : INIT_STATUS[status].color }}>{INIT_STATUS[status].label}</span></div>
                          <div className="mt-2 flex items-center gap-2 text-[11.5px] text-[#5a5a5a]"><Icon name="user" size={12} className="text-[#9aa0a6]" /><span>{s.role}</span><span className="text-[#cbcbcb]">·</span><Icon name="info" size={12} className="text-[#9aa0a6]" /><span>{INIT_LAST_ACTIVITY[key] || "—"}</span></div>
                          <div className="mt-2.5 text-[10.5px] uppercase tracking-[0.06em] text-[#9aa0a6] font-semibold">Collaterals</div>
                          <div className="mt-1.5 flex flex-col gap-1">
                            {cols.map((c, i) => (<div key={i} className="flex items-center gap-2 text-[12px]" style={{ color: INIT_SYSTEM[c.system].color }}><Icon name={INIT_SYSTEM[c.system].icon} size={13} /><span className="text-[#0e0e10] truncate flex-1">{c.type}</span><InitLifecycle lifecycle={c.lifecycle} sm /></div>))}
                          </div>
                          <button onClick={() => onOpenStep(it.id, s.id)} className="mt-3 w-full flex items-center justify-center gap-1.5 py-1.5 rounded-md bg-[var(--accent)] text-white text-[12px] font-medium hover:brightness-110">Open step <Icon name="external" size={12} /></button>
                        </div>
                      )}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {/* legend */}
      <div className="shrink-0 border-t border-[#e8e3d8] bg-[#faf8f3] px-6 py-2 flex items-center gap-4 text-[11px] text-[#6b6b6b] whitespace-nowrap overflow-x-auto">
        <span className="font-semibold text-[#9aa0a6] uppercase tracking-[0.06em] text-[10.5px] shrink-0">Status</span>
        {["completed", "active", "gated", "pending", "skipped"].map((k) => (<span key={k} className="inline-flex items-center gap-1.5 shrink-0"><InitDot status={k} size={7} /> {INIT_STATUS[k].label}</span>))}
        <span className="ml-auto inline-flex items-center gap-1.5 text-[#9aa0a6] shrink-0"><Icon name="external" size={11} /> Promoted chips link to source system</span>
      </div>
    </div>
  );
}

function InitFilter({ label, options }) {
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState(options[0]);
  const active = value !== options[0];
  return (
    <div className="relative">
      <button onClick={() => setOpen((o) => !o)} className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md border text-[12.5px] ${active ? "border-[var(--accent)]/40 text-[var(--accent)] bg-[var(--accent)]/[0.06]" : "border-[#ece7da] text-[#5a5a5a] bg-white hover:bg-[#faf8f3]"}`}>
        <Icon name="filter-funnel" size={12} /><span>{active ? value : label}</span><Icon name="chevron-down" size={12} className="text-[#9aa0a6]" />
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
          <div className="absolute right-0 top-full mt-1 w-[180px] bg-white rounded-lg border border-[#ece7da] shadow-xl z-40 py-1">
            {options.map((o) => (<button key={o} onClick={() => { setValue(o); setOpen(false); }} className="w-full flex items-center gap-2 px-3 py-1.5 text-[12.5px] text-[#1f1f1f] hover:bg-black/[0.04] text-left"><span className="flex-1">{o}</span>{o === value && <Icon name="check" size={13} className="text-[var(--accent)]" />}</button>))}
          </div>
        </>
      )}
    </div>
  );
}

// ================================================================
//  SCREEN C — INITIATIVE STEP WORKSPACE
// ================================================================

// participants per initiative (humans + the step agent rendered separately)
const INIT_PARTICIPANTS = {
  usr:        [{ initials: "SS", tint: "#b6892e" }, { initials: "MC", tint: "#3b5cf6" }, { initials: "TB", tint: "#0e7c66" }],
  billing:    [{ initials: "MC", tint: "#3b5cf6" }, { initials: "LH", tint: "#c2410c" }],
  offline:    [{ initials: "TB", tint: "#0e7c66" }, { initials: "SS", tint: "#b6892e" }],
  sso:        [{ initials: "LH", tint: "#c2410c" }, { initials: "TB", tint: "#0e7c66" }],
  onboarding: [{ initials: "MC", tint: "#3b5cf6" }],
};

// step skills (capabilities) — generic per layer
const STEP_SKILLS = {
  discovery:    ["Run discovery interview", "Draft opportunity canvas", "Condense research"],
  prd:          ["Draft PRD section", "Pull success metrics", "Condense memories"],
  architecture: ["Draft ADR", "Diagram system", "Assess risk"],
  planning:     ["Draft story", "Pull related Jira stories", "Condense memories"],
  delivery:     ["Draft release plan", "Generate runbook", "Pull open issues"],
  gtm:          ["Draft launch brief", "Pull support themes", "Condense memories"],
};

// memories per step (sample; falls back to a generic pair)
const STEP_MEMORIES = {
  "usr.planning": [
    { title: "Indexing latency budget", snippet: "Search results must return < 200ms p95; reindex runs nightly off-peak.", source: "Architecture · ADR", system: "confluence" },
    { title: "Relevance metric agreed", snippet: "Team agreed on nDCG@10 ≥ 0.8 on the curated eval set as the relevance gate.", source: "PRD · §4 Success metrics", system: "confluence" },
    { title: "CJK tokenization risk", snippet: "Default analyzer splits CJK incorrectly — needs language-aware analyzer per locale.", source: "Chat · Edge cases", system: "teklens" },
  ],
  "billing.prd": [
    { title: "Dunning policy", snippet: "Failed payments retry on a 1/3/7-day schedule before dunning email.", source: "Discovery brief", system: "confluence" },
    { title: "Tax engine constraint", snippet: "EU VAT must be computed server-side; client estimates are non-binding.", source: "Chat · Compliance", system: "teklens" },
  ],
  "offline.architecture": [
    { title: "Conflict resolution", snippet: "Last-write-wins is unacceptable for notes; needs CRDT or per-field merge.", source: "Chat · Edge cases", system: "teklens" },
    { title: "Sync envelope size", snippet: "Mobile sync payloads capped at 2MB; large attachments deferred.", source: "Sync model spec", system: "confluence" },
  ],
};
function stepMemories(initId, stepId) {
  return STEP_MEMORIES[`${initId}.${stepId}`] || [
    { title: "Accountable role confirmed", snippet: `${INIT_STEPS[initStepIndex(stepId)].role} owns the exit gate for this step.`, source: "Pipeline · BMAD", system: "teklens" },
    { title: "Upstream context", snippet: "Prior step collaterals are promoted and available as inputs.", source: "Initiative timeline", system: "teklens" },
  ];
}
const CONTRIB_POOL = [{ initials: "SS", tint: "#b6892e" }, { initials: "MC", tint: "#3b5cf6" }, { initials: "TB", tint: "#0e7c66" }];

// ---------- Avatars ----------
function InitAgentAvatar({ size = 24 }) {
  return (
    <span className="inline-flex items-center justify-center rounded-full text-white shrink-0" title="Step agent"
      style={{ width: size, height: size, background: "linear-gradient(135deg,#3b5cf6,#8b5cf6 55%,#ec4899)" }}>
      <Icon name="sparkles" size={size * 0.55} />
    </span>
  );
}
function InitAvatarStack({ people, size = 26, agent = false }) {
  return (
    <div className="flex items-center">
      {people.map((p, i) => (
        <span key={i} className="ring-2 ring-white rounded-full" style={{ marginLeft: i === 0 ? 0 : -size * 0.32, zIndex: people.length - i + (agent ? 1 : 0) }}>
          <InitAvatar owner={p} size={size} />
        </span>
      ))}
      {agent && <span className="ring-2 ring-white rounded-full" style={{ marginLeft: -size * 0.32, zIndex: 0 }}><InitAgentAvatar size={size} /></span>}
    </div>
  );
}

// ---------- Workspace header (breadcrumb + participants + Promote) ----------
function StepWorkspaceHeader({ pinned, onPromote }) {
  const initiative = initById(pinned.initiativeId);
  const step = INIT_STEPS[initStepIndex(pinned.stepId || initiative.active)];
  const status = initCellStatus(initiative, step.id);
  const gated = status === "gated" || status === "active";
  const participants = INIT_PARTICIPANTS[initiative.id] || [];
  return (
    <div className="shrink-0 bg-white px-5 py-2.5 flex items-center gap-3 border-b border-[#f0ebdd]">
      <div className="flex items-center gap-2 min-w-0">
        <span className="text-[14px] font-semibold text-[#0e0e10] truncate">{initiative.name}</span>
        <Icon name="chevron-right" size={14} className="text-[#cbcbcb]" />
        <span className="text-[14px] font-semibold text-[#0e0e10]">{step.name}</span>
        <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[11px] font-medium border"
          style={{ color: INIT_STATUS[status].color === "var(--accent)" ? "var(--accent)" : INIT_STATUS[status].color, borderColor: "currentColor", background: status === "gated" ? "#fdf3e3" : "#f7f7f5" }}>
          <InitDot status={status} size={6} pulse={status === "gated"} /> {INIT_STATUS[status].label}
        </span>
      </div>
      <div className="flex-1" />
      <InitAvatarStack people={participants} size={26} agent />
      <div className="w-px h-6 bg-[#e8e3d8] mx-1" />
      <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[12px] border bg-[var(--accent)]/[0.07] border-[var(--accent)]/30 text-[var(--accent)] whitespace-nowrap">
        <Icon name="user" size={12} /><span className="font-medium">{step.role}</span>
      </span>
      <button onClick={() => onPromote()} disabled={!gated}
        className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[13px] font-medium shadow-[0_1px_0_rgba(0,0,0,0.08)] ${gated ? "bg-[var(--accent)] text-white hover:brightness-110" : "bg-[#f1f1ee] text-[#9aa0a6] cursor-not-allowed"}`}>
        <Icon name="chevron-up" size={14} /> Promote
      </button>
    </div>
  );
}

// ---------- Artifacts panel (replaces widget rail when a step is open) ----------
function InitiativeArtifactsPanel({ pinned, onClose, onPromote }) {
  const initiative = initById(pinned.initiativeId);
  const step = INIT_STEPS[initStepIndex(pinned.stepId || initiative.active)];
  const status = initCellStatus(initiative, step.id);
  const gated = status === "gated" || status === "active";
  const [memOpen, setMemOpen] = useState(true);
  const [colOpen, setColOpen] = useState(true);
  const memories = stepMemories(initiative.id, step.id);
  const collaterals = (initiative.cells[step.id]?.collaterals) || [];

  return (
    <div className="w-full h-full flex flex-col bg-[#faf8f3] border-l border-[#e8e3d8]">
      <div className="shrink-0 h-11 px-3 flex items-center gap-2 border-b border-[#e8e3d8]">
        <Icon name="folder" size={15} className="text-[#9b8866]" />
        <span className="text-[13px] font-semibold text-[#0e0e10]">Artifacts</span>
        <span className="text-[11px] text-[#9aa0a6]">{step.name}</span>
        <div className="flex-1" />
        <button onClick={onClose} className="p-1 rounded hover:bg-black/[0.05] text-[#9aa0a6]" title="Collapse"><Icon name="panel-right" size={16} /></button>
      </div>
      <div className="flex-1 overflow-y-auto">
        {/* Memories */}
        <ArtSection icon="hash" tint={INIT_LAYER_COLOR.knowledge} title="Memories & work-items" count={memories.length} open={memOpen} onToggle={() => setMemOpen(o => !o)}>
          <div className="flex flex-col gap-2">
            {memories.map((m, i) => <MemoryCard key={i} m={m} />)}
          </div>
        </ArtSection>
        <div className="h-px bg-[#e8e3d8] mx-3" />
        {/* Draft collaterals */}
        <ArtSection icon="file" tint={INIT_LAYER_COLOR.definition} title="Draft collaterals" count={collaterals.length} open={colOpen} onToggle={() => setColOpen(o => !o)}>
          {collaterals.length === 0 ? (
            <div className="rounded-lg border border-dashed border-[#ddd8c9] px-3 py-5 text-center text-[11.5px] text-[#9aa0a6]">
              No collateral yet.<br />Use a skill in the chat to start a draft.
            </div>
          ) : (
            <div className="flex flex-col gap-2.5">
              {collaterals.map((c, i) => <ColCard key={i} c={c} canPromote={gated && c.lifecycle !== "Promoted"} onPromote={() => onPromote(c)} />)}
            </div>
          )}
        </ArtSection>
      </div>
    </div>
  );
}

function ArtSection({ icon, tint, title, count, open, onToggle, children }) {
  return (
    <div className="px-3 py-3">
      <button onClick={onToggle} className="w-full flex items-center gap-2 mb-2.5">
        <span className="w-6 h-6 rounded-md flex items-center justify-center" style={{ background: tint + "1f", color: tint }}><Icon name={icon} size={13} /></span>
        <span className="text-[12.5px] font-semibold text-[#0e0e10] whitespace-nowrap">{title}</span>
        <span className="text-[11px] text-[#9aa0a6] tabular-nums">{count}</span>
        <Icon name={open ? "chevron-down" : "chevron-right"} size={14} className="ml-auto text-[#9aa0a6]" />
      </button>
      {open && children}
    </div>
  );
}

function MemoryCard({ m }) {
  return (
    <div className="rounded-lg border border-[#f0e3d2] bg-[#fdf6ec] p-2.5 hover:border-[#e9c89c] transition-colors cursor-pointer group/mem" style={{ boxShadow: "inset 2px 0 0 #d97706" }}>
      <div className="flex items-start gap-1.5">
        <span className="text-[12.5px] font-semibold text-[#0e0e10] leading-tight flex-1">{m.title}</span>
        <button className="opacity-0 group-hover/mem:opacity-100 transition-opacity text-[#b45309] shrink-0" title="Cite into draft"><Icon name="chevron-up" size={13} /></button>
      </div>
      <div className="mt-1 text-[11.5px] text-[#6b5535] leading-snug">{m.snippet}</div>
      <div className="mt-1.5 flex items-center gap-1.5 text-[10.5px] text-[#9a7d4e]" style={{ color: INIT_SYSTEM[m.system].color }}>
        <Icon name={INIT_SYSTEM[m.system].icon} size={11} />
        <span className="truncate" style={{ color: "#9a7d4e" }}>{m.source}</span>
      </div>
    </div>
  );
}

function ColCard({ c, canPromote, onPromote }) {
  const s = INIT_SYSTEM[c.system];
  const contributors = CONTRIB_POOL.slice(0, 2 + (c.type.length % 2));
  return (
    <div className="rounded-lg border border-[#ece7da] bg-white p-3 hover:border-[var(--accent)]/40 transition-colors">
      <div className="flex items-start gap-2">
        <span className="w-8 h-8 rounded-md flex items-center justify-center shrink-0" style={{ background: s.color + "14", color: s.color }}><Icon name="file" size={15} /></span>
        <div className="flex-1 min-w-0">
          <div className="text-[13px] font-semibold text-[#0e0e10] leading-tight">{c.type}</div>
          <div className="text-[11px] text-[#9aa0a6] mt-0.5 flex items-center gap-1">
            {c.broken ? <span className="text-[#c2410c] inline-flex items-center gap-1"><Icon name="link" size={11} /> link broken — re-auth</span> : <>via {s.label}</>}
          </div>
        </div>
      </div>
      <div className="mt-2.5 flex items-center gap-2">
        <InitLifecycle lifecycle={c.lifecycle} />
        <div className="ml-auto"><InitAvatarStack people={contributors} size={18} /></div>
      </div>
      <div className="mt-2 flex items-center gap-2">
        <span className="text-[10.5px] text-[#9aa0a6] flex items-center gap-1"><Icon name="info" size={11} /> updated 12m ago</span>
        <div className="flex-1" />
        <button className="text-[11.5px] text-[#5a5a5a] px-2 py-1 rounded hover:bg-black/[0.04]">Open</button>
        <button onClick={onPromote} disabled={!canPromote}
          className={`flex items-center gap-1 text-[11.5px] font-medium px-2 py-1 rounded ${canPromote ? "bg-[var(--accent)] text-white hover:brightness-110" : "bg-[#f1f1ee] text-[#bcbcbc] cursor-not-allowed"}`}
          title={canPromote ? "Promote to source system" : c.lifecycle === "Promoted" ? "Already promoted" : "Disabled until exit gate"}>
          <Icon name="chevron-up" size={12} /> Promote
        </button>
      </div>
    </div>
  );
}

// ---------- Promote dialog ----------
function PromoteDialog({ collateral, step, onClose }) {
  const s = INIT_SYSTEM[collateral.system];
  const target = collateral.system === "jira" ? "Jira project TEK — Epic “Unified Search”"
    : collateral.system === "confluence" ? "Confluence space ENG"
    : collateral.system === "git" ? "Git repo contem/teklens-ai"
    : "Teklens workspace";
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-6" onClick={onClose}>
      <div className="w-[440px] bg-white rounded-2xl border border-[#ece7da] shadow-2xl overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="px-5 py-3.5 border-b border-[#f0ebdd] flex items-center gap-2">
          <Icon name="chevron-up" size={16} className="text-[var(--accent)]" />
          <span className="text-[14px] font-semibold text-[#0e0e10]">Promote collateral</span>
          <button onClick={onClose} className="ml-auto p-1 rounded hover:bg-black/[0.05] text-[#9aa0a6]"><Icon name="x" size={15} /></button>
        </div>
        <div className="px-5 py-4">
          <div className="flex items-center gap-2.5 p-3 rounded-lg border border-[#ece7da] bg-[#faf8f3]">
            <span className="w-9 h-9 rounded-md flex items-center justify-center shrink-0" style={{ background: s.color + "14", color: s.color }}><Icon name="file" size={16} /></span>
            <div className="flex-1 min-w-0">
              <div className="text-[13px] font-semibold text-[#0e0e10]">{collateral.type}</div>
              <div className="text-[11px] text-[#9aa0a6] mt-0.5">Draft collateral · {step.name}</div>
            </div>
            <InitLifecycle lifecycle={collateral.lifecycle} />
          </div>
          <div className="mt-4 text-[11px] uppercase tracking-[0.06em] text-[#9aa0a6] font-semibold">Resolved target binding</div>
          <div className="mt-1.5 flex items-center gap-2.5 p-3 rounded-lg border border-[var(--accent)]/30 bg-[var(--accent)]/[0.05]">
            <span style={{ color: s.color }}><Icon name={s.icon} size={18} /></span>
            <div className="flex-1">
              <div className="text-[12.5px] font-medium text-[#0e0e10]">Publish to {target}</div>
              <div className="text-[11px] text-[#6b6b6b] mt-0.5">Becomes the single system of record · synced back via webhook</div>
            </div>
          </div>
          <div className="mt-4 flex items-start gap-2 text-[11.5px] text-[#9a6516] bg-[#fdf3e3] border border-[#f2dfbe] rounded-lg px-3 py-2">
            <Icon name="shield" size={14} className="mt-0.5 shrink-0" />
            <span>This is the <span className="font-semibold">exit-gate decision</span> for {step.name}. Promoting marks the StepRun complete and advances the workflow.</span>
          </div>
        </div>
        <div className="px-5 py-3 border-t border-[#f0ebdd] bg-[#faf8f3] flex items-center gap-2">
          <span className="text-[11.5px] text-[#9aa0a6] flex items-center gap-1.5"><Icon name="users" size={13} /> Any project member can approve</span>
          <div className="flex-1" />
          <button onClick={onClose} className="px-3 py-1.5 rounded-md text-[12.5px] text-[#5a5a5a] hover:bg-black/[0.05]">Cancel</button>
          <button onClick={onClose} className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-md bg-[var(--accent)] text-white text-[12.5px] font-medium hover:brightness-110">
            <Icon name="check" size={14} /> Confirm &amp; promote
          </button>
        </div>
      </div>
    </div>
  );
}
