// Features Workspace — Overview + Detail

function FeaturesSection({ pdata, featureId }) {
  // If featureId present, show the detail view; otherwise show the overview.
  if (featureId) {
    const detail = pdata.featureDetail && pdata.featureDetail[featureId];
    if (!detail) {
      return (
        <Card>
          <EmptyState
            illustration={<NoResultsIllus size={140} />}
            title="We don't have a full workspace built for that feature yet"
            body="The Smart Project Brief has the deepest sample content — open it to explore."
            action={<button className="btn btn-primary btn-sm" onClick={() => location.hash = `#/projects/${pdata.id}/features/f-brief`}>Open Smart Project Brief</button>}
          />
        </Card>
      );
    }
    return <FeatureDetail pdata={pdata} detail={detail} />;
  }
  return <FeaturesOverview pdata={pdata} />;
}

// =========================================================
// FEATURES OVERVIEW
// =========================================================
function FeaturesOverview({ pdata }) {
  const [view, setView] = React.useState('overview'); // overview | list | board | timeline
  const [group, setGroup] = React.useState('stage');  // stage | status | priority
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const [aiOpen, setAiOpen] = React.useState(false);

  // Summary counts
  const cnts = React.useMemo(() => {
    const c = { all: 0, building: 0, review: 0, design: 0, blocked: 0, done: 0 };
    pdata.features.forEach(f => {
      c.all += 1;
      if (f.blocked) { c.blocked += 1; return; }
      if (f.status === 'Building' || f.status === 'On track' || f.status === 'At risk') c.building += 1;
      else if (f.status === 'In review') c.review += 1;
      else if (f.status === 'Design') c.design += 1;
      else if (f.status === 'Done') c.done += 1;
    });
    return c;
  }, [pdata.features]);

  // Filter + search
  const filtered = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    return pdata.features.filter(f => {
      if (statusFilter === 'building' && !(f.status === 'Building' || f.status === 'On track' || f.status === 'At risk') && !f.blocked) return false;
      if (statusFilter === 'review'   && f.status !== 'In review') return false;
      if (statusFilter === 'design'   && f.status !== 'Design') return false;
      if (statusFilter === 'blocked'  && !f.blocked) return false;
      if (statusFilter === 'done'     && f.status !== 'Done') return false;
      if (q) {
        const h = [f.title, f.purpose, f.owner, f.status].join(' ').toLowerCase();
        if (!h.includes(q)) return false;
      }
      return true;
    });
  }, [pdata.features, statusFilter, query]);

  // Group by
  const groups = React.useMemo(() => {
    if (group === 'stage') {
      const order = ['Discovery','Product Definition','UI/UX','Development Foundation','Building','Review','Testing','Launch'];
      const byStage = {};
      filtered.forEach(f => {
        const k = f.stage || 'Uncategorized';
        (byStage[k] = byStage[k] || []).push(f);
      });
      // Turn into ordered array
      const knownStageMap = {};
      pdata.stages.forEach(s => { knownStageMap[s.name] = s; });
      const alias = { 'UI/UX': 'UI / UX', 'Building': 'Core Implementation' };
      return Object.entries(byStage).map(([key, items]) => {
        const stageObj = knownStageMap[alias[key]] || knownStageMap[key];
        return { key, items, stageObj, total: items.length };
      }).sort((a, b) => (a.stageObj?.n || 99) - (b.stageObj?.n || 99));
    }
    if (group === 'status') {
      const bySt = {};
      filtered.forEach(f => {
        const k = f.blocked ? 'Blocked' : f.status;
        (bySt[k] = bySt[k] || []).push(f);
      });
      return Object.entries(bySt).map(([key, items]) => ({ key, items, total: items.length }));
    }
    if (group === 'priority') {
      const byP = {};
      filtered.forEach(f => {
        (byP[f.priority] = byP[f.priority] || []).push(f);
      });
      return ['P0','P1','P2'].filter(k => byP[k]).map(k => ({ key: k, items: byP[k], total: byP[k].length }));
    }
    return [{ key: 'All', items: filtered, total: filtered.length }];
  }, [filtered, group, pdata.stages]);

  return (
    <div>
      {/* Header */}
      <div className="feat-page-head">
        <div className="titleblock">
          <div className="t">
            Features
            <span style={{ fontSize: 16, color: 'var(--text-tertiary)', fontWeight: 500 }}>{pdata.features.length}</span>
          </div>
          <div className="sub">
            Features move through the project's stages, drawing on research, decisions, and design.
          </div>
        </div>
        <div className="actions">
          <button className="btn btn-white btn-sm ai-suggest-btn" onClick={() => setAiOpen(v => !v)}>
            <Icon name="spark" size={13} strokeWidth={1.75} style={{ color: 'var(--text-tertiary)' }} />
            <span>Suggest</span>
          </button>
          <button className="btn btn-primary btn-sm">
            <Icon name="plus" size={14} strokeWidth={2} />
            <span>Add feature</span>
          </button>
        </div>
      </div>

      {/* Slim status distribution — a single stacked bar showing the mix at a glance */}
      <FeatureStatusDistribution cnts={cnts} onFilter={setStatusFilter} active={statusFilter} />

      {/* Summary strip + view switcher */}
      <div className="feat-controls" style={{ marginTop: 4 }}>
        <div className="feat-summary">
          <div className={`feat-summary-item${statusFilter === 'all' ? ' active' : ''}`} onClick={() => setStatusFilter('all')}>
            <span className="k">All</span>
            <span className="v tabular">{cnts.all}</span>
          </div>
          <div className={`feat-summary-item${statusFilter === 'building' ? ' active' : ''}`} onClick={() => setStatusFilter('building')}>
            <span className="k"><span className="dot green" />In progress</span>
            <span className="v tabular">{cnts.building}</span>
          </div>
          <div className={`feat-summary-item${statusFilter === 'review' ? ' active' : ''}`} onClick={() => setStatusFilter('review')}>
            <span className="k"><span className="dot blue" />In review</span>
            <span className="v tabular">{cnts.review}</span>
          </div>
          <div className={`feat-summary-item${statusFilter === 'design' ? ' active' : ''}`} onClick={() => setStatusFilter('design')}>
            <span className="k"><span className="dot purple" />Design</span>
            <span className="v tabular">{cnts.design}</span>
          </div>
          <div className={`feat-summary-item${statusFilter === 'blocked' ? ' active' : ''}`} onClick={() => setStatusFilter('blocked')}>
            <span className="k"><span className="dot red" />Blocked</span>
            <span className="v tabular">{cnts.blocked}</span>
          </div>
          <div className={`feat-summary-item${statusFilter === 'done' ? ' active' : ''}`} onClick={() => setStatusFilter('done')}>
            <span className="k"><span className="dot gray" />Done</span>
            <span className="v tabular">{cnts.done}</span>
          </div>
        </div>
        <div className="spacer" />
        <div className="tabs">
          <button className={`tab${view === 'overview' ? ' active' : ''}`} onClick={() => setView('overview')}><Icon name="grid" size={13} strokeWidth={1.75}/><span>Overview</span></button>
          <button className={`tab${view === 'list' ? ' active' : ''}`}     onClick={() => setView('list')}><Icon name="list" size={13} strokeWidth={1.75}/><span>List</span></button>
          <button className={`tab${view === 'board' ? ' active' : ''}`}    onClick={() => setView('board')}><Icon name="kanban" size={13} strokeWidth={1.75}/><span>Board</span></button>
          <button className="tab" style={{ opacity: 0.55, cursor: 'not-allowed' }} title="Timeline · coming soon"><Icon name="chartLine" size={13} strokeWidth={1.75}/><span>Timeline</span></button>
        </div>
      </div>

      <div className="feat-controls">
        <Input placeholder="Search features, owners, purposes…" value={query} onChange={setQuery} leadIcon={<Icon name="search" size={16} strokeWidth={1.75}/>} style={{ minWidth: 260, flex: '0 1 340px' }} />
        <div className="spacer" />
        <span style={{ fontSize: 12, color: 'var(--text-tertiary)', letterSpacing: '-0.02em' }}>Group by</span>
        <div className="tabs">
          <button className={`tab${group === 'stage' ? ' active' : ''}`}    onClick={() => setGroup('stage')}>Stage</button>
          <button className={`tab${group === 'status' ? ' active' : ''}`}   onClick={() => setGroup('status')}>Status</button>
          <button className={`tab${group === 'priority' ? ' active' : ''}`} onClick={() => setGroup('priority')}>Priority</button>
        </div>
      </div>

      {/* AI suggestion (dismissible) — restrained, no gradient */}
      {aiOpen && (
        <div className="feat-ai-quiet" style={{ marginTop: 8 }}>
          <div className="g"><Icon name="spark" size={14} strokeWidth={1.75}/></div>
          <div className="body">
            <div className="t">3 features suggested from your research &amp; decisions</div>
            <div className="s">Brief freshness widget · N/A section marker · Auto-pull change log — nothing changes until you accept.</div>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-white btn-sm">Review</button>
            <button className="btn btn-white btn-sm" onClick={() => setAiOpen(false)} aria-label="Dismiss"><Icon name="x" size={13} strokeWidth={2}/></button>
          </div>
        </div>
      )}

      {/* Groups */}
      {(view === 'overview' || view === 'list') && groups.map(g => (
        <div className="feat-group" key={g.key} style={{ marginTop: 12 }}>
          <div className="feat-group-head">
            <div className={`num${groupNumTone(g)}`}>{groupNumLabel(g)}</div>
            <div>
              <div className="name">
                {g.stageObj?.name || g.key}
                <span className="cnt">· {g.total}</span>
                {g.stageObj && (
                  <span className="stage-tag">Stage {String(g.stageObj.n).padStart(2, '0')}</span>
                )}
              </div>
              {g.stageObj && <div className="name-desc">{g.stageObj.goal}</div>}
            </div>
            <div className="grp-progress">
              <span className="n">{Math.round(g.items.reduce((s, f) => s + f.progress, 0) / g.items.length)}% avg</span>
              <div className="bar">
                <ProgressBar value={Math.round(g.items.reduce((s, f) => s + f.progress, 0) / g.items.length)} tone={g.stageObj?.status === 'now' ? 'blue' : g.stageObj?.status === 'done' ? 'green' : 'blue'} />
              </div>
            </div>
          </div>
          {g.items.map(f => <FeatureRow key={f.id} f={f} projectId={pdata.id} />)}
        </div>
      ))}

      {view === 'board' && <FeatureBoard features={pdata.features} projectId={pdata.id} />}
    </div>
  );
}

