// =========================================================
// DECISIONS WORKSPACE V2 — Phase 19
// -----------------------------------------------------------------
// Global (cross-project) canonical destination for product,
// design, technical, commercial, and operational decisions.
//
// Depth cap: Decisions → Decision Detail. Three peer views:
// Overview / Log / Reviews. No sub-nav inside a view.
//
// Reads exclusively from data.decisions[] (canonical) —
// enriched additively in Phase 19. Every canonical Feature /
// Research / Design / Development / Documents / My Work item
// references the same decision IDs; nothing is duplicated.
// =========================================================

const DC_STATE = {
  'open':       { tone: 'yellow', label: 'Open'       },
  'decided':    { tone: 'green',  label: 'Decided'    },
  'superseded': { tone: 'gray',   label: 'Superseded' },
  'archived':   { tone: 'gray',   label: 'Archived'   },
};

// Type badges — deliberately monochrome. Type is a small mono
// short code, never a colored category.
const DC_TYPE = {
  product:     { short: 'PROD', label: 'Product'     },
  design:      { short: 'DES',  label: 'Design'      },
  technical:   { short: 'TECH', label: 'Technical'   },
  commercial:  { short: 'COMM', label: 'Commercial'  },
  operational: { short: 'OPS',  label: 'Operational' },
};

function dcStateChip(state, size = 'sm') {
  const s = DC_STATE[state];
  if (!s) return null;
  return <Label tone={s.tone} dot size={size}>{s.label}</Label>;
}

function dcPortrait(name) {
  const projs = Object.values(window.MYGENI_PROJECT_DATA || {});
  for (const p of projs) {
    const hit = (p.people || {})[(name || '').toLowerCase()];
    if (hit?.portrait) return hit.portrait;
  }
  return null;
}

function dcProject(pid) {
  return window.MYGENI_PROJECT_DATA?.[pid];
}

function dcDecById(data, id) {
  return (data.decisions || []).find(d => d.id === id);
}

// -----------------------------------------------------------------
// Compact project glyph — one neutral surface for every project.
// -----------------------------------------------------------------
function DCProjectGlyph({ project }) {
  const code = (project?.code || project?.name || 'PR').replace(/[^A-Z0-9]/g, '').slice(0, 3) || 'PR';
  return <span className="dc-proj-glyph mono">{code}</span>;
}

// -----------------------------------------------------------------
// Canonical link chip cloud — resolves stage / mission / feature /
// research / design / dev / doc / work / contract into deep links.
// -----------------------------------------------------------------
function DCLinkedChips({ links, impactNodes, size }) {
  const chips = [];
  if (links) {
    const project = dcProject(links.project);
    const stage   = links.stage   && project?.stages?.find(s => s.n === links.stage);
    const mission = links.mission && (window.MYGENI_MISSIONS || {})[links.mission];
    const feature = links.feature && project?.features?.find(f => f.id === links.feature);
    if (project) chips.push({ icon: 'projects', label: project.code, href: `#/projects/${project.id}/overview` });
    if (stage)   chips.push({ icon: 'stages',   label: `S${String(stage.n).padStart(2,'0')} · ${stage.name}`, href: `#/projects/${project.id}/plan` });
    if (mission) chips.push({ icon: mission.icon, label: `${mission.label} mission`, href: `#/projects/${project.id}/plan` });
    if (feature) chips.push({ icon: 'features', label: feature.title, href: `#/projects/${project.id}/features/${feature.id}` });
  }
  (impactNodes || []).forEach(n => {
    const p = dcProject(n.project);
    if (!p) return;
    if (n.kind === 'design')   chips.push({ icon: 'palette',   label: n.label, href: `#/projects/${p.id}/design/item/${n.ref}` });
    if (n.kind === 'research') chips.push({ icon: 'flask',     label: n.label, href: `#/projects/${p.id}/research/study/${n.ref}` });
    if (n.kind === 'dev')      chips.push({ icon: 'terminal',  label: n.label, href: `#/projects/${p.id}/development/system/${n.ref}` });
    if (n.kind === 'doc')      chips.push({ icon: 'files',     label: n.label, href: `#/projects/${p.id}/documents/doc/${n.ref}` });
  });
  if (!chips.length) return null;
  return (
    <div className={`dc-chips${size === 'sm' ? ' dc-chips-sm' : ''}`}>
      {chips.map((c, i) => (
        <a key={i} href={c.href} className="dc-chip" onClick={(e) => e.stopPropagation()}>
          <Icon name={c.icon} size={10} strokeWidth={1.75} />
          <span className="truncate">{c.label}</span>
        </a>
      ))}
    </div>
  );
}

// Compact inline (safe inside a parent <a>).
function DCLinkedInline({ links }) {
  if (!links) return null;
  const project = dcProject(links.project);
  const stage   = links.stage   && project?.stages?.find(s => s.n === links.stage);
  const feature = links.feature && project?.features?.find(f => f.id === links.feature);
  const parts = [];
  if (project) parts.push(project.code);
  if (stage)   parts.push(`S${String(stage.n).padStart(2,'0')} · ${stage.name}`);
  if (feature) parts.push(feature.title);
  if (!parts.length) return null;
  return (
    <span className="dc-inline">
      {parts.map((p, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="dot-sep">·</span>}
          <span>{p}</span>
        </React.Fragment>
      ))}
    </span>
  );
}

