// S5 — Validated before it answers.
// Onboarding doesn't trust the upload. The data-prep pipeline reconciles the
// spec's question codes to the real columns, enforces weighting, executes every
// metric to catch anomalies, and — the part clients feel — re-derives the
// numbers and ties them back to the client's own published Full Tabs before a
// single question is allowed to run. Faithful to pipeline/data_prep/runner.py,
// _reconcile_spec_to_source(), catalog_validator.detect_anomalies(), and
// generate_validation_sheet.py → validation/system_scores.csv vs client tabs.

const { useState: vlUse, useEffect: vlEff } = React;
const { pitchC, pitchMono } = window;

// Structural checks the pipeline runs on upload (each → a real function).
const CHECKS = [
  { t: 'Spec ↔ source reconciled', d: 'question codes matched to columns', fn: '_reconcile_spec_to_source()' },
  { t: 'Weighting enforced', d: 'weighted bases, never raw counts', fn: '_ensure_weight_column()' },
  { t: 'Every metric executes', d: 'no empty · constant · flat results', fn: 'detect_anomalies()' },
  { t: 'Spec coverage complete', d: 'every spec row profiled', fn: 'check_spec_coverage()' },
];

// The part the user asked for: re-computed scores tied back to the client's
// own published reference tabs, matched within tolerance.
const REF_ROWS = [
  { metric: 'Prompted awareness',      tab: '38.0%', sys: '38.0%' },
  { metric: 'Consideration · T2B',     tab: '22.3%', sys: '22.3%' },
  { metric: 'Future consideration',    tab: '9.1%',  sys: '9.1%'  },
  { metric: 'Last purchased · Habitat',tab: '4.2%',  sys: '4.2%'  },
  { metric: 'Weighted base (n)',       tab: '2,481', sys: '2,481', plain: true },
];