// -----------------------------------------------------------------
// Board view — 4 columns keyed off feature status. Cards remain
// compact and reuse the same feature model. No drag chrome, no
// swimlanes, no per-card actions — just fast scannable columns.
// -----------------------------------------------------------------
function FeatureBoard({ features, projectId }) {
  // Map feature.status → column key
  const columnFor = (f) => {
    if (f.blocked)                                            return 'in-progress'; // blocked features still live in their working column, badge shows blocker
    const s = (f.status || '').toLowerCase();
    if (s.includes('review'))                                 return 'in-review';
    if (s === 'building' || s.includes('progress') ||
        s.includes('design') || s === 'on track')             return 'in-progress';
    if (s === 'done')                                         return 'done';
    return 'planned';
  };

  const cols = [
    { key: 'planned',     label: 'Planned',     dot: 'gray',   tone: 'var(--text-muted)' },
    { key: 'in-progress', label: 'In Progress', dot: 'blue',   tone: 'var(--primary-01)' },
    { key: 'in-review',   label: 'In Review',   dot: 'purple', tone: 'var(--primary-04)' },
    { key: 'done',        label: 'Done',        dot: 'green',  tone: 'var(--success-solid)' },
  ];
  const buckets = Object.fromEntries(cols.map(c => [c.key, []]));
  features.forEach(f => { buckets[columnFor(f)].push(f); });

  return (
    <div className="feat-board">
      {cols.map(c => (
        <div className="fb-col" key={c.key}>
          <div className="fb-col-head">
            <span className={`fb-dot ${c.dot}`} />
            <span className="fb-label">{c.label}</span>
            <span className="fb-count mono">{buckets[c.key].length}</span>
          </div>
          <div className="fb-col-body">
            {buckets[c.key].length === 0 && (
              <div className="fb-empty">Nothing here yet.</div>
            )}
            {buckets[c.key].map(f => (
              <a
                href={`#/projects/${projectId}/features/${f.id}`}
                className={`fb-card${f.blocked ? ' blocked' : ''}`}
                key={f.id}
              >
                <div className="fb-card-head">
                  <span className={`fb-prio ${f.priority}`}>{f.priority}</span>
                  <span className="fb-stage mono">S{String(f.stageN).padStart(2, '0')}</span>
                </div>
                <div className="fb-card-title">{f.title}</div>
                <div className="fb-card-purpose">{f.purpose}</div>
                {f.blocked && (
                  <div className="fb-card-blocker">
                    <Icon name="circleAlert" size={11} strokeWidth={2}/>
                    <span>{f.blocker || 'Blocked'}</span>
                  </div>
                )}
                <div className="fb-card-foot">
                  <div className="fb-progress">
                    <div className="fb-progress-bar">
                      <div className="fb-progress-fill" style={{ width: `${f.progress}%`, background: c.tone }} />
                    </div>
                    <span className="fb-progress-num mono">{f.progress}%</span>
                  </div>
                  <Avatar name={f.owner} size="xs" />
                </div>
              </a>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function groupNumLabel(g) {
  if (g.stageObj) return String(g.stageObj.n).padStart(2, '0');
  if (g.key === 'Blocked') return '!';
  if (['P0','P1','P2'].includes(g.key)) return g.key;
  return g.key[0];
}
function groupNumTone(g) {
  if (g.stageObj?.status === 'done') return ' done';
  if (g.stageObj?.status === 'now')  return ' now';
  return '';
}

// -------- Feature row --------
// -----------------------------------------------------------------
// FeatureStatusDistribution — a compact single stacked bar giving
// the user the "mix" of the project's features at a glance. Reuses
// the same tones as the summary strip; clickable segments filter.
// -----------------------------------------------------------------
function FeatureStatusDistribution({ cnts, onFilter, active }) {
  const total = cnts.all || 1;
  const segments = [
    { key: 'building', label: 'In progress', tone: 'var(--success-solid)', value: cnts.building },
    { key: 'review',   label: 'In review',   tone: 'var(--primary-01)',    value: cnts.review },
    { key: 'design',   label: 'Design',      tone: 'var(--primary-04)',    value: cnts.design },
    { key: 'blocked',  label: 'Blocked',     tone: 'var(--danger-solid)',  value: cnts.blocked },
    { key: 'done',     label: 'Done',        tone: 'var(--text-muted)',    value: cnts.done },
  ].filter(s => s.value > 0);

  return (
    <div className="feat-dist">
      <div className="feat-dist-head">
        <span className="fd-eyebrow">Status distribution</span>
        <span className="fd-total mono">{cnts.all} features</span>
      </div>
      <div className="feat-dist-bar" role="img" aria-label={`${cnts.all} features by status`}>
        {segments.map(s => (
          <button
            key={s.key}
            className={`feat-dist-seg${active === s.key ? ' active' : ''}`}
            onClick={() => onFilter(active === s.key ? 'all' : s.key)}
            style={{ flex: s.value, background: s.tone }}
            aria-label={`${s.label}: ${s.value}`}
            title={`${s.label} · ${s.value}`}
          />
        ))}
      </div>
    </div>
  );
}

function FeatureRow({ f, projectId }) {
  const toneMap = {
    'On track':  { label: 'green',  prog: 'green' },
    'Building':  { label: 'yellow', prog: 'warn'  },
    'In review': { label: 'blue',   prog: 'blue'  },
    'Design':    { label: 'purple', prog: 'purple'},
    'At risk':   { label: 'red',    prog: 'red'   },
    'Blocked':   { label: 'red',    prog: 'red'   },
    'Discovery': { label: 'blue',   prog: 'blue'  },
  };
  const t = toneMap[f.status] || { label: 'gray', prog: 'blue' };

  return (
    <a className="feat-row" href={`#/projects/${projectId}/features/${f.id}`}>
      <div className="fr-lead">
        <span className={`fr-priority ${f.priority}`}>{f.priority}</span>
      </div>
      <div className="fr-body">
        <div className="fr-line1">
          <span className="fr-name">{f.title}</span>
          {f.blocked ? (
            <span className="fr-blocker"><Icon name="block" size={11} strokeWidth={2}/> Blocked</span>
          ) : (
            <Label tone={t.label} dot size="sm">{f.status}</Label>
          )}
        </div>
        <div className="fr-purpose">{f.purpose}</div>
        <div className="fr-rel">
          {f.links.research > 0 && <span className="fr-rc">Research · {f.links.research}</span>}
          {f.links.decision > 0 && <span className="fr-rc">Decisions · {f.links.decision}</span>}
          {f.links.design > 0   && <span className="fr-rc"><span className="fr-rc-dot green"/>Design</span>}
          {f.blocker && <span className="fr-rc red"><Icon name="circleAlert" size={11} strokeWidth={2}/> {f.blocker}</span>}
        </div>
      </div>
      <div className="fr-col">
        <div className="k">Current stage</div>
        <div className="v">Stage {String(f.stageN).padStart(2, '0')} · {f.stage}</div>
      </div>
      <div className="fr-col">
        <div className="k">Target</div>
        <div className="v" style={{ color: f.blocked ? 'var(--danger-solid)' : 'var(--text-primary)' }}>{f.target}</div>
      </div>
      <div className="fr-col fr-progress">
        <div className="row">
          <span className="n tabular">{f.progress}%</span>
          <span className="m"><Avatar name={f.owner} size="xs" /></span>
        </div>
        <ProgressBar value={f.progress} tone={t.prog} />
        <div className="m truncate">{f.owner.split(' ')[0]}</div>
      </div>
      <Icon name="chevronRight" size={14} strokeWidth={2} style={{ color: 'var(--text-tertiary)' }}/>
    </a>
  );
}

// =========================================================
// FEATURE DETAIL WORKSPACE
// =========================================================
// ------------------------------------------------------------
// Feature ↔ Plan/Stage stripe — the connection made explicit
// as a compact 3-node timeline. Sits between the feature header
// and the two-column body so it's the first thing you read.
// ------------------------------------------------------------
function FeatureStageStripe({ pdata, d }) {
  // Resolve current + next stage from pdata for the summary line.
  const stages    = pdata.stages || [];
  const cur       = stages.find(s => s.n === d.stageN);
  const nextStage = stages.find(s => s.n === (d.nextStageN || d.stageN + 1));
  // Reuse the exact Stage visual language from Phase 8 (HorizontalStages).
  const stageNodes = stages.map(s => ({ n: s.n, name: s.name, status: s.status }));

  return (
    <div className="feat-journey">
      <div className="fj-head">
        <div className="fj-eyebrow">
          <Icon name="stages" size={11} strokeWidth={1.75} style={{ color: 'var(--primary-01)' }} />
          <span>Feature journey · linked to project stages</span>
        </div>
        <div className="fj-summary">
          <span>Current project stage <b>{cur?.name}</b></span>
          <span className="fj-dot" />
          <span>Feature state <b>In Design</b></span>
          {nextStage && <><span className="fj-dot" /><span>Next <b>{nextStage.name}</b></span></>}
        </div>
        <a href={`#/projects/${pdata.id}/plan`} className="fj-open">
          <span>Open plan</span>
          <Icon name="chevronRight" size={12} strokeWidth={2}/>
        </a>
      </div>
      <div className="fj-track">
        <HorizontalStages stages={stageNodes} dense={true} active={cur?.n} />
      </div>
    </div>
  );
}

// -----------------------------------------------------------------
// ReadinessComposition — the unified Research + Design + Development
// surface. Answers "what's ready, what's missing, what happens next"
// as one composed block instead of three flat cards.
// -----------------------------------------------------------------
function ReadinessComposition({ pdata, d }) {
  const [aiOpen, setAiOpen] = React.useState(false);
  const r = d.readiness;
  if (!r) return null;

  const gateInfo = {
    ready:     { label: 'Ready for next stage',     tone: 'green',  icon: 'check' },
    attention: { label: 'Almost ready',             tone: 'yellow', icon: 'clock' },
    blocked:   { label: 'Blocked from next stage',  tone: 'red',    icon: 'circleAlert' },
  }[r.gate] || { label: 'Not ready', tone: 'gray', icon: 'clock' };

  // Route pillars to the correct project section on click.
  const sectionFor = {
    research: 'research',
    design:   'design',
    dev:      'development',
  };

  return (
    <div className="fd-readiness">
      <div className="fdr-head">
        <div className="fdr-eyebrow">
          <Icon name="target" size={11} strokeWidth={2} style={{ color: 'var(--primary-01)' }} />
          <span>Readiness · for Stage {String(r.nextStageN).padStart(2, '0')} · {r.nextStageName}</span>
        </div>
        <div className={`fdr-gate fdr-gate-${gateInfo.tone}`}>
          <Icon name={gateInfo.icon} size={12} strokeWidth={2}/>
          <span>{gateInfo.label}</span>
          <span className="fdr-gate-note">· {r.gateNote}</span>
        </div>
        <button className="fdr-check" onClick={() => setAiOpen(v => !v)}>
          <Icon name="spark" size={11} strokeWidth={1.75} style={{ color: 'var(--text-tertiary)' }}/>
          <span>Check next-stage readiness</span>
        </button>
      </div>

      {/* Pillars row */}
      <div className="fdr-pillars">
        {r.pillars.map(p => {
          const tone = (window.MYGENI_MISSION_TONES || {})[p.tone] || (window.MYGENI_MISSION_TONES || {}).blue;
          const stateChip = {
            ready:      { label: p.stateLabel || 'Ready',      tone: 'green'  },
            'in-review': { label: p.stateLabel || 'In review', tone: 'blue' },
            'in-progress': { label: p.stateLabel || 'In progress', tone: 'blue' },
            attention:  { label: p.stateLabel || 'Not ready',  tone: 'yellow' },
            blocked:    { label: p.stateLabel || 'Blocked',    tone: 'red' },
            'not-started': { label: p.stateLabel || 'Not started', tone: 'gray' },
          }[p.state] || { label: p.stateLabel || 'Pending', tone: 'gray' };
          return (
            <a
              key={p.key}
              href={`#/projects/${pdata.id}/${sectionFor[p.key] || 'overview'}`}
              className={`fdr-pillar fdr-state-${p.state}`}
            >
              <div className="fdr-pillar-head">
                <div className="fdr-pillar-icon" style={{ background: tone.bg, color: tone.fg }}>
                  <Icon name={p.icon} size={16} strokeWidth={1.75}/>
                </div>
                <div className="fdr-pillar-title-block">
                  <div className="fdr-pillar-title">{p.label}</div>
                  <Label tone={stateChip.tone} dot size="sm">{stateChip.label}</Label>
                </div>
              </div>
              <div className="fdr-pillar-meter">
                <div className="fdr-meter-track">
                  <div className="fdr-meter-fill" style={{ width: `${(p.done / Math.max(p.total, 1)) * 100}%`, background: tone.fg }} />
                </div>
                <span className="mono fdr-meter-num">{p.done}/{p.total}</span>
              </div>
              <div className="fdr-pillar-summary">{p.summary}</div>
            </a>
          );
        })}
      </div>

      {/* Previews strip — the most representative work across pillars */}
      {r.previews && r.previews.length > 0 && (
        <div className="fdr-previews">
          {r.previews.map((prv, i) => {
            const tone = (window.MYGENI_MISSION_TONES || {})[prv.tone] || (window.MYGENI_MISSION_TONES || {}).blue;
            return (
              <a
                key={i}
                href={`#/projects/${pdata.id}/${prv.kind === 'research' ? 'research' : prv.kind === 'design' ? 'design' : 'development'}`}
                className="fdr-prev"
              >
                <div className="fdr-prev-visual" style={{ background: tone.bg }}>
                  <ReadinessPreviewMock kind={prv.mock} tone={tone} />
                  <span className="fdr-prev-badge" style={{ color: tone.fg }}>{prv.label}</span>
                </div>
                <div className="fdr-prev-meta">
                  <div className="fdr-prev-title">{prv.title}</div>
                  <div className="fdr-prev-sub">{prv.meta}</div>
                </div>
              </a>
            );
          })}
        </div>
      )}

      {/* Inline AI panel */}
      {aiOpen && (
        <div className="fdr-ai">
          <div className="fdr-ai-head">
            <div className="fdr-ai-title">Readiness check for {r.nextStageName}</div>
            <a className="fdr-ai-close" onClick={() => setAiOpen(false)}><Icon name="x" size={13} strokeWidth={2}/></a>
          </div>
          <div className="fdr-ai-list">
            <div className="fdr-ai-row done"><Icon name="check" size={12} strokeWidth={2.5}/><span><b>Research</b> · all 3 findings linked and cited in the brief.</span></div>
            <div className="fdr-ai-row done"><Icon name="check" size={12} strokeWidth={2.5}/><span><b>Design</b> · 4 of 5 screens approved.</span></div>
            <div className="fdr-ai-row miss"><Icon name="clock" size={12} strokeWidth={2}/><span><b>Design</b> · sign-off from Alireza still pending on the v3 shell.</span></div>
            <div className="fdr-ai-row miss"><Icon name="circleAlert" size={12} strokeWidth={2}/><span><b>Development</b> · integration blocked on decisions-inbox events schema (R-03).</span></div>
          </div>
          <div className="fdr-ai-foot">Two items remaining. Once cleared, this feature is ready to enter <b>Development Foundation</b>.</div>
        </div>
      )}
    </div>
  );
}

// Small SVG mocks used inside the readiness previews strip.
function ReadinessPreviewMock({ kind, tone }) {
  if (kind === 'brief-shell') {
    return (
      <svg viewBox="0 0 220 120" width="100%" height="100%" preserveAspectRatio="none">
        <rect x="12" y="12" width="60" height="96" rx="6" fill="rgba(255,255,255,0.55)"/>
        <rect x="14" y="16" width="40" height="4" fill="rgba(16,16,16,0.20)" rx="2"/>
        {[26,36,46,56,66,76,86].map(y => (<rect key={y} x="14" y={y} width="52" height="3" fill="rgba(16,16,16,0.10)" rx="2"/>))}
        <rect x="80" y="12" width="128" height="96" rx="6" fill="rgba(255,255,255,0.75)"/>
        <rect x="86" y="18" width="80" height="5" fill="rgba(16,16,16,0.25)" rx="2"/>
        <rect x="86" y="30" width="54" height="3" fill="rgba(16,16,16,0.14)" rx="2"/>
        <rect x="86" y="42" width="116" height="3" fill="rgba(16,16,16,0.10)" rx="2"/>
        <rect x="86" y="50" width="106" height="3" fill="rgba(16,16,16,0.10)" rx="2"/>
        <rect x="86" y="58" width="96" height="3" fill="rgba(16,16,16,0.10)" rx="2"/>
        <rect x="86" y="70" width="60" height="12" rx="3" fill={tone.fg} opacity="0.20"/>
        <rect x="86" y="88" width="116" height="3" fill="rgba(16,16,16,0.10)" rx="2"/>
        <rect x="86" y="96" width="90" height="3" fill="rgba(16,16,16,0.10)" rx="2"/>
      </svg>
    );
  }
  if (kind === 'brief-dec') {
    return (
      <svg viewBox="0 0 220 120" width="100%" height="100%" preserveAspectRatio="none">
        {[16,44,72,100].map((y, i) => (
          <g key={i}>
            <rect x="14" y={y} width="192" height="20" rx="6" fill="rgba(255,255,255,0.75)"/>
            <circle cx="26" cy={y+10} r="4" fill={i === 0 ? 'var(--success-solid)' : 'rgba(16,16,16,0.20)'}/>
            <rect x="38" y={y+6} width="100" height="4" fill="rgba(16,16,16,0.24)" rx="2"/>
            <rect x="38" y={y+13} width="66" height="3" fill="rgba(16,16,16,0.10)" rx="2"/>
            <rect x="160" y={y+7} width="36" height="6" rx="3" fill={tone.fg} opacity="0.16"/>
          </g>
        ))}
      </svg>
    );
  }
  if (kind === 'doc') {
    return (
      <svg viewBox="0 0 220 120" width="100%" height="100%" preserveAspectRatio="none">
        <g transform="translate(18 14)">
          <rect width="55%" height="6" fill="rgba(16,16,16,0.28)" rx="3"/>
          <rect width="40%" height="4" y="12" fill="rgba(16,16,16,0.14)" rx="2"/>
          <rect width="86%" height="3" y="26" fill="rgba(16,16,16,0.10)" rx="2"/>
          <rect width="78%" height="3" y="34" fill="rgba(16,16,16,0.10)" rx="2"/>
          <rect width="82%" height="3" y="42" fill="rgba(16,16,16,0.10)" rx="2"/>
          <rect width="70%" height="3" y="54" fill="rgba(16,16,16,0.10)" rx="2"/>
          <rect width="88%" height="3" y="62" fill="rgba(16,16,16,0.10)" rx="2"/>
          <rect width="60%" height="3" y="70" fill="rgba(16,16,16,0.10)" rx="2"/>
          <rect width="72%" height="3" y="82" fill="rgba(16,16,16,0.10)" rx="2"/>
        </g>
      </svg>
    );
  }
  if (kind === 'api') {
    return (
      <svg viewBox="0 0 220 120" width="100%" height="100%" preserveAspectRatio="none" fontFamily="var(--font-mono)">
        <rect x="14" y="14" width="192" height="92" rx="8" fill="rgba(255,255,255,0.75)"/>
        <rect x="24" y="24" width="50" height="14" rx="4" fill={tone.fg} opacity="0.85"/>
        <text x="49" y="34" textAnchor="middle" fontSize="8" fontWeight="700" fill="white">POST</text>
        <text x="82" y="34" fontSize="10" fontWeight="600" fill="rgba(16,16,16,0.72)">/briefs</text>
        <line x1="24" y1="50" x2="196" y2="50" stroke="rgba(16,16,16,0.08)" strokeWidth="1"/>
        <text x="24" y="66" fontSize="9" fill="rgba(16,16,16,0.55)">201 · created</text>
        <text x="24" y="80" fontSize="9" fill="rgba(16,16,16,0.55)">400 · invalid section</text>
        <text x="24" y="94" fontSize="9" fill="rgba(16,16,16,0.55)">401 · unauthorized</text>
      </svg>
    );
  }
  return null;
}

// Small attachment card for the Attachments strip.
function AttachmentCard({ a }) {
  const iconMap = { doc: 'fileText', pdf: 'fileText', image: 'image', link: 'externalLink', design: 'palette', contract: 'contracts' };
  const toneMap = { doc: 'gray', pdf: 'gray', image: 'peach', link: 'blue', design: 'peach', contract: 'green' };
  const tone = (window.MYGENI_MISSION_TONES || {})[toneMap[a.kind]] || (window.MYGENI_MISSION_TONES || {}).gray;
  return (
    <div className="fd-attach-card">
      <div className="fd-attach-preview" style={{ background: tone.bg, color: tone.fg }}>
        <Icon name={iconMap[a.kind] || 'paperclip'} size={22} strokeWidth={1.5}/>
        <span className="fd-attach-kind">{a.kind.toUpperCase()}</span>
      </div>
      <div className="fd-attach-meta">
        <div className="fd-attach-name">{a.name}</div>
        <div className="fd-attach-sub">
          {a.size && <span>{a.size}</span>}
          {a.size && <span className="fd-dot" />}
          <span>{a.updated}</span>
          <span className="fd-dot" />
          <span>{a.owner}</span>
        </div>
      </div>
    </div>
  );
}

function FeatureDetail({ pdata, detail: d }) {
  const [aiReqsOpen, setAiReqsOpen] = React.useState(false);
  const doneAcc  = d.acceptance.filter(a => a.done).length;

  const currentStage = pdata.stages.find(s => s.n === d.stageN);
  const nextStage    = pdata.stages.find(s => s.n === d.nextStageN);

  return (
    <div>
      {/* Header */}
      <div className="fd-header">
        <a href={`#/projects/${pdata.id}/features`} className="fd-back">
          <Icon name="arrowLeft" size={13} strokeWidth={2}/>
          <span>Features</span>
        </a>

        <div className="fd-titlerow">
          <h1 className="fd-title">{d.title}</h1>
          <span className="fd-code">{d.code}</span>
          <span className={`fd-priority ${d.priority}`}>{d.priority}</span>
          <Label tone={d.tone === 'yellow' ? 'yellow' : d.tone === 'green' ? 'green' : d.tone === 'red' ? 'red' : d.tone === 'blue' ? 'blue' : 'purple'} dot size="sm">{d.status}</Label>
        </div>
        <p className="fd-purpose">{d.purpose}</p>

        <div className="fd-meta">
          <div className="m"><Icon name="person" size={14} strokeWidth={1.75}/> Owner <b>{d.owner}</b></div>
          <div className="m"><AvatarStack names={d.team} max={4} size="xs"/> {d.team.length} people</div>
          <span className="divider" />
          <div className="m"><Ring percent={d.progress} color="var(--primary-01)" size={28} label="" />
            <span><b>{d.progress}%</b></span>
          </div>
          <div className="m"><Icon name="clock" size={14} strokeWidth={1.75}/> Target <b>{d.target.date}</b> <span style={{ color: 'var(--text-tertiary)' }}>· in {d.target.when}d</span></div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <button className="icon-btn" style={{ width: 36, height: 36 }} aria-label="Share"><Icon name="share" size={16} strokeWidth={1.75}/></button>
            <button className="btn btn-primary btn-sm"><Icon name="edit" size={14} strokeWidth={1.75}/><span>Update</span></button>
          </div>
        </div>
      </div>

      {/* Feature ↔ Plan/Stage stripe — the connection made obvious */}
      <FeatureStageStripe pdata={pdata} d={d} />

      <div className="fd-body">
        {/* MAIN */}
        <div className="fd-main">
          {/* Overview */}
          <div className="fd-ov">
            <span className="lbl">Why</span>
            <p className="p">{d.why}</p>

            <div style={{ marginTop: 18 }}>
              <span className="lbl">User problem</span>
              <p className="p">{d.userProblem}</p>
            </div>

            <div style={{ marginTop: 18 }}>
              <span className="lbl">Desired outcome</span>
              <p className="p">{d.desiredOutcome}</p>
            </div>

            <div className="fd-ov-grid">
              <div>
                <span className="lbl" style={{ color: 'var(--success-solid)' }}>Scope</span>
                <ul className="scope-list">
                  {d.scope.map((s, i) => (
                    <li key={i}><span className="tick"><Icon name="check" size={14} strokeWidth={2.5}/></span><span>{s}</span></li>
                  ))}
                </ul>
              </div>
              <div>
                <span className="lbl">Out of scope</span>
                <ul className="scope-list oos">
                  {d.outOfScope.map((s, i) => (
                    <li key={i}><span className="tick"><Icon name="x" size={13} strokeWidth={2.5}/></span><span>{s}</span></li>
                  ))}
                </ul>
              </div>
            </div>
          </div>

          {/* Requirements */}
          <div className="fd-card">
            <div className="fd-card-head">
              <h3><Icon name="spec" size={15} strokeWidth={1.75} style={{ color: 'var(--primary-01)' }}/> Requirements</h3>
              <div className="desc">{d.requirements.length} · scoped for this feature</div>
              <a className="link">Add requirement</a>
            </div>
            <div>
              {d.requirements.map((r) => (
                <div className="req-row" key={r.id}>
                  <div className="r-id">{r.id}</div>
                  <div className="r-text">{r.text}</div>
                  <div><span className={`r-priority ${r.priority}`}>{r.priority}</span></div>
                  <div><Label tone={r.tone} dot size="sm">{r.status}</Label></div>
                  <div className="r-owner"><Avatar name={r.owner} size="xs"/> {r.owner.split(' ')[0]}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Acceptance + Success */}
          <div className="fd-card">
            <div className="fd-card-head">
              <h3><Icon name="check" size={15} strokeWidth={2} style={{ color: 'var(--success-solid)' }}/> Acceptance criteria</h3>
              <div className="desc">{doneAcc} of {d.acceptance.length} complete · all must pass to move Stage 04</div>
            </div>
            <div className="acc-list">
              {d.acceptance.map((a, i) => (
                <div className={`acc-item${a.done ? ' done' : ''}`} key={i}>
                  <div className="cb" />
                  <div className="t">{a.text}</div>
                </div>
              ))}
            </div>
            <div className="success-signal">
              <div className="g"><Icon name="target" size={16} strokeWidth={1.75}/></div>
              <div>
                <div className="k">Success signal</div>
                <div className="v">{d.successSignal}</div>
              </div>
            </div>
          </div>

          {/* Readiness composition — a single composed surface that
              answers "is this feature ready to move to the next stage?"
              Replaces the earlier trio of flat Research/Design/Development
              cards; opens onto those sections via row/preview clicks. */}
          <ReadinessComposition pdata={pdata} d={d} />

          {/* Attachments strip — first-class */}
          {d.attachments && d.attachments.length > 0 && (
            <div className="fd-attach">
              <div className="fd-card-head" style={{ marginBottom: 10 }}>
                <h3><Icon name="paperclip" size={15} strokeWidth={1.75} style={{ color: 'var(--text-tertiary)' }}/> Attachments <span style={{ marginLeft: 6, fontSize: 12, color: 'var(--text-tertiary)', fontWeight: 500 }}>{d.attachments.length}</span></h3>
                <a className="link" href={`#/projects/${pdata.id}/documents`}>Open Documents →</a>
              </div>
              <div className="fd-attach-grid">
                {d.attachments.map((a, i) => <AttachmentCard key={i} a={a} />)}
              </div>
            </div>
          )}

          {/* Tasks */}
          <div className="tasks-card">
            <div className="tasks-head">
              <h4><Icon name="check" size={15} strokeWidth={2} style={{ color: 'var(--text-tertiary)' }}/> Tasks <span style={{ marginLeft: 6, fontSize: 12, color: 'var(--text-tertiary)', fontWeight: 500 }}>{d.tasks.length} · related to this feature</span></h4>
              <a className="link" href="#/my-work">Open in My Work →</a>
            </div>
            {d.tasks.map((t, i) => (
              <div className={`task-row${t.done ? ' done' : ''}`} key={i}>
                <div className="cb" />
                <div className="t-title">{t.title}{t.blocker ? <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--danger-solid)', fontWeight: 600, letterSpacing: '-0.02em' }}>{t.blocker}</span> : null}</div>
                <div className="t-owner"><Avatar name={t.owner} size="xs"/> {t.owner.split(' ')[0]}</div>
                <div className="t-due">{t.due}</div>
                <div className="t-status"><Label tone={t.tone} dot size="sm">{t.status}</Label></div>
              </div>
            ))}
          </div>

          {/* Related — Documents */}
          <div className="fd-card">
            <div className="fd-card-head">
              <h3><Icon name="files" size={15} strokeWidth={1.75}/> Documents</h3>
              <a className="link" href={`#/projects/${pdata.id}/documents`}>Open Documents →</a>
            </div>
            <div className="fd-docs-grid">
              {d.relatedDocs.map((doc, i) => (
                <div className="docs-card" key={i}>
                  <div className="docs-visual">
                    <DocVisual kind={doc.preview} />
                    <span className="doc-badge">{doc.kind}</span>
                  </div>
                  <div className="docs-meta">
                    <div className="docs-title">{doc.title}</div>
                    <div className="docs-sub"><span>{doc.size}</span><span>·</span><span>updated {doc.updated}</span></div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Activity */}
          <div className="fd-card">
            <div className="fd-card-head">
              <h3><Icon name="clock" size={15} strokeWidth={1.75}/> Activity</h3>
              <a className="link">Full log</a>
            </div>
            <div>
              {d.activity.map((g, i) => (
                <div key={i}>
                  <div className="act-day-label">{g.day}</div>
                  {g.items.map((it, j) => (
                    <div className="act-item" key={j}>
                      <div className={`act-ico ${activityTone(it.tone)}`}>
                        <Icon name={it.ico} size={15} strokeWidth={1.75}/>
                      </div>
                      <div className="act-text">
                        <b>{it.a}</b> <span className="a-ctx">{it.v}</span> <b>{it.what}</b><span className="a-ctx">{it.extra}</span>
                      </div>
                      <div className="act-time">{it.time}</div>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* RIGHT RAIL */}
        <div className="fd-side">
          {/* Dependencies */}
          <div className="dep-card">
            <div className="fd-card-head" style={{ marginBottom: 6 }}>
              <h3><Icon name="link" size={15} strokeWidth={1.75}/> Dependencies</h3>
            </div>
            <div className="dep-sub">Depends on</div>
            <div className="dep-list">
              {d.dependsOn.map((x, i) => (
                <div className="dep-item depson" key={i}>
                  <div className="g"><Icon name="arrowLeft" size={12} strokeWidth={2}/></div>
                  <div className="n truncate">{x.title}</div>
                  <Label tone={x.tone} dot size="sm">{x.status}</Label>
                </div>
              ))}
            </div>
            <div className="dep-sub">Blocks</div>
            <div className="dep-list">
              {d.blocks.map((x, i) => (
                <div className="dep-item blocks" key={i}>
                  <div className="g"><Icon name="arrowRight" size={12} strokeWidth={2}/></div>
                  <div className="n truncate">{x.title}</div>
                  <Label tone={x.tone} dot size="sm">{x.status}</Label>
                </div>
              ))}
            </div>
          </div>

          {/* Decisions (linked) */}
          <div className="fd-card">
            <div className="fd-card-head" style={{ marginBottom: 6 }}>
              <h3><Icon name="decisions" size={15} strokeWidth={1.75}/> Decisions</h3>
              <a className="link" href={`#/projects/${pdata.id}/overview`}>All</a>
            </div>
            {d.relatedDecisions.map((idx, i) => {
              const dec = pdata.decisions[idx];
              if (!dec) return null;
              return (
                <div className="dec-item" key={i} style={{ padding: '10px 4px' }}>
                  <div className="dec-head">
                    <Label tone={dec.tone === 'green' ? 'green' : dec.tone === 'yellow' ? 'yellow' : 'red'} dot size="sm">{dec.status}</Label>
                    <span className="when">{dec.when}</span>
                  </div>
                  <div className="dec-title" style={{ fontSize: 13.5 }}>{dec.title}</div>
                  <div className="dec-ctx" style={{ fontSize: 12 }}>{dec.ctx}</div>
                </div>
              );
            })}
          </div>

          {/* Assist — a single quiet section, not a stack of sparkles */}
          <div className="fd-assist">
            <div className="fd-assist-head">
              <Icon name="spark" size={13} strokeWidth={1.75} style={{ color: 'var(--text-tertiary)' }}/>
              <span>Assist</span>
            </div>
            <div className="fd-assist-actions">
              <a onClick={() => setAiReqsOpen(v => !v)}>Suggest requirements</a>
              <a>Summarize research</a>
              <a>Identify missing dependencies</a>
            </div>
          </div>

          {/* Inline suggestion panel (calm) */}
          {aiReqsOpen && (
            <div className="fd-assist-panel">
              <div className="fd-assist-panel-head">
                <div className="t">Suggested requirements</div>
                <a className="close" onClick={() => setAiReqsOpen(false)}><Icon name="x" size={14} strokeWidth={2}/></a>
              </div>
              <div className="fd-assist-suggs">
                {d.aiSuggestedReqs.map((s, i) => (
                  <div className="fd-assist-sugg" key={i}>
                    <div>
                      <div className="t">{s.text}</div>
                      <div className="w">{s.why}</div>
                    </div>
                    <button className="add"><Icon name="plus" size={12} strokeWidth={2}/></button>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 8, fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '-0.02em' }}>
                Drafts only. Nothing changes until you accept.
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function activityTone(t) {
  return { brand: 'lav', blue: 'lav', green: 'mint', red: 'peach', orange: 'cream', purple: 'lav' }[t] || 'peach';
}

// Small screen mocks used inside FeatureDetail > Design section
function BriefScreenMock({ kind }) {
  if (kind === 'brief-shell') {
    return (
      <svg viewBox="0 0 260 200" width="100%" height="100%" preserveAspectRatio="none">
        <rect x="14" y="14" width="80" height="170" rx="10" fill="white" stroke="rgba(16,16,16,0.08)" strokeWidth="1.2"/>
        <rect x="22" y="26" width="60" height="7" rx="2" fill="rgba(16,16,16,0.30)"/>
        {[42, 62, 82, 102, 122, 142].map((y, i) => (
          <rect key={i} x="22" y={y} width="60" height="12" rx="4" fill={i === 1 ? 'rgba(42,133,255,0.12)' : 'transparent'}/>
        ))}
        <rect x="102" y="14" width="144" height="170" rx="10" fill="white" stroke="rgba(16,16,16,0.08)" strokeWidth="1.2"/>
        <rect x="112" y="26" width="120" height="10" rx="3" fill="rgba(16,16,16,0.32)"/>
        <rect x="112" y="42" width="90" height="5" rx="2" fill="rgba(16,16,16,0.14)"/>
        {[62, 92, 122, 152].map((y, i) => (
          <g key={i}>
            <rect x="112" y={y} width="124" height="22" rx="6" fill="rgba(16,16,16,0.04)"/>
            <rect x="118" y={y+4} width="50" height="5" rx="2" fill="rgba(16,16,16,0.30)"/>
            <rect x="118" y={y+12} width="100" height="4" rx="1.5" fill="rgba(16,16,16,0.12)"/>
          </g>
        ))}
      </svg>
    );
  }
  if (kind === 'brief-dec') {
    return (
      <svg viewBox="0 0 260 200" width="100%" height="100%" preserveAspectRatio="none">
        <rect x="14" y="14" width="232" height="18" rx="6" fill="rgba(0,166,86,0.10)" stroke="rgba(0,166,86,0.25)" strokeWidth="1.2"/>
        <rect x="22" y="20" width="60" height="5" rx="2" fill="rgba(0,166,86,0.65)"/>
        <rect x="90" y="20" width="120" height="5" rx="2" fill="rgba(16,16,16,0.22)"/>
        {[42, 74, 106, 138].map((y, i) => (
          <g key={i}>
            <rect x="14" y={y} width="232" height="22" rx="6" fill="white" stroke="rgba(16,16,16,0.08)" strokeWidth="1.2"/>
            <circle cx="26" cy={y+10} r="5" fill={i % 2 ? 'rgba(0,166,86,0.5)' : 'rgba(239,157,14,0.5)'}/>
            <rect x="36" y={y+6} width="120" height="4" rx="1.5" fill="rgba(16,16,16,0.30)"/>
            <rect x="36" y={y+14} width="180" height="3" rx="1.5" fill="rgba(16,16,16,0.10)"/>
            <rect x="200" y={y+9} width="40" height="5" rx="2" fill="rgba(42,133,255,0.20)"/>
          </g>
        ))}
        <rect x="14" y="170" width="232" height="14" rx="4" fill="rgba(42,133,255,0.08)" stroke="rgba(42,133,255,0.20)" strokeWidth="1.2"/>
      </svg>
    );
  }
  if (kind === 'brief-prob') {
    return (
      <svg viewBox="0 0 260 200" width="100%" height="100%" preserveAspectRatio="none">
        <rect x="14" y="14" width="232" height="18" rx="6" fill="rgba(255,188,153,0.30)" stroke="rgba(255,188,153,0.55)" strokeWidth="1.2"/>
        <rect x="22" y="20" width="52" height="5" rx="2" fill="rgba(196,91,34,0.75)"/>
        <rect x="90" y="20" width="120" height="5" rx="2" fill="rgba(16,16,16,0.22)"/>
        {[
          [42, 'peach'],
          [98, 'sky'],
          [154, 'cream'],
        ].map(([y, tone], i) => (
          <g key={i}>
            <rect x="14" y={y} width="232" height="44" rx="10" fill="white" stroke="rgba(16,16,16,0.08)" strokeWidth="1.2"/>
            <rect x="22" y={y+8} width="18" height="18" rx="5" fill={tone === 'peach' ? '#FFBC99' : tone === 'sky' ? '#B1E5FC' : '#FFD88D'}/>
            <rect x="48" y={y+10} width="120" height="5" rx="2" fill="rgba(16,16,16,0.32)"/>
            <rect x="48" y={y+22} width="180" height="4" rx="1.5" fill="rgba(16,16,16,0.14)"/>
            <rect x="48" y={y+30} width="140" height="4" rx="1.5" fill="rgba(16,16,16,0.14)"/>
          </g>
        ))}
      </svg>
    );
  }
  return null;
}

Object.assign(window, { FeaturesSection, FeaturesOverview, FeatureDetail });