// =========================================================
// SHARED ROW — used across Overview / Log
// =========================================================

function DCRow({ dec, showType = false, onOpen }) {
  const project = dcProject(dec.project);
  const evidenceN = (dec.evidence || []).length;
  return (
    <a href={`#/decisions/dec/${dec.id}`}
       className={`dc-row dc-row-${dec.status}`}
       onClick={onOpen ? (e) => { e.preventDefault(); onOpen(dec.id); } : undefined}>
      <div className="dc-row-main">
        <div className="dc-row-head">
          {dcStateChip(dec.status)}
          {showType && DC_TYPE[dec.type] && <span className="dc-type mono">{DC_TYPE[dec.type].short}</span>}
          <span className="dc-row-title">{dec.title}</span>
        </div>
        {dec.ctx && <div className="dc-row-ctx">{dec.ctx}</div>}
        <div className="dc-row-meta">
          {project && (
            <>
              <DCProjectGlyph project={project} />
              <span className="dc-proj-name">{project.code}</span>
              <span className="dot-sep">·</span>
            </>
          )}
          <DCLinkedInline links={dec.links} />
          {evidenceN > 0 && <>
            <span className="dot-sep">·</span>
            <span className="dc-evidence-count">
              <Icon name="link" size={10} strokeWidth={1.75} />
              <span>{evidenceN} evidence</span>
            </span>
          </>}
        </div>
      </div>
      <div className="dc-row-side">
        <Avatar name={dec.owner} size="xs" portrait={dcPortrait(dec.owner)} />
        <div className="dc-row-owner">
          <div className="dc-row-owner-name">{dec.owner}</div>
          <div className="dc-row-owner-when">{dec.status === 'open' ? 'Awaiting decision' : `Decided ${dec.when}`}</div>
        </div>
      </div>
      <Icon name="chevronRight" size={14} strokeWidth={2} style={{ color: 'var(--text-tertiary)', flex: 'none' }} />
    </a>
  );
}

// =========================================================
// OVERVIEW
// =========================================================

