/* global React, Reveal */
const { useState: useSMState, useEffect: useSMEffect } = React;

/* ============================================================
   AlgorithmCompare - SM-2 vs FSRS-6 side by side
   ============================================================ */

/* SM-2 interval sequence for the chart */
const SM2_INTERVALS = [1, 4, 9, 19, 38, 72, 140];
const SM2_LABELS    = ['1d', '4d', '9d', '19d', '38d', '72d', '140d'];

/* Shared panel wrapper */
const AlgoPanel = ({ children, style }) => (
  <div style={{
    background: 'var(--surface)', border: '1px solid var(--border-strong)',
    borderRadius: 16, padding: 28,
    display: 'flex', flexDirection: 'column', gap: 20,
    ...style,
  }}>
    {children}
  </div>
);

/* ---- SM-2 Panel ---- */
const SM2Panel = () => {
  const [grade, setGrade] = useSMState(null);

  const GRADES = [
    { id: 'again', label: 'Again', next: '10m', q: 0 },
    { id: 'hard',  label: 'Hard',  next: '6d',  q: 3 },
    { id: 'good',  label: 'Good',  next: '15d', q: 4 },
    { id: 'easy',  label: 'Easy',  next: '35d', q: 5 },
  ];

  useSMEffect(() => {
    if (grade !== null) {
      const t = setTimeout(() => setGrade(null), 1400);
      return () => clearTimeout(t);
    }
  }, [grade]);

  const maxInterval = SM2_INTERVALS[SM2_INTERVALS.length - 1];

  return (
    <AlgoPanel>
      {/* Label */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--fg-3)', flexShrink: 0 }} />
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--fg-3)' }}>SM-2</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Classic algorithm</span>
      </div>

      {/* Description */}
      <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6, color: 'var(--fg-2)', letterSpacing: '-0.011em' }}>
        After each review you grade your recall. SM-2 adjusts the card's ease factor and schedules the next showing. Backed by 30 years of memory research.
      </p>

      {/* Key metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
        {[
          ['Ease factor', '2.50'],
          ['Current interval', '15d'],
          ['Repetitions', '3'],
          ['Next review', '+15d'],
        ].map(([k, v]) => (
          <div key={k} style={{ padding: '10px 12px', background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 9 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg-3)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{k}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 17, color: 'var(--fg)', marginTop: 3, fontVariantNumeric: 'tabular-nums' }}>{v}</div>
          </div>
        ))}
      </div>

      {/* Interval growth chart */}
      <div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg-3)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>Interval growth (Good every review)</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 5, height: 52 }}>
          {SM2_INTERVALS.map((d, i) => (
            <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1, gap: 3 }}>
              <div style={{ width: '100%', height: `${(d / maxInterval) * 44}px`, background: 'var(--fg-3)', borderRadius: '2px 2px 0 0', minHeight: 3, opacity: 0.7 + (d / maxInterval) * 0.3 }} />
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 8, color: 'var(--fg-4)', letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>{SM2_LABELS[i]}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Rating buttons */}
      <div style={{ display: 'flex', gap: 6 }}>
        {GRADES.map((g) => {
          const picked = grade === g.id;
          return (
            <button key={g.id} onClick={() => setGrade(g.id)}
              style={{
                flex: 1, height: 48, borderRadius: 8, cursor: 'pointer',
                background: picked ? 'var(--fg)' : (g.id === 'good' ? 'var(--surface-3)' : 'var(--surface-2)'),
                color: picked ? '#000' : 'var(--fg)',
                border: picked ? 'none' : `1px solid var(--border${g.id === 'good' ? '-strong' : ''})`,
                fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
                transition: 'all var(--dur-2) var(--ease-out)',
              }}>
              <span>{g.label}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: picked ? '#444' : 'var(--fg-3)', fontWeight: 400 }}>{g.next}</span>
            </button>
          );
        })}
      </div>
    </AlgoPanel>
  );
};

/* ---- FSRS-6 Panel ---- */

