// Teklens.AI — Initiative Detail page (opened from the Dashboard).
// Extended version of the expanded line item: header + stepper, recent conversations & runs (joinable),
// stage-relevant agents with their forges/skills grouped beneath, memories, and a pinned composer.
// Reuses globals from dashboard.jsx (DASH_*, atoms) and app's `Icon`.

function InitiativeDetail({ initiativeId, onBack, onOpenContext }) {
  const it = dashInitById(initiativeId) || DASH_INITIATIVES[0];
  const phase = DASH_PHASES[dashPhaseIndex(it.phase)];
  const caps = DASH_CAPS[it.phase] || [];
  const roleIds = DASH_STAGE_ROLES[it.phase] || ["pm", "po"];
  const capsByRole = (rid) => caps.filter((c) => c.agent === rid);
  // capabilities whose agent isn't one of the headline roles fall under the first role
  const extra = caps.filter((c) => !roleIds.includes(c.agent));

  return (
    <div className="flex-1 min-w-0 flex flex-col bg-[#f4f1ea]">
      {/* ===== sticky header ===== */}
      <div className="shrink-0 bg-white border-b border-[#e8e3d8]">
        <div className="px-6 py-3 flex items-center gap-3">
          <button onClick={onBack} className="flex items-center gap-1 px-2 py-1.5 -ml-1 rounded-md text-[12.5px] text-[#5a5a5a] hover:bg-black/[0.04] hover:text-[#0e0e10]"><Icon name="chevron-left" size={16} /> Dashboard</button>
          <span className="w-px h-5 bg-[#e8e3d8]" />
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2">
              <h1 className="text-[17px] font-semibold text-[#0e0e10] truncate">{it.name}</h1>
              <span className="text-[11px] font-mono text-[#9aa0a6] shrink-0">{it.code}</span>
            </div>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <span className="text-[11.5px] text-[#9aa0a6]">Owner</span>
            <PersonAvatar who={it.owner} size={30} />
          </div>
        </div>
        {/* description — belongs to the initiative */}
        <div className="px-6 -mt-1 pb-2"><p className="text-[12.5px] text-[#5a5a5a] leading-snug max-w-[820px]" data-comment-anchor="9d32cb30e1-p-45-13">{it.desc}</p></div>
        {/* stepper row */}
        <div className="px-6 pb-3"><div className="p-2 rounded-xl bg-[#faf8f3] border border-[#f0ebdd] flex items-center gap-2 flex-wrap"><div className="flex-1 min-w-[260px]"><StageStepper phase={it.phase} /></div><AdvanceStage phase={it.phase} name={it.name} /></div></div>
      </div>

      {/* ===== scroll body ===== */}
      <div className="flex-1 overflow-y-auto">
        <div className="max-w-[1000px] mx-auto px-6 py-6 flex flex-col gap-7">

          {/* pinned composer */}
          <div>
            <div className="text-[11px] uppercase tracking-[0.06em] text-[#9aa0a6] font-semibold mb-1.5">Start a conversation in this initiative</div>
            <PinnedComposer pinLabel={it.name} pinIcon="grid" onSubmit={() => onOpenContext({ kind: "conversation", label: it.name })} />
          </div>

          {/* artefacts */}
          <Section icon="file" title="Artefacts" count={it.artefacts.length}>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-1.5">
              {it.artefacts.map((a) => <ArtefactRow key={a.id} a={a} onOpen={() => onOpenContext({ kind: "artefact", label: a.name })} onDragStart={(e) => e.preventDefault()} />)}
            </div>
          </Section>

          {/* recent conversations + recent runs */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
            <Section icon="message" title="Recent conversations" count={it.convos.length} hint="public · joinable">
              <div className="flex flex-col">{it.convos.map((c) => <ConvoCard key={c.id} c={c} onJoin={() => onOpenContext({ kind: "conversation", label: c.title })} />)}</div>
            </Section>
            <Section icon="circle-dot" title="Recent runs" count={it.runs.length} hint="each produces an artefact">
              <div className="flex flex-col">{it.runs.map((r) => <RunCard key={r.id} r={r} onOpen={() => onOpenContext({ kind: "run", label: r.title })} />)}</div>
            </Section>
          </div>

          {/* stage agents + their forges/skills */}
          <div>
            <div className="flex items-baseline gap-2 mb-1">
              <h2 className="text-[15px] font-semibold text-[#0e0e10]">{phase.name} Stage: Agent team</h2>
            </div>
            <div className="flex flex-col gap-4 mt-3">
              {roleIds.map((rid, idx) => {
                const role = DASH_ROLES[rid];
                const list = [...capsByRole(rid), ...(idx === 0 ? extra : [])];
                return (
                  <div key={rid} className="rounded-2xl border border-[#e8e3d8] bg-white overflow-hidden">
                    <div className="flex items-center gap-3 px-4 py-3 border-b border-[#f0ebdd] bg-[#faf8f3]">
                      <RoleAvatar rid={rid} size={42} />
                      <div className="min-w-0 flex-1">
                        <div className="text-[14px] font-semibold text-[#0e0e10]">{role.title}</div>
                        <div className="text-[11.5px] text-[#9aa0a6]">{list.length} forges &amp; skills for this stage</div>
                      </div>
                      <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md border border-[#ece7da] text-[11.5px] text-[#6b6b6b]"><Icon name="sparkles" size={12} className="text-[var(--accent)]" /> Smart select</span>
                    </div>
                    <div className="p-3 grid grid-cols-1 lg:grid-cols-2 gap-2">
                      {list.map((cap, i) => <CapabilityCard key={i} cap={cap} onRun={(label) => onOpenContext({ kind: "skill", label })} />)}
                    </div>
                  </div>);

              })}
            </div>
          </div>

          {/* memories */}
          <Section icon="hash" title="Memories" count={it.memories.length}>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-2">
              {it.memories.map((m) => <MemoryRow key={m.id} m={m} onOpen={() => onOpenContext({ kind: "memory", label: m.title })} />)}
            </div>
          </Section>

          <div className="h-2" />
        </div>
      </div>
    </div>);

}

function Section({ icon, title, count, hint, children }) {
  return (
    <section>
      <div className="flex items-center gap-2 mb-2.5">
        <span className="w-6 h-6 rounded-md flex items-center justify-center bg-[#f4f1ea] text-[#9b8866]"><Icon name={icon} size={13} /></span>
        <h2 className="text-[14px] font-semibold text-[#0e0e10]">{title}</h2>
        {count != null && <span className="text-[11px] text-[#9aa0a6] tabular-nums">{count}</span>}
        {hint && <span className="text-[11.5px] text-[#9aa0a6] ml-1">· {hint}</span>}
      </div>
      <div className="rounded-2xl border border-[#e8e3d8] bg-white p-3">{children}</div>
    </section>);

}

function RoleAvatar({ rid, size = 42 }) {
  const role = DASH_ROLES[rid];
  const src = window.__res ? window.__res(role.avatar) : role.avatar;
  return <img src={src} alt={role.title} title={role.title} className="rounded-full object-cover shrink-0 bg-white ring-2 ring-[var(--accent)]" style={{ width: size, height: size }} />;
}

function MemoryRow({ m, onOpen }) {
  return (
    <button onClick={onOpen} className="group text-left rounded-xl border border-[#f0e3d2] bg-[#fdf6ec] p-3 hover:border-[#e9c89c] transition-colors" style={{ boxShadow: "inset 2px 0 0 #d97706" }}>
      <div className="flex items-start gap-1.5">
        <Icon name="file" size={13} className="text-[#b45309] mt-0.5 shrink-0" />
        <span className="text-[12.5px] font-semibold text-[#0e0e10] leading-tight flex-1">{m.title}</span>
        <Icon name="chevron-right" size={14} className="text-[#caa367] shrink-0 group-hover:text-[#b45309]" />
      </div>
      <div className="mt-1 text-[11.5px] text-[#6b5535] leading-snug">{m.snippet}</div>
    </button>);

}