function SlideValidation() {
  const [n, setN] = vlUse(0);   // checks revealed
  const [r, setR] = vlUse(0);   // reference rows reconciled
  const [done, setDone] = vlUse(false);

  vlEff(() => {
    const ts = [];
    CHECKS.forEach((_, i) => ts.push(setTimeout(() => setN(i + 1), 300 + i * 360)));
    const base = 300 + CHECKS.length * 360 + 200;
    REF_ROWS.forEach((_, i) => ts.push(setTimeout(() => setR(i + 1), base + i * 320)));
    ts.push(setTimeout(() => setDone(true), base + REF_ROWS.length * 320 + 250));
    return () => ts.forEach(clearTimeout);
  }, []);

  return (
    <div style={{
      flex: 1, minHeight: 0,
      display: 'grid', gridTemplateColumns: '0.84fr 1.16fr', gap: 28, marginTop: 24,
    }}>
      {/* LEFT — structural checks on upload */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minHeight: 0 }}>
        <div style={{
          fontFamily: pitchMono, fontSize: 14, fontWeight: 700,
          letterSpacing: 1.8, textTransform: 'uppercase', color: pitchC.muted2,
        }}>Checks on upload</div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 11, flex: 1, justifyContent: 'center' }}>
          {CHECKS.map((c, i) => {
            const shown = n >= i + 1;
            return (
              <div key={c.t} style={{
                display: 'flex', alignItems: 'flex-start', gap: 13,
                padding: '12px 16px', background: '#fff',
                border: `1px solid ${shown ? pitchC.moss + '44' : pitchC.hair}`, borderRadius: 12,
                opacity: shown ? 1 : 0.32,
                transform: shown ? 'translateX(0)' : 'translateX(-10px)',
                transition: 'opacity 320ms ease, transform 320ms ease, border-color 320ms ease',
              }}>
                <span style={{
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  width: 24, height: 24, borderRadius: '50%', flexShrink: 0, marginTop: 1,
                  background: shown ? pitchC.mossBg : pitchC.bgSoft,
                }}>
                  {shown ? (
                    <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke={pitchC.moss} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8.5l3 3 7-7"/></svg>
                  ) : (
                    <span style={{ width: 7, height: 7, borderRadius: '50%', background: pitchC.hair2 }} />
                  )}
                </span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 16.5, fontWeight: 600, color: pitchC.ink, letterSpacing: -0.01 }}>{c.t}</div>
                  <div style={{ fontSize: 13.5, color: pitchC.muted, marginTop: 1 }}>{c.d}</div>
                  <div style={{ fontFamily: pitchMono, fontSize: 11.5, color: pitchC.muted2, marginTop: 4 }}>{c.fn}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* RIGHT — reference numbers reconciled to the client's own tabs */}
      <div style={{
        background: '#fff', border: `1px solid ${pitchC.hair}`, borderRadius: 16,
        padding: '20px 24px 18px', display: 'flex', flexDirection: 'column',
        minHeight: 0, overflow: 'hidden', boxShadow: '0 2px 0 rgba(0,0,0,0.02)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          paddingBottom: 13, marginBottom: 4, borderBottom: `1px solid ${pitchC.hair}`,
        }}>
          <span style={{ display: 'flex', gap: 6 }}>
            {[pitchC.orange, pitchC.amber, pitchC.moss].map(c => (
              <span key={c} style={{ width: 11, height: 11, borderRadius: '50%', background: c, opacity: 0.85 }} />
            ))}
          </span>
          <span style={{ fontFamily: pitchMono, fontSize: 13, fontWeight: 600, color: pitchC.muted, marginLeft: 6 }}>
            beacon · reference numbers
          </span>
          <span style={{ marginLeft: 'auto', fontFamily: pitchMono, fontSize: 12.5, fontWeight: 600, color: done ? pitchC.moss : pitchC.sea }}>
            {done ? 'reconciled ✓' : 'matching…'}
          </span>
        </div>

        {/* column headers */}
        <div style={{
          display: 'grid', gridTemplateColumns: '1.5fr 0.9fr 0.9fr 0.7fr',
          gap: 10, padding: '8px 4px', alignItems: 'center',
          fontFamily: pitchMono, fontSize: 11.5, fontWeight: 700,
          letterSpacing: 0.8, textTransform: 'uppercase', color: pitchC.muted2,
        }}>
          <span>Metric</span>
          <span style={{ textAlign: 'right' }}>Your tab</span>
          <span style={{ textAlign: 'right' }}>System</span>
          <span style={{ textAlign: 'right' }}>Δ</span>
        </div>

        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 4 }}>
          {REF_ROWS.map((row, i) => {
            const shown = r >= i + 1;
            return (
              <div key={row.metric} style={{
                display: 'grid', gridTemplateColumns: '1.5fr 0.9fr 0.9fr 0.7fr',
                gap: 10, alignItems: 'center', padding: '10px 14px', borderRadius: 9,
                background: shown ? pitchC.mossBg : pitchC.bgSoft,
                border: `1px solid ${shown ? pitchC.moss + '2e' : 'transparent'}`,
                opacity: shown ? 1 : 0.4,
                transform: shown ? 'translateY(0)' : 'translateY(5px)',
                transition: 'opacity 300ms ease, transform 300ms ease, background 300ms ease, border-color 300ms ease',
              }}>
                <span style={{ fontSize: 15, color: pitchC.ink, fontWeight: 500 }}>{row.metric}</span>
                <span style={{ fontFamily: pitchMono, fontSize: 14.5, color: pitchC.muted, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{row.tab}</span>
                <span style={{ fontFamily: pitchMono, fontSize: 14.5, fontWeight: 700, color: pitchC.ink, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{shown ? row.sys : '··'}</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'flex-end', gap: 5 }}>
                  {shown ? (
                    <>
                      <span style={{ fontFamily: pitchMono, fontSize: 12.5, color: pitchC.moss }}>{row.plain ? '—' : '0.0'}</span>
                      <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke={pitchC.moss} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8.5l3 3 7-7"/></svg>
                    </>
                  ) : (
                    <span style={{ fontFamily: pitchMono, fontSize: 12.5, color: pitchC.muted2 }}>·</span>
                  )}
                </span>
              </div>
            );
          })}
        </div>

        {/* result */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          marginTop: 10, padding: '13px 16px', borderRadius: 11,
          background: done ? pitchC.mossBg : pitchC.bgSoft,
          border: `1px solid ${done ? pitchC.moss + '44' : pitchC.hair}`,
          opacity: done ? 1 : 0.3,
          transform: done ? 'translateY(0)' : 'translateY(6px)',
          transition: 'opacity 380ms ease, transform 380ms ease, background 380ms ease',
        }}>
          <span style={{ color: pitchC.moss, fontFamily: pitchMono, fontWeight: 700 }}>→</span>
          <span style={{ fontFamily: pitchMono, fontSize: 16, color: '#16603f', fontWeight: 600 }}>
            Validated — set up for success
          </span>
          <span style={{ marginLeft: 'auto', fontFamily: pitchMono, fontSize: 12, color: pitchC.muted2 }}>
            validation/system_scores.csv
          </span>
        </div>
      </div>
    </div>
  );
}

window.SlideValidation = SlideValidation;