/* Forgetting curve SVG - exponential decay from 100% at t=0 */
const ForgettingCurve = () => {
  const W = 280; const H = 80;
  const pts = Array.from({ length: 40 }, (_, i) => {
    const t = i / 39;
    const y = Math.exp(-2.5 * t);
    return `${(t * (W - 20) + 10).toFixed(1)},${((1 - y) * (H - 20) + 4).toFixed(1)}`;
  }).join(' ');

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 80 }}>
      <line x1="10" y1={H - 4} x2={W - 10} y2={H - 4} stroke="var(--border)" strokeWidth="0.8" />
      <line x1="10" y1="4" x2="10" y2={H - 4} stroke="var(--border)" strokeWidth="0.8" />
      <polyline points={pts} fill="none" stroke="var(--accent-cool-2)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" opacity="0.8" />
      <line x1="10" y1={((1 - 0.9) * (H - 20) + 4).toFixed(1)} x2={W - 10} y2={((1 - 0.9) * (H - 20) + 4).toFixed(1)}
        stroke="var(--fg)" strokeWidth="0.8" strokeDasharray="3 3" opacity="0.4" />
      <text x={W - 9} y={((1 - 0.9) * (H - 20) + 3).toFixed(1)} textAnchor="end" fontFamily="var(--font-mono)" fontSize="8" fill="var(--fg-3)">90%</text>
      <text x="12" y={H - 8} fontFamily="var(--font-mono)" fontSize="7.5" fill="var(--fg-4)">now</text>
      <text x={W - 10} y={H - 8} textAnchor="end" fontFamily="var(--font-mono)" fontSize="7.5" fill="var(--fg-4)">next review</text>
    </svg>
  );
};

const FSRSPanel = () => (
  <AlgoPanel style={{ border: '1px solid var(--border-strong)', background: 'var(--surface-2)' }}>
    {/* Label + badge */}
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent-cool-2)', flexShrink: 0, boxShadow: '0 0 6px var(--accent-cool-glow)' }} />
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--accent-cool-2)' }}>FSRS-6</span>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg)', letterSpacing: '0.1em', textTransform: 'uppercase', padding: '2px 8px', borderRadius: 999, background: 'var(--surface-4)', border: '1px solid var(--border-strong)' }}>Advanced</span>
    </div>

    {/* Description */}
    <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6, color: 'var(--fg-2)', letterSpacing: '-0.011em' }}>
      FSRS-6 models your actual forgetting curve. It tracks stability and difficulty per card to schedule reviews at 90% desired retention.
    </p>

    {/* Key metrics */}
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
      {[
        ['Stability', '14.2d'],
        ['Difficulty', '5.6 / 10'],
        ['Retrievability', '91%'],
        ['Next review', '+14d'],
      ].map(([k, v]) => (
        <div key={k} style={{ padding: '10px 12px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 9 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg-3)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{k}</div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 17, color: 'var(--fg)', marginTop: 3, fontVariantNumeric: 'tabular-nums' }}>{v}</div>
        </div>
      ))}
    </div>

    {/* Forgetting curve */}
    <div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--fg-3)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>Retrievability over time</div>
      <ForgettingCurve />
    </div>

    {/* Feature callouts */}
    <div style={{ display: 'flex', flexDirection: 'column', gap: 7, paddingTop: 4, borderTop: '1px solid var(--border)' }}>
      {[
        'Per-card stability and difficulty tracking',
        'Targets 90% desired retention rate',
        'Adapts faster to your personal memory pattern',
      ].map((t) => (
        <div key={t} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', fontSize: 13, color: 'var(--fg-2)', letterSpacing: '-0.011em' }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent-cool-2)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}>
            <polyline points="20 6 9 17 4 12" />
          </svg>
          {t}
        </div>
      ))}
    </div>
  </AlgoPanel>
);

const AlgorithmCompare = () => (
  <section className="section" style={{ display: 'flex', flexDirection: 'column', gap: 56, borderTop: '1px solid var(--border)' }}>
    <Reveal>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 720 }}>
        <span className="eyebrow">Spaced repetition</span>
        <h2 className="h-display">
          Two algorithms. <span className="dim">You choose.</span>
        </h2>
        <p style={{ margin: 0, fontSize: 17, lineHeight: 1.6, color: 'var(--fg-2)', letterSpacing: '-0.011em', maxWidth: 600 }}>
          SM-2 is the battle-tested classic - simple, reliable, used by millions. FSRS-6 is the modern default, modelling your personal forgetting curve for smarter scheduling. Switch any time in Settings.
        </p>
      </div>
    </Reveal>

    <Reveal delay={120}>
      <div className="algo-grid" style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, alignItems: 'stretch',
      }}>
        <SM2Panel />
        <FSRSPanel />
      </div>
    </Reveal>
  </section>
);

/* Keep SM2Visualizer as an alias so existing app.jsx import still works */
const SM2Visualizer = AlgorithmCompare;

Object.assign(window, { SM2Visualizer, AlgorithmCompare });
