// Layer deep-dive: components strip + per-head attention breakdown + top features

const { useMemo: useMemoLD } = React;

function LayerDeepDive({ selected, onPickCell }) {
  const { layer, component } = selected;

  const allComps = AtlasData.COMPONENTS;
  const isAttn = ['heads', 'q', 'k', 'v'].includes(component);
  const headLikeComp = isAttn ? component : 'heads';

  const heads = useMemoLD(
    () => (AtlasData.headBreakdown ? AtlasData.headBreakdown(layer, headLikeComp) : []),
    [layer, headLikeComp]
  );
  const feats = useMemoLD(
    () => (AtlasData.topFeatures ? AtlasData.topFeatures(layer, component) : []),
    [layer, component]
  );

  const componentRow = AtlasData.FSTAT[layer] || [];
  const compIndex = allComps.findIndex(c => c.id === component);
  const cellVal = componentRow[compIndex];

  return (
    <div className="ld">
      <div className="ld-head">
        <div>
          <div className="bf-eyebrow">Layer deep-dive</div>
          <div className="ld-title">
            <span className="mono lg">L{layer}</span>
            <span className="ld-sep">·</span>
            <span className="ld-comp">{component}</span>
          </div>
          <div className="ld-meta">
            <span>position <b>{(layer / Math.max(1, AtlasData.N_LAYERS - 1) * 100).toFixed(0)}%</b> through stack</span>
            <span className="dot">·</span>
            <span>kind <b>{allComps.find(c => c.id === component)?.kind || '—'}</b></span>
            <span className="dot">·</span>
            <span>F-stat <b>{Number.isFinite(cellVal) ? cellVal.toFixed(2) : '—'}</b></span>
          </div>
        </div>
      </div>

      <div className="ld-section">
        <div className="ld-eyebrow">Components in this layer</div>
        <div className="ld-comps" style={{ gridTemplateColumns: `repeat(${Math.min(4, allComps.length)}, 1fr)` }}>
          {allComps.map((c, ci) => {
            const v = componentRow[ci];
            const active = c.id === component;
            const hasData = Number.isFinite(v);
            return (
              <button
                key={c.id}
                className={"ld-comp-chip" + (active ? ' is-active' : '') + (hasData ? '' : ' is-empty')}
                onClick={() => onPickCell({ layer, component: c.id })}
              >
                <span className="ld-chip-name mono">{c.label}</span>
                <span className="ld-chip-bar"><span style={{ width: (hasData ? v * 100 : 4) + '%' }} /></span>
                <span className="ld-chip-v mono">{hasData ? v.toFixed(2) : '—'}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="ld-cols">
        <div className="ld-section">
          <div className="ld-eyebrow">
            {isAttn ? <>Attention <b className="mono">{component}</b> heads · top_sep_score</> : <>Heads in this layer · top_sep_score</>}
          </div>
          {heads.length === 0 ? (
            <div className="ld-empty muted">
              No per-head data for L{layer} · {headLikeComp} yet — this layer hasn't been ingested.
            </div>
          ) : (
            <div className="ld-heads">
              {heads.map((h) => (
                <div key={h.head} className="ld-head-row">
                  <span className="mono dim w-9">H{String(h.head).padStart(2, '0')}</span>
                  <span className="ld-head-role">{h.role}</span>
                  <span className="ld-head-bar"><span style={{ width: Math.min(100, (h.fstat / 15) * 100) + '%' }} /></span>
                  <span className="mono a-right w-12">{h.fstat.toFixed(2)}</span>
                </div>
              ))}
            </div>
          )}
          {heads.length > 0 && heads[0].taxonomy && (
            <div className="ld-taxonomy">
              <div className="ld-eyebrow" style={{ marginTop: 14 }}>dim taxonomy · top head ({heads[0] && `H${String(heads[0].head).padStart(2, '0')}`})</div>
              <Taxonomy tax={heads[0].taxonomy} dims={heads[0].dims} />
            </div>
          )}
        </div>

        <div className="ld-section">
          <div className="ld-eyebrow">Top compliance features at L{layer} · {component}</div>
          {feats.length === 0 ? (
            <div className="ld-empty muted">
              No compliance features for L{layer} · {component} — likely not in the analyzed component set
              (compliance analysis runs on <span className="mono">mlp</span> and <span className="mono">gate</span> right now).
            </div>
          ) : (
            <div className="ld-feats">
              {feats.map((f, i) => (
                <div key={i} className="ld-feat">
                  <div className="ld-feat-top">
                    <span className="mono dim">f{f.feature}</span>
                    <span className={"ld-feat-leaning tone-" + (f.leaning === 'corp' ? 'rose' : 'sage')}>
                      {f.leaning}-leaning
                    </span>
                    <span className="ld-feat-fstat mono">F {f.fstat?.toFixed(1)}</span>
                    <span className="ld-feat-dens mono">Δ {f.delta?.toFixed(2)}</span>
                  </div>
                  <div className="ld-feat-desc">{f.desc}</div>
                  <div className="ld-feat-fbar"><span style={{ width: Math.min(100, (f.fstat / 3000) * 100) + '%' }} /></div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Taxonomy({ tax, dims }) {
  const order = ['broadly_shared', 'partial_shared', 'all_shared', 'non_activated'];
  const keys = order.filter(k => k in tax).concat(Object.keys(tax).filter(k => !order.includes(k)));
  const total = dims || keys.reduce((a, k) => a + (tax[k] || 0), 0) || 1;
  const TONE = {
    broadly_shared: 'lavender',
    partial_shared: 'rose',
    all_shared:     'gold',
    non_activated:  'sage',
  };
  return (
    <div className="ld-tax">
      <div className="ld-tax-bar">
        {keys.map(k => (
          <span key={k} className={"ld-tax-seg tone-" + (TONE[k] || 'lavender')}
                style={{ width: ((tax[k] || 0) / total * 100) + '%' }} />
        ))}
      </div>
      <div className="ld-tax-legend">
        {keys.map(k => (
          <span key={k} className="ld-tax-leg">
            <span className={"ld-tax-dot tone-" + (TONE[k] || 'lavender')} />
            <span className="mono">{k.replace('_', ' ')}</span>
            <span className="muted mono">{tax[k]}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

window.LayerDeepDive = LayerDeepDive;
