// Live data-source pill — shows status + per-config progress bars.

const { useState: useStateDS, useEffect: useEffectDS, useRef: useRefDS } = React;

function DataSource() {
  const [s, setS] = useStateDS(window.AtlasLoader.state);
  const [expanded, setExpanded] = useStateDS(false);
  const [panelPos, setPanelPos] = useStateDS({ top: 0, right: 0 });
  const pillRef = useRefDS(null);

  useEffectDS(() => window.AtlasLoader.subscribe(setS), []);

  useEffectDS(() => {
    if (!expanded || !pillRef.current) return;
    const r = pillRef.current.getBoundingClientRect();
    setPanelPos({ top: r.bottom + 10, right: window.innerWidth - r.right });
  }, [expanded]);

  const dot = {
    idle:    { c: 'var(--cream-dim)', label: 'idle' },
    loading: { c: 'var(--gold)',      label: 'streaming' },
    live:    { c: 'var(--sage)',      label: 'live' },
    error:   { c: 'var(--coral)',     label: 'offline' },
  }[s.status] || { c: 'var(--cream-dim)', label: s.status };

  // pill label
  let pillLabel = `data · ${dot.label}`;
  if (s.status === 'loading') {
    const totalLoaded = (s.progress.perHead + s.progress.bouncer + s.progress.prompts) / 3;
    pillLabel = `streaming · ${Math.round(totalLoaded * 100)}%`;
  } else if (s.status === 'live') {
    pillLabel = 'live · juiceb0xc0de';
  }

  const panel = expanded && ReactDOM.createPortal(
    <div className="ds-panel card" data-screen-label="datasource"
         style={{ position: 'fixed', top: panelPos.top, right: panelPos.right, zIndex: 9999 }}>
          <div className="ds-head">
            <div>
              <div className="bf-eyebrow">connected to</div>
              <div className="ds-repo mono">huggingface.co/datasets/{s.repo}</div>
            </div>
            <button className="link-btn" onClick={() => window.AtlasLoader.refresh()}>refresh</button>
          </div>

          {s.status === 'error' && (
            <div className="ds-error mono">{s.error || 'could not reach dataset'}</div>
          )}

          {s.splits && s.splits.length > 0 && (
            <div className="ds-section">
              <div className="ds-eyebrow">configs · {s.splits.length}</div>
              <div className="ds-splits">
                {s.splits.map(sp => {
                  // map config name to a progress key
                  const k = sp.config === 'per_head' ? 'perHead'
                          : sp.config === 'bouncer_analysis' ? 'bouncer'
                          : sp.config === 'prompts' ? 'prompts' : null;
                  const p = k ? (s.progress[k] || 0) : null;
                  return (
                    <div key={sp.config + '/' + sp.split} className="ds-split">
                      <div className="ds-split-top">
                        <span className="mono">{sp.config}</span>
                        <span className="muted mono">{(sp.num_rows ?? '?').toLocaleString()} rows</span>
                      </div>
                      {p != null && (
                        <div className="ds-split-bar">
                          <span style={{ width: (p * 100) + '%' }} />
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          <div className="ds-section">
            <div className="ds-eyebrow">status</div>
            <div className="ds-stats">
              <div><span className="k">N_LAYERS</span><span className="v mono">{window.AtlasData?.N_LAYERS}</span></div>
              <div><span className="k">components</span><span className="v mono">{window.AtlasData?.COMPONENTS?.length}</span></div>
              <div><span className="k">features</span><span className="v mono">{(window.AtlasData?.SURGICAL?.length || 0).toLocaleString()}</span></div>
              <div><span className="k">behaviors</span><span className="v mono">{window.AtlasData?.BEHAVIORS?.length}</span></div>
              <div><span className="k">source</span><span className="v">{window.AtlasData?.META?.source || 'preview'}</span></div>
            </div>
          </div>

          <div className="ds-note muted">
            Real-time fetch of the published configs from the HuggingFace datasets-server.
            <b> compliance_scores</b> (52 MB of raw per-feature vectors) is intentionally skipped to keep page load fast — query via SQL instead.
          </div>
        </div>,
    document.body
  );

  return (
    <div className={"ds " + (expanded ? 'is-open' : '')}>
      <button ref={pillRef} className="ds-pill" onClick={() => setExpanded(!expanded)}>
        <span className="ds-led" style={{ background: dot.c, boxShadow: `0 0 10px ${dot.c}` }} />
        <span className="ds-label">{pillLabel}</span>
        <span className="ds-chev">{expanded ? '▾' : '▸'}</span>
      </button>
      {panel}
    </div>
  );
}

window.DataSource = DataSource;
