/* P20b · Rapid Classifier (M01.E02 mastery)
 * 50 charts en <60s cada uno. Minimalismo extremo. Atajos 1-4.
 */

function P20b_RapidClassifier(props = {}) {
  const total = props.total || 50;
  const [index, setIndex] = React.useState(props.initialIndex || 22); // 0-indexed (mostrando "Gráfico 23")
  const [timer, setTimer] = React.useState(props.initialTimer != null ? props.initialTimer : 42);
  const [submissions, setSubmissions] = React.useState(props.submissions || []);

  // Cada chart usa un seed distinto y un régimen
  const charts = React.useMemo(() => {
    const out = [];
    const regimes = ['uptrend', 'downtrend', 'range', 'transition'];
    for (let i = 0; i < total; i++) {
      const r = regimes[(i * 7) % 4];
      out.push({
        seed: 100 + i * 13,
        regime: r,
        groundTruth: r,
      });
    }
    return out;
  }, [total]);

  const current = charts[index];
  const bars = React.useMemo(() =>
    window.synthetic.makeSeries({ seed: current.seed, n: 180, drift: 0.0008, vol: 0.012, cycles: 3, regime: current.regime }),
  [current.seed, current.regime]);

  // Tick del timer
  React.useEffect(() => {
    if (props.frozen) return;
    if (timer <= 0) { handleNext('expired'); return; }
    const t = setTimeout(() => setTimer(timer - 1), 1000);
    return () => clearTimeout(t);
  }, [timer, props.frozen]);

  function classify(label) {
    setSubmissions([...submissions, { index, label, timeRemaining: timer }]);
    handleNext(label);
  }
  function handleNext() {
    if (index + 1 >= total) return;
    setIndex(index + 1);
    setTimer(60);
  }

  // Atajos de teclado
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === '1') classify('uptrend');
      if (e.key === '2') classify('downtrend');
      if (e.key === '3') classify('range');
      if (e.key === '4') classify('transition');
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  const timerColor = timer < 10 ? '#D85C5C' : timer < 30 ? '#E07A5F' : '#F0B86E';

  const options = [
    { id: 'uptrend', label: 'Alcista', key: '1', color: '#5BC68F' },
    { id: 'downtrend', label: 'Bajista', key: '2', color: '#D85C5C' },
    { id: 'range', label: 'Rango', key: '3', color: '#A2A9B4' },
    { id: 'transition', label: 'Transición', key: '4', color: '#F0B86E' },
  ];

  // Progress bar
  const progressPct = (index / total) * 100;

  return (
    <div style={{ height: '100%', background: 'var(--surface-0)', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden' }}>
      {/* Mini header */}
      <div style={{ height: 48, display: 'flex', alignItems: 'center', padding: '0 24px', gap: 24, borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: timerColor, minWidth: 70, fontWeight: 600 }}>
          0:{timer.toString().padStart(2, '0')}
        </div>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 14, color: 'var(--text-secondary)' }}>
          Gráfico <span style={{ color: 'var(--text-primary)', fontWeight: 600, fontFamily: 'var(--font-mono)' }}>{index + 1}</span> de {total}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 200, justifyContent: 'flex-end' }}>
          <div style={{ width: 140, height: 4, background: 'var(--surface-2)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ width: `${progressPct}%`, height: '100%', background: 'var(--text-primary)' }} />
          </div>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>{index}/{total}</span>
        </div>
      </div>

      {/* Chart centrado */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px 32px 0' }}>
        <ChartCanvas
          bars={bars}
          width={1100}
          height={460}
          anonymized
          showWatermark
          watermark="Educativo"
        />
      </div>

      {/* 4 botones grandes */}
      <div style={{ display: 'flex', gap: 24, padding: '24px 32px 32px', justifyContent: 'center' }}>
        {options.map((opt) => (
          <button key={opt.id} onClick={() => classify(opt.id)} style={{
            flex: 1, maxWidth: 260,
            height: 92,
            background: 'var(--surface-1)',
            border: '1px solid var(--border-default)',
            borderRadius: 'var(--radius-md)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '0 24px',
            cursor: 'pointer',
            fontFamily: 'var(--font-sans)',
            color: 'var(--text-primary)',
            transition: 'border-color 120ms, background 120ms',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.borderColor = opt.color; e.currentTarget.style.background = 'var(--surface-2)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-default)'; e.currentTarget.style.background = 'var(--surface-1)'; }}>
            <span style={{ fontSize: 24, fontWeight: 600 }}>{opt.label}</span>
            <span style={{
              width: 28, height: 28, borderRadius: 4,
              background: 'var(--surface-3)',
              color: opt.color, border: `1px solid ${opt.color}`,
              display: 'grid', placeItems: 'center',
              fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600,
            }}>{opt.key}</span>
          </button>
        ))}
      </div>

      {/* Hint atajos */}
      <div style={{ position: 'absolute', bottom: 8, left: '50%', transform: 'translateX(-50%)', fontSize: 11, color: 'var(--text-disabled)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>
        SIN TUTOR · SIN PAUSA · ATAJOS 1-4
      </div>
    </div>
  );
}

window.P20b_RapidClassifier = P20b_RapidClassifier;