function DCOverview({ data, onOpen, onNavigate }) {
  const all = data.decisions || [];
  const open = all.filter(d => d.status === 'open');
  const decided = all.filter(d => d.status === 'decided');
  const recentlyDecided = [...decided].slice(0, 4);

  // Flagship for the Decision Impact card
  const flagship = dcDecById(data, 'dec-brief-model') || decided[0];

  // Upcoming reviews — decisions with a reviewDate (future-ish)
  const reviews = decided.filter(d => d.reviewDate);

  return (
    <div className="dc-overview">
      {/* --- Needs Decision --------------------------------------- */}
      <div>
        <div className="ov-section-head" style={{ paddingBottom: 10 }}>
          <h3>Needs decision</h3>
          {open.length > 0 && <span className="dc-count">{open.length}</span>}
        </div>
        {open.length ? (
          <div className="dc-needs-list">
            {open.map(dec => {
              const project = dcProject(dec.project);
              const evidenceN = (dec.evidence || []).length;
              const blocking = dec.links?.feature && project?.features?.find(f => f.id === dec.links.feature);
              return (
                <a key={dec.id} href={`#/decisions/dec/${dec.id}`}
                   className="dc-needs-card"
                   onClick={(e) => { e.preventDefault(); onOpen(dec.id); }}>
                  <div className="dc-needs-body">
                    <div className="dc-needs-eyebrow">
                      <Label tone="yellow" dot size="sm">Open</Label>
                      {DC_TYPE[dec.type] && <span className="dc-type mono">{DC_TYPE[dec.type].short}</span>}
                    </div>
                    <div className="dc-needs-question">{dec.question || dec.title}</div>
                    <div className="dc-needs-meta">
                      {project && <>
                        <DCProjectGlyph project={project} />
                        <span>{project.code}</span>
                        <span className="dot-sep">·</span>
                      </>}
                      <DCLinkedInline links={dec.links} />
                    </div>
                    <div className="dc-needs-facts">
                      {evidenceN > 0 && (
                        <span className="dc-needs-fact">
                          <span className="dc-eyebrow-inline">Evidence</span>
                          <b>{evidenceN} linked items</b>
                        </span>
                      )}
                      {blocking && (
                        <span className="dc-needs-fact">
                          <span className="dc-eyebrow-inline">Blocking</span>
                          <b>{blocking.title}</b>
                        </span>
                      )}
                      <span className="dc-needs-fact">
                        <span className="dc-eyebrow-inline">Owner</span>
                        <span className="dc-needs-owner">
                          <Avatar name={dec.owner} size="xs" portrait={dcPortrait(dec.owner)} />
                          <b>{dec.owner.split(' ')[0]}</b>
                        </span>
                      </span>
                    </div>
                  </div>
                  <div className="dc-needs-cta">
                    <span>Open decision</span>
                    <Icon name="chevronRight" size={14} strokeWidth={2} />
                  </div>
                </a>
              );
            })}
          </div>
        ) : (
          <div className="dc-quiet">
            <Icon name="check" size={14} strokeWidth={1.75} />
            <span>No open decisions right now.</span>
          </div>
        )}
      </div>

      {/* --- Recently decided ------------------------------------- */}
      <div>
        <div className="ov-section-head" style={{ paddingBottom: 10 }}>
          <h3>Recently decided</h3>
          <a className="link" onClick={() => onNavigate('log')}>Full decision log →</a>
        </div>
        <div className="dc-list">
          {recentlyDecided.map(d => <DCRow key={d.id} dec={d} showType onOpen={onOpen} />)}
        </div>
      </div>

      {/* --- Decision Impact (flagship) -------------------------- */}
      {flagship && flagship.impact && (
        <div>
          <div className="ov-section-head" style={{ paddingBottom: 10 }}>
            <h3>Decision impact</h3>
            <span className="dc-count-line">How one decision shapes execution</span>
          </div>
          <div className="dc-impact-card" onClick={() => onOpen(flagship.id)} style={{ cursor: 'pointer' }}>
            <div className="dc-impact-head">
              <div className="dc-eyebrow-inline">Decision</div>
              <div className="dc-impact-title">{flagship.title}</div>
              <div className="dc-impact-sum">{flagship.impact.summary}</div>
            </div>
            <DCImpactMap flagship={flagship} />
          </div>
        </div>
      )}

      {/* --- Upcoming reviews ------------------------------------ */}
      {reviews.length > 0 && (
        <div>
          <div className="ov-section-head" style={{ paddingBottom: 10 }}>
            <h3>Upcoming reviews</h3>
            <a className="link" onClick={() => onNavigate('reviews')}>All reviews →</a>
          </div>
          <div className="dc-list">
            {reviews.slice(0, 3).map(d => (
              <a key={d.id} href={`#/decisions/dec/${d.id}`}
                 className="dc-review-row"
                 onClick={(e) => { e.preventDefault(); onOpen(d.id); }}>
                <div className="dc-review-date">
                  <div className="mono dc-review-d">{d.reviewDate?.split(' ')[1]?.replace(',','') || ''}</div>
                  <div className="dc-review-m">{d.reviewDate?.split(' ')[0] || ''}</div>
                </div>
                <div className="dc-review-body">
                  <div className="dc-review-title">{d.title}</div>
                  <div className="dc-review-sub">
                    <span>Review scheduled for</span>
                    <b>{d.reviewDate}</b>
                    <span className="dot-sep">·</span>
                    <span>Decided {d.when}</span>
                  </div>
                </div>
                {dcStateChip(d.status)}
              </a>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// =========================================================
// LOG
// =========================================================

function DCLog({ data, onOpen }) {
  const all = data.decisions || [];
  const [chip,    setChip]    = React.useState('all');
  const [project, setProject] = React.useState('all');
  const [stage,   setStage]   = React.useState('all');
  const [type,    setType]    = React.useState('all');
  const [owner,   setOwner]   = React.useState('all');

  const projects = Array.from(new Set(all.map(d => d.project).filter(Boolean)));
  const stages   = Array.from(new Set(all.map(d => d.links?.stage).filter(Boolean))).sort();
  const types    = Array.from(new Set(all.map(d => d.type).filter(Boolean)));
  const owners   = Array.from(new Set(all.map(d => d.owner).filter(Boolean)));

  const chips = [
    { k: 'all',        label: 'All',        n: all.length },
    { k: 'open',       label: 'Open',       n: all.filter(d => d.status === 'open').length },
    { k: 'decided',    label: 'Decided',    n: all.filter(d => d.status === 'decided').length },
    { k: 'superseded', label: 'Superseded', n: all.filter(d => d.status === 'superseded').length },
  ];

  const filtered = all.filter(d => {
    if (chip    !== 'all' && d.status !== chip)                       return false;
    if (project !== 'all' && d.project !== project)                   return false;
    if (stage   !== 'all' && String(d.links?.stage) !== stage)        return false;
    if (type    !== 'all' && d.type !== type)                         return false;
    if (owner   !== 'all' && d.owner !== owner)                       return false;
    return true;
  });

  const clearAll = () => { setChip('all'); setProject('all'); setStage('all'); setType('all'); setOwner('all'); };
  const any = chip !== 'all' || project !== 'all' || stage !== 'all' || type !== 'all' || owner !== 'all';

  return (
    <div className="dc-log">
      <div className="dv-filters">
        <div className="dv-filter-chips">
          {chips.map(c => (
            <button key={c.k}
                    className={`dv-chip${chip === c.k ? ' active' : ''}`}
                    onClick={() => setChip(c.k)}>
              {c.label} <span className="dv-chip-n">{c.n}</span>
            </button>
          ))}
        </div>
        <div className="dv-filter-selects">
          <select value={project} onChange={(e) => setProject(e.target.value)} className="dv-select">
            <option value="all">All projects</option>
            {projects.map(pid => <option key={pid} value={pid}>{dcProject(pid)?.code || pid}</option>)}
          </select>
          <select value={stage} onChange={(e) => setStage(e.target.value)} className="dv-select">
            <option value="all">All stages</option>
            {stages.map(s => <option key={s} value={String(s)}>Stage {String(s).padStart(2,'0')}</option>)}
          </select>
          <select value={type} onChange={(e) => setType(e.target.value)} className="dv-select">
            <option value="all">Any type</option>
            {types.map(t => <option key={t} value={t}>{DC_TYPE[t]?.label || t}</option>)}
          </select>
          <select value={owner} onChange={(e) => setOwner(e.target.value)} className="dv-select">
            <option value="all">Any owner</option>
            {owners.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
          {any && <button className="dv-clear" onClick={clearAll}>Clear</button>}
        </div>
      </div>

      <div className="dx-result-count">
        <span className="mono">{filtered.length}</span> of <span className="mono">{all.length}</span> decisions
      </div>

      {filtered.length ? (
        <div className="dc-list">
          {filtered.map(d => <DCRow key={d.id} dec={d} showType onOpen={onOpen} />)}
        </div>
      ) : (
        <div className="dv-empty dv-empty-large">
          No decisions match those filters. <button className="link" onClick={clearAll}>Clear all</button>.
        </div>
      )}
    </div>
  );
}

// =========================================================
// REVIEWS
// =========================================================

function DCReviews({ data, onOpen }) {
  const all = data.decisions || [];
  const withReview = all.filter(d => d.reviewDate && d.status === 'decided');
  const superseded = all.filter(d => d.status === 'superseded');

  return (
    <div className="dc-reviews">
      <div>
        <div className="ov-section-head" style={{ paddingBottom: 10 }}>
          <h3>Review due</h3>
          {withReview.length > 0 && <span className="dc-count">{withReview.length}</span>}
        </div>
        {withReview.length ? (
          <div className="dc-list">
            {withReview.map(d => (
              <a key={d.id} href={`#/decisions/dec/${d.id}`}
                 className="dc-review-row"
                 onClick={(e) => { e.preventDefault(); onOpen(d.id); }}>
                <div className="dc-review-date">
                  <div className="mono dc-review-d">{d.reviewDate?.split(' ')[1]?.replace(',','') || ''}</div>
                  <div className="dc-review-m">{d.reviewDate?.split(' ')[0] || ''}</div>
                </div>
                <div className="dc-review-body">
                  <div className="dc-review-title">{d.title}</div>
                  <div className="dc-review-sub">
                    <span>Review scheduled for</span>
                    <b>{d.reviewDate}</b>
                    <span className="dot-sep">·</span>
                    <span>Decided {d.when}</span>
                    <span className="dot-sep">·</span>
                    <span>Owner {d.owner}</span>
                  </div>
                </div>
                <div className="dc-review-outcomes">
                  <span className="dc-review-outcome">Still valid</span>
                  <span className="dc-review-outcome">Needs update</span>
                  <span className="dc-review-outcome">Supersede</span>
                </div>
              </a>
            ))}
          </div>
        ) : (
          <div className="dc-quiet"><Icon name="check" size={14} strokeWidth={1.75} /><span>No reviews due.</span></div>
        )}
      </div>

      {superseded.length > 0 && (
        <div>
          <div className="ov-section-head" style={{ paddingBottom: 10 }}>
            <h3>Superseded (preserved)</h3>
            <span className="dc-count-line">History kept intact</span>
          </div>
          <div className="dc-list">
            {superseded.map(d => {
              const newer = d.supersededBy && dcDecById(data, d.supersededBy);
              return (
                <a key={d.id} href={`#/decisions/dec/${d.id}`}
                   className="dc-super-row"
                   onClick={(e) => { e.preventDefault(); onOpen(d.id); }}>
                  <div className="dc-super-body">
                    <div className="dc-super-title">{d.title}</div>
                    <div className="dc-super-sub">
                      <span>Superseded on {newer?.when || d.when}</span>
                      {newer && <>
                        <span className="dot-sep">·</span>
                        <span>by</span>
                        <b>{newer.title}</b>
                      </>}
                    </div>
                  </div>
                  {dcStateChip(d.status)}
                </a>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// =========================================================
// IMPACT MAP — restrained radial composition
// =========================================================

function DCImpactMap({ flagship }) {
  const nodes = flagship?.impact?.nodes || [];
  if (!nodes.length) return null;
  const W = 720, H = 320;
  const cx = W / 2, cy = H / 2;
  const R = 130;
  const n = nodes.length;
  const kindIcon = { feature: 'features', design: 'palette', dev: 'terminal', research: 'flask', stage: 'stages', doc: 'files' };

  const positions = nodes.map((node, i) => {
    const angle = (Math.PI * 2 * i) / n - Math.PI / 2;
    return { x: cx + R * Math.cos(angle), y: cy + R * Math.sin(angle), node };
  });

  const centerR = 68;
  const nodeH = 30, nodeW = 156;

  const hrefFor = (node) => {
    const p = dcProject(node.project);
    if (!p) return null;
    if (node.kind === 'feature')  return `#/projects/${p.id}/features/${node.ref}`;
    if (node.kind === 'design')   return `#/projects/${p.id}/design/item/${node.ref}`;
    if (node.kind === 'dev')      return `#/projects/${p.id}/development/system/${node.ref}`;
    if (node.kind === 'research') return `#/projects/${p.id}/research/study/${node.ref}`;
    if (node.kind === 'doc')      return `#/projects/${p.id}/documents/doc/${node.ref}`;
    if (node.kind === 'stage')    return `#/projects/${p.id}/plan`;
    return null;
  };

  return (
    <div className="dc-impact-map">
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
        {/* Connectors */}
        {positions.map((p, i) => (
          <line key={'l'+i} x1={cx} y1={cy} x2={p.x} y2={p.y}
                stroke="rgba(16,16,16,0.15)" strokeWidth="1"
                strokeDasharray={i % 3 === 0 ? '' : '3 3'} />
        ))}

        {/* Center node */}
        <g>
          <circle cx={cx} cy={cy} r={centerR} fill="#FDFDFD"
                  stroke="rgba(42,133,255,0.55)" strokeWidth="1.5" />
          <circle cx={cx} cy={cy} r={centerR + 6} fill="none"
                  stroke="rgba(42,133,255,0.15)" strokeWidth="1" />
          <text x={cx} y={cy - 8} textAnchor="middle" fontFamily="Inter" fontSize="9"
                fontWeight="700" letterSpacing="1.4" fill="var(--text-tertiary)">DECISION</text>
          <text x={cx} y={cy + 8} textAnchor="middle" fontFamily="Inter" fontSize="12"
                fontWeight="700" letterSpacing="-0.02em" fill="var(--text-primary)">
            <tspan x={cx} dy="0">Structured</tspan>
            <tspan x={cx} dy="14">Project Brief</tspan>
          </text>
        </g>

        {/* Perimeter nodes */}
        {positions.map((p, i) => {
          const node = p.node;
          const href = hrefFor(node);
          const iconName = kindIcon[node.kind] || 'grid';
          const cardX = p.x - nodeW / 2;
          const cardY = p.y - nodeH / 2;
          const inner = (
            <g>
              <rect x={cardX} y={cardY} width={nodeW} height={nodeH} rx="8"
                    fill="#FDFDFD" stroke="rgba(16,16,16,0.12)" strokeWidth="1" />
              <text x={cardX + 14} y={cardY + nodeH/2 + 4} fontFamily="Inter"
                    fontSize="12" fontWeight="600" letterSpacing="-0.015em"
                    fill="var(--text-primary)">{node.label}</text>
              <rect x={cardX + nodeW - 32} y={cardY + 8} width="24" height="14" rx="4"
                    fill="var(--bg-app)" />
              <text x={cardX + nodeW - 20} y={cardY + 18} textAnchor="middle"
                    fontFamily="JetBrains Mono" fontSize="8" fontWeight="700"
                    letterSpacing="0.05em" fill="var(--text-tertiary)">
                {(node.kind || '').slice(0, 4).toUpperCase()}
              </text>
            </g>
          );
          return href ? (
            <a key={i} href={href}>{inner}</a>
          ) : (
            <g key={i}>{inner}</g>
          );
        })}
      </svg>
    </div>
  );
}

// =========================================================
// EVIDENCE CARD — per-source-kind realistic preview
// =========================================================

function DCEvidenceCard({ ev, projectId }) {
  const kind = ev.sourceKind;
  const p = dcProject(projectId);

  const href = (() => {
    if (!p) return null;
    if (kind === 'research') return `#/projects/${p.id}/research/study/${ev.ref?.research}`;
    if (kind === 'design')   return ev.ref?.design ? `#/projects/${p.id}/design/item/${ev.ref.design}` : null;
    if (kind === 'dev')      return `#/projects/${p.id}/development/system/${ev.ref?.dev}`;
    if (kind === 'doc')      return `#/projects/${p.id}/documents/doc/${ev.ref?.doc}`;
    if (kind === 'insight')  return `#/projects/${p.id}/research/insights`;
    return null;
  })();

  const kindLbl = ({
    research: 'Research', design: 'Design', dev: 'Development',
    doc: 'Document', insight: 'Insight',
  })[kind] || 'Evidence';

  // Body varies per kind. Research gets an editorial pull-quote; Design
  // uses DXPreview if a linked doc exists; Dev shows a mini diagram;
  // Doc shows DXPreview; Insight shows an editorial highlight.
  let body;
  if (kind === 'research' || kind === 'insight') {
    body = (
      <div className="dc-ev-quote">
        <div className="dc-ev-mark">"</div>
        <div className="dc-ev-quote-text">{ev.finding}</div>
      </div>
    );
  } else if (kind === 'design' && ev.ref?.doc) {
    const doc = p?.documents?.find(d => d.id === ev.ref.doc);
    body = (
      <div className="dc-ev-preview-row">
        <div className="dc-ev-preview-thumb">
          {doc && window.DXPreview ? <DXPreview doc={doc} /> : <div className="dc-ev-thumb-fallback" />}
        </div>
        <div className="dc-ev-text">{ev.finding}</div>
      </div>
    );
  } else if (kind === 'dev') {
    body = (
      <div className="dc-ev-preview-row">
        <div className="dc-ev-preview-thumb dc-ev-preview-thumb-dev">
          <svg viewBox="0 0 100 62" width="100%" height="100%">
            <rect x="6" y="8" width="34" height="14" rx="3" fill="#FDFDFD" stroke="rgba(16,16,16,0.12)"/>
            <rect x="6" y="28" width="34" height="14" rx="3" fill="#FDFDFD" stroke="rgba(42,133,255,0.55)"/>
            <rect x="6" y="46" width="34" height="12" rx="3" fill="#FDFDFD" stroke="rgba(16,16,16,0.12)"/>
            <rect x="52" y="18" width="42" height="14" rx="3" fill="#FDFDFD" stroke="rgba(16,16,16,0.12)"/>
            <rect x="52" y="36" width="42" height="14" rx="3" fill="#FDFDFD" stroke="rgba(16,16,16,0.12)"/>
            <path d="M40 35 H52" stroke="#2A85FF" strokeWidth="1.2" fill="none"/>
            <path d="M40 15 H52 M40 52 H52" stroke="rgba(16,16,16,0.20)" strokeWidth="1" fill="none"/>
          </svg>
        </div>
        <div className="dc-ev-text">{ev.finding}</div>
      </div>
    );
  } else if (kind === 'doc') {
    const doc = p?.documents?.find(d => d.id === ev.ref?.doc);
    body = (
      <div className="dc-ev-preview-row">
        <div className="dc-ev-preview-thumb">
          {doc && window.DXPreview ? <DXPreview doc={doc} /> : <div className="dc-ev-thumb-fallback" />}
        </div>
        <div className="dc-ev-text">{ev.finding}</div>
      </div>
    );
  } else {
    body = <div className="dc-ev-text">{ev.finding}</div>;
  }

  const CardTag = href ? 'a' : 'div';
  return (
    <CardTag {...(href ? { href } : {})} className="dc-ev-card">
      <div className="dc-ev-head">
        <span className="dc-ev-kind mono">{kindLbl.toUpperCase()}</span>
        <span className="dc-ev-title">{ev.title}</span>
      </div>
      {body}
      {ev.ownerRef && (
        <div className="dc-ev-owner">
          <Avatar name={ev.ownerRef} size="xs" portrait={dcPortrait(ev.ownerRef)} />
          <span>{ev.ownerRef}</span>
        </div>
      )}
    </CardTag>
  );
}

// =========================================================
// DECISION DETAIL — the flagship composition
// =========================================================

function DCDetail({ data, decisionId }) {
  const dec = dcDecById(data, decisionId);
  if (!dec) {
    return (
      <div className="dc-detail">
        <a href="#/decisions/log" className="dv-back">
          <Icon name="chevronL" size={12} strokeWidth={2} /> <span>Back to Log</span>
        </a>
        <div className="dv-empty dv-empty-large" style={{ marginTop: 20 }}>Decision not found.</div>
      </div>
    );
  }

  const project = dcProject(dec.project);
  const chosen = (dec.options || []).find(o => o.chosen);
  const supersedes  = dec.supersedes && dcDecById(data, dec.supersedes);
  const supersededBy= dec.supersededBy && dcDecById(data, dec.supersededBy);

  // Related work items (My Work v2) that point to this decision — none
  // currently do explicitly, but we render the section defensively.
  const relatedWork = (data.workItems || []).filter(w => w.links?.decision === dec.id);

  return (
    <div className="dc-detail">
      <a href="#/decisions/log" className="dv-back">
        <Icon name="chevronL" size={12} strokeWidth={2} /> <span>Back to Log</span>
      </a>

      {/* --- Compact header --------------------------------------- */}
      <div className="dc-detail-head">
        <div className="dc-detail-head-l">
          <div className="dc-eyebrow">
            <Icon name="decisions" size={12} strokeWidth={1.75} />
            <span>Decision</span>
            <span className="dot-sep">·</span>
            <span className="mono">{dec.id.toUpperCase()}</span>
            {DC_TYPE[dec.type] && <>
              <span className="dot-sep">·</span>
              <span className="dc-type mono">{DC_TYPE[dec.type].short}</span>
            </>}
          </div>
          <h1 className="dc-detail-title">{dec.title}</h1>
          {dec.context && <p className="dc-detail-context">{dec.context}</p>}
          <div className="dc-detail-meta">
            {dcStateChip(dec.status)}
            {dec.decidedDate && (
              <span className="dc-detail-meta-item">
                <Icon name="clock" size={12} strokeWidth={1.75} />
                <span>Decided {dec.decidedDate}</span>
              </span>
            )}
            {dec.reviewDate && (
              <span className="dc-detail-meta-item">
                <Icon name="refresh" size={12} strokeWidth={1.75} />
                <span>Review {dec.reviewDate}</span>
              </span>
            )}
            {project && (
              <a href={`#/projects/${project.id}/overview`} className="dc-detail-meta-item link">
                <DCProjectGlyph project={project} />
                <span>{project.name}</span>
              </a>
            )}
          </div>
        </div>
        <div className="dc-detail-head-r">
          <div className="dc-detail-people">
            <div className="dc-person">
              <div className="dc-eyebrow-inline">Owner</div>
              <div className="dc-person-row">
                <Avatar name={dec.owner} size="sm" portrait={dcPortrait(dec.owner)} />
                <span>{dec.owner}</span>
              </div>
            </div>
            {dec.decisionMaker && dec.decisionMaker !== dec.owner && (
              <div className="dc-person">
                <div className="dc-eyebrow-inline">Decided by</div>
                <div className="dc-person-row">
                  <Avatar name={dec.decisionMaker} size="sm" portrait={dcPortrait(dec.decisionMaker)} />
                  <span>{dec.decisionMaker}</span>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* --- Supersession banner if applicable ------------------- */}
      {(supersedes || supersededBy) && (
        <div className="dc-super-banner">
          {supersedes && (
            <div className="dc-super-line">
              <span className="dc-eyebrow-inline">Supersedes</span>
              <a href={`#/decisions/dec/${supersedes.id}`} className="dc-super-link">
                <Icon name="refresh" size={11} strokeWidth={1.75} />
                <span>{supersedes.title}</span>
              </a>
            </div>
          )}
          {supersededBy && (
            <div className="dc-super-line">
              <span className="dc-eyebrow-inline">Superseded by</span>
              <a href={`#/decisions/dec/${supersededBy.id}`} className="dc-super-link">
                <Icon name="refresh" size={11} strokeWidth={1.75} />
                <span>{supersededBy.title}</span>
              </a>
            </div>
          )}
        </div>
      )}

      {/* --- Two-column body ------------------------------------- */}
      <div className="dc-detail-grid">

        {/* Left column — the Decision Story */}
        <div className="dc-detail-main">

          {/* QUESTION */}
          {dec.question && (
            <section className="dc-story dc-story-question">
              <div className="dc-story-eyebrow">
                <span className="dc-story-num mono">01</span>
                <span>Question</span>
              </div>
              <p className="dc-story-question-text">{dec.question}</p>
            </section>
          )}

          {/* EVIDENCE */}
          {(dec.evidence || []).length > 0 && (
            <section className="dc-story">
              <div className="dc-story-eyebrow">
                <span className="dc-story-num mono">02</span>
                <span>Evidence</span>
                <span className="dc-story-count mono">{dec.evidence.length}</span>
              </div>
              <div className="dc-ev-grid">
                {dec.evidence.map(ev => (
                  <DCEvidenceCard key={ev.id} ev={ev} projectId={dec.project} />
                ))}
              </div>
            </section>
          )}

          {/* OPTIONS */}
          {(dec.options || []).length > 0 && (
            <section className="dc-story">
              <div className="dc-story-eyebrow">
                <span className="dc-story-num mono">03</span>
                <span>Options considered</span>
              </div>
              <div className="dc-opts">
                {dec.options.map((opt, i) => (
                  <div key={opt.id} className={`dc-opt${opt.chosen ? ' dc-opt-chosen' : ''}`}>
                    <div className="dc-opt-head">
                      <span className="dc-opt-letter mono">Option {String.fromCharCode(65 + i)}</span>
                      {opt.chosen && (
                        <span className="dc-opt-pin">
                          <Icon name="pin" size={10} strokeWidth={2} />
                          <span>Chosen</span>
                        </span>
                      )}
                    </div>
                    <div className="dc-opt-title">{opt.title}</div>
                    {opt.summary && <p className="dc-opt-summary">{opt.summary}</p>}
                    <div className="dc-opt-cols">
                      {opt.pros?.length > 0 && (
                        <div className="dc-opt-col">
                          <div className="dc-eyebrow-inline">Pros</div>
                          <ul>{opt.pros.map((p, i) => <li key={i}>{p}</li>)}</ul>
                        </div>
                      )}
                      {opt.tradeoffs?.length > 0 && (
                        <div className="dc-opt-col">
                          <div className="dc-eyebrow-inline">Tradeoffs</div>
                          <ul className="dc-opt-tradeoffs">{opt.tradeoffs.map((p, i) => <li key={i}>{p}</li>)}</ul>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </section>
          )}

          {/* DECISION — the strongest typographic element */}
          {chosen && dec.status !== 'open' && (
            <section className="dc-story dc-story-decision">
              <div className="dc-story-eyebrow">
                <span className="dc-story-num mono">04</span>
                <span>Decision</span>
              </div>
              <div className="dc-decision-block">
                {chosen.title && chosen.summary
                  ? <>
                      <div className="dc-decision-h">{chosen.title}</div>
                      <p className="dc-decision-p">{chosen.summary}</p>
                    </>
                  : <div className="dc-decision-h">{chosen.title}</div>}
              </div>
            </section>
          )}

          {/* RATIONALE */}
          {dec.rationale && (
            <section className="dc-story">
              <div className="dc-story-eyebrow">
                <span className="dc-story-num mono">05</span>
                <span>Rationale</span>
              </div>
              <p className="dc-rationale">{dec.rationale}</p>
            </section>
          )}

          {/* CONSEQUENCES */}
          {(dec.consequences || []).length > 0 && (
            <section className="dc-story">
              <div className="dc-story-eyebrow">
                <span className="dc-story-num mono">06</span>
                <span>Consequences</span>
              </div>
              <div className="dc-cons">
                <div className="dc-cons-col">
                  <div className="dc-eyebrow-inline">What changes now</div>
                  <ul>{dec.consequences.filter(c => c.kind === 'change').map((c, i) => <li key={i}>{c.note}</li>)}</ul>
                </div>
                {dec.consequences.some(c => c.kind === 'accept') && (
                  <div className="dc-cons-col">
                    <div className="dc-eyebrow-inline">What we intentionally accept</div>
                    <ul className="dc-cons-accept">{dec.consequences.filter(c => c.kind === 'accept').map((c, i) => <li key={i}>{c.note}</li>)}</ul>
                  </div>
                )}
              </div>
            </section>
          )}

          {/* IMPACT MAP */}
          {dec.impact?.nodes?.length > 0 && (
            <section className="dc-story">
              <div className="dc-story-eyebrow">
                <span className="dc-story-num mono">07</span>
                <span>Impact</span>
              </div>
              {dec.impact.summary && <p className="dc-impact-summary">{dec.impact.summary}</p>}
              <div className="dc-impact-card dc-impact-card-flat">
                <DCImpactMap flagship={dec} />
              </div>
            </section>
          )}
        </div>

        {/* Right rail */}
        <div className="dc-detail-rail">
          {/* Participants */}
          {dec.participants?.length > 0 && (
            <div className="dc-rail-card">
              <div className="dc-card-head"><h4>Participants</h4></div>
              <div className="dc-participants">
                {dec.participants.map(name => (
                  <div key={name} className="dc-participant">
                    <Avatar name={name} size="xs" portrait={dcPortrait(name)} />
                    <span>{name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Related canonical */}
          <div className="dc-rail-card">
            <div className="dc-card-head"><h4>Related</h4></div>
            <DCLinkedChips links={dec.links} impactNodes={dec.impact?.nodes} />
          </div>

          {/* Related work */}
          {relatedWork.length > 0 && (
            <div className="dc-rail-card">
              <div className="dc-card-head"><h4>Related work</h4></div>
              <div className="dc-list">
                {relatedWork.map(w => (
                  <a key={w.id} href={`#/my-work/item/${w.id}`} className="dc-related-work">
                    <Icon name="work" size={13} strokeWidth={1.75} />
                    <span className="truncate">{w.title}</span>
                  </a>
                ))}
              </div>
            </div>
          )}

          {/* At a glance */}
          <div className="dc-rail-card">
            <div className="dc-card-head"><h4>At a glance</h4></div>
            <div className="dc-glance">
              {dec.createdDate && <div className="dc-glance-row"><span>Created</span><b>{dec.createdDate}</b></div>}
              {dec.decidedDate && <div className="dc-glance-row"><span>Decided</span><b>{dec.decidedDate}</b></div>}
              {dec.reviewDate  && <div className="dc-glance-row"><span>Review</span><b>{dec.reviewDate}</b></div>}
              {DC_TYPE[dec.type] && <div className="dc-glance-row"><span>Type</span><b>{DC_TYPE[dec.type].label}</b></div>}
              <div className="dc-glance-row"><span>Status</span>{dcStateChip(dec.status)}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// =========================================================
// ROUTER SHELL
// -----------------------------------------------------------------
// Sub-route shape:
//   /decisions              → Overview
//   /decisions/log          → Log
//   /decisions/reviews      → Reviews
//   /decisions/dec/:id      → Decision Detail
// =========================================================

function DecisionsWorkspaceV2({ data, subId, sub2 }) {
  const isDetail = subId === 'dec';
  const view = isDetail
    ? 'dec'
    : (subId === 'log' ? 'log' : (subId === 'reviews' ? 'reviews' : 'overview'));

  const setView = (v) => {
    location.hash = v === 'overview' ? '#/decisions' : `#/decisions/${v}`;
  };
  const openDecision = (id) => {
    location.hash = `#/decisions/dec/${id}`;
  };

  // Aggregate counts for the shell summary (Overview only — Log has its
  // own filter chips with counts, Reviews has section counts).
  const all = data.decisions || [];
  const openN     = all.filter(d => d.status === 'open').length;
  const decidedN  = all.filter(d => d.status === 'decided').length;
  const reviewsN  = all.filter(d => d.status === 'decided' && d.reviewDate).length;

  return (
    <main className="main dc-root" data-screen-label={`Decisions · ${view}`}>
      {!isDetail && (
        <div className="mw-head">
          <div>
            <h1 className="mw-h1">Decisions</h1>
            <p className="mw-h1-sub">Every canonical product, design, technical, commercial, and operational decision — with the evidence and impact behind it.</p>
            {view === 'overview' && (
              <div className="dc-shell-summary">
                <b>{openN}</b> open <span className="dot-sep">·</span>
                <b>{decidedN}</b> decided <span className="dot-sep">·</span>
                <b>{reviewsN}</b> up for review
              </div>
            )}
          </div>
          <div className="mw-head-right">
            <div className="dv-seg" role="tablist" aria-label="Decisions views">
              {[
                { k: 'overview', label: 'Overview' },
                { k: 'log',      label: 'Log'      },
                { k: 'reviews',  label: 'Reviews'  },
              ].map(t => (
                <button key={t.k} role="tab" aria-selected={view === t.k}
                        className={`dv-seg-btn${view === t.k ? ' active' : ''}`}
                        onClick={() => setView(t.k)}>
                  {t.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {view === 'overview' && <DCOverview data={data} onOpen={openDecision} onNavigate={setView} />}
      {view === 'log'      && <DCLog      data={data} onOpen={openDecision} />}
      {view === 'reviews'  && <DCReviews  data={data} onOpen={openDecision} />}
      {view === 'dec'      && <DCDetail   data={data} decisionId={sub2} />}
    </main>
  );
}

Object.assign(window, {
  DecisionsWorkspaceV2,
  DCRow, DCImpactMap, DCEvidenceCard,
});
