/* global React, Reveal */
const { useState: useSMSt, useEffect: useSMEf, useRef: useSMRef } = React;

/* App design tokens */
const AC = {
  bg:        'var(--bg)',
  surface:   'var(--surface)',
  s2:        'var(--surface-2)',
  s3:        'var(--surface-3)',
  border:    'var(--border)',
  borderStr: 'var(--border-strong)',
  fg:        'var(--fg)',
  fg2:       'var(--fg-2)',
  fg3:       'var(--fg-3)',
  fg4:       'var(--fg-4)',
  green:     'var(--accent)',
};

const dotBg = {
  background: AC.bg,
  backgroundImage: 'radial-gradient(circle, rgba(255,255,255,0.07) 1px, transparent 1px)',
  backgroundSize: '24px 24px',
};

const STUDY_MODES = [
  { id: 'classic', label: 'Classic', blurb: 'See front, reveal back, grade your recall.', color: 'var(--accent-warm)' },
  { id: 'typed',   label: 'Type',    blurb: 'Type the answer to lock it into memory.',    color: 'var(--accent-cool)' },
  { id: 'speed',   label: 'Speed',   blurb: 'Rapid-fire reviews against the clock.',      color: 'var(--accent)' },
];

/* ---- Shared: card face shell ---- */
const CardFace = ({ children, style }) => (
  <div style={{
    background: AC.surface, border: `1px solid ${AC.borderStr}`,
    borderRadius: 16, padding: '32px 32px',
    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
    minHeight: 200, textAlign: 'center',
    ...style,
  }}>{children}</div>
);

/* ============================================================
   Classic Flip - 3D rotateY flip animation
   ============================================================ */
const CLASSIC_QA = [
  { front: 'What is the powerhouse of the cell?', back: 'Mitochondria' },
  { front: 'What gas do plants absorb during photosynthesis?', back: 'Carbon dioxide (CO2)' },
  { front: 'What is the chemical symbol for gold?', back: 'Au' },
];

const RATING_BTNS = [
  { label: 'Again', kbd: '1', hint: '< 1m', primary: false },
  { label: 'Hard',  kbd: '2', hint: '6m',   primary: false },
  { label: 'Good',  kbd: '3', hint: '1d',   primary: true  },
  { label: 'Easy',  kbd: '4', hint: '4d',   primary: false },
];

const ClassicMode = ({ onDone }) => {
  const [flipped,  setFlipped]  = useSMSt(false);
  const [bouncing, setBouncing] = useSMSt(false);

  useSMEf(() => {
    // Phase 1: show front 2s, Phase 2: bounce 300ms, Phase 3: fade in back 2s
    const t1 = setTimeout(() => setBouncing(true), 2000);
    const t2 = setTimeout(() => { setBouncing(false); setFlipped(true); }, 2300);
    const t3 = setTimeout(onDone, 4300);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);

  const card = CLASSIC_QA[0];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      <style>{`
        @keyframes cardBounce { 0%,100% { transform: scale(1); } 50% { transform: scale(1.04); } }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
      `}</style>
      <div style={{ textAlign: 'center', marginBottom: 14 }}>
        <span style={{ fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace", fontSize: 10, color: AC.fg3, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
          {flipped ? 'BACK' : 'FRONT'} · CLICK CARD OR PRESS{' '}
          <span style={{ display: 'inline-block', background: AC.s2, border: `1px solid ${AC.border}`, borderRadius: 4, padding: '1px 6px', fontSize: 9.5, letterSpacing: '0.04em' }}>SPACE</span>
          {' '}TO FLIP
        </span>
      </div>

      <div style={{
        background: AC.surface, border: `1px solid ${AC.borderStr}`,
        borderRadius: 16, padding: '32px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        minHeight: 200, textAlign: 'center',
        margin: '0 16px',
        animation: bouncing ? 'cardBounce 300ms ease-out both' : 'none',
      }}>
        {flipped ? (
          <div style={{ fontWeight: 800, fontSize: 24, color: AC.fg, letterSpacing: '-0.025em', lineHeight: 1.2, animation: 'fadeIn 250ms ease both' }}>
            {card.back}
          </div>
        ) : (
          <div style={{ fontWeight: 800, fontSize: 24, color: AC.fg, letterSpacing: '-0.025em', lineHeight: 1.2, textWrap: 'balance', maxWidth: 480, margin: '0 auto' }}>
            {card.front}
          </div>
        )}
      </div>

      {/* Bar zone — empty for Classic, reserved for layout consistency */}
      <div style={{ height: 2, margin: '8px 16px 0' }} />

      <div style={{ margin: '12px 16px 0' }}>
        {flipped ? (
          <div style={{ display: 'flex', gap: 10, animation: 'fadeIn 250ms ease both' }}>
            {RATING_BTNS.map((b) => (
              <div key={b.label} style={{
                flex: 1, height: 64, borderRadius: 10, cursor: 'default',
                background: b.primary ? AC.fg : AC.surface, color: b.primary ? AC.bg : AC.fg,
                border: b.primary ? 'none' : `1px solid ${AC.border}`,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ fontWeight: 600, fontSize: 14 }}>{b.label}</span>
                  <span style={{ fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace", fontSize: 10, opacity: 0.5 }}>{b.kbd}</span>
                </div>
                <span style={{ fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace", fontSize: 11, color: b.primary ? 'rgba(0,0,0,0.5)' : AC.fg3 }}>{b.hint}</span>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <div style={{ padding: '11px 36px', background: AC.fg, color: AC.bg, borderRadius: 10, fontSize: 14, fontWeight: 600, cursor: 'default' }}>
              Show answer
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

/* ============================================================
   Typed Quiz
   ============================================================ */
const TYPED_FRONT  = 'What is the powerhouse of the cell?';
const TYPED_ANSWER = 'Mitochondria';

const TypedMode = ({ onDone }) => {
  const [typed,  setTyped]  = useSMSt('');
  const [phase,  setPhase]  = useSMSt('idle');

  useSMEf(() => {
    // Phase 1: idle 1s, Phase 2: type chars over 1s, Phase 3: correct 1s
    const perChar = Math.floor(1000 / TYPED_ANSWER.length);
    const timers = [];
    TYPED_ANSWER.split('').forEach((_, i) => {
      timers.push(setTimeout(() => {
        setTyped(TYPED_ANSWER.slice(0, i + 1));
        if (i === 0) setPhase('typing');
      }, 1000 + i * perChar));
    });
    timers.push(setTimeout(() => setPhase('correct'), 2000));
    timers.push(setTimeout(onDone, 4000));
    return () => timers.forEach(clearTimeout);
  }, []);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      <div style={{ textAlign: 'center', marginBottom: 14 }}>
        <span style={{ fontFamily: 'monospace', fontSize: 10, color: AC.fg3, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
          Type Your Answer
        </span>
      </div>
      <CardFace>
        <div style={{ fontWeight: 800, fontSize: 22, color: AC.fg, letterSpacing: '-0.025em', lineHeight: 1.3, textWrap: 'balance', maxWidth: 460, margin: '0 auto' }}>
          {TYPED_FRONT}
        </div>
      </CardFace>
      <div style={{ marginTop: 12, padding: '14px 20px', background: AC.surface, border: `1px solid ${phase === 'correct' ? AC.fg : AC.border}`, borderRadius: 10, transition: 'border-color 200ms ease', minHeight: 52, display: 'flex', alignItems: 'center' }}>
        <span style={{ fontWeight: 700, fontSize: 17, color: AC.fg, letterSpacing: '-0.011em', flex: 1 }}>
          {typed}
          {phase === 'typing' && (
            <span style={{ display: 'inline-block', width: 2, height: 17, background: AC.fg, marginLeft: 2, verticalAlign: 'middle', animation: 'blink 1s steps(1) infinite' }} />
          )}
          <style>{`@keyframes blink { 50% { opacity: 0; } }`}</style>
        </span>
      </div>
      {phase === 'correct' && (
        <div style={{ textAlign: 'center', marginTop: 10, fontFamily: 'monospace', fontSize: 10.5, color: AC.green, letterSpacing: '0.16em', textTransform: 'uppercase', animation: 'fadeIn 180ms ease both' }}>
          Correct
        </div>
      )}
      {phase !== 'correct' && (
        <div style={{ textAlign: 'center', marginTop: 8, fontFamily: 'monospace', fontSize: 10, color: AC.fg3, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          Press Enter to check
        </div>
      )}
      {/* Bar zone — empty for Type, reserved for layout consistency */}
      <div style={{ height: 2, marginTop: 8 }} />
    </div>
  );
};

/* ============================================================
   Speed Round
   ============================================================ */
const SPEED_CARDS   = ['What is the powerhouse of the cell?', 'What planet is closest to the sun?', 'What is H2O commonly known as?'];
const SPEED_ANSWERS = ['Mitochondria', 'Mercury', 'Water'];

const SpeedMode = ({ onDone }) => {
  const [timer,    setTimer]    = useSMSt(4);
  const [bouncing, setBouncing] = useSMSt(false);
  const [revealed, setRevealed] = useSMSt(false);

  useSMEf(() => {
    // Phase 1: count 4→0 (4s), Phase 2: bounce 300ms, Phase 3: fadeIn reveal + hold 2s
    const t1 = setTimeout(() => setTimer(3), 1000);
    const t2 = setTimeout(() => setTimer(2), 2000);
    const t3 = setTimeout(() => setTimer(1), 3000);
    const t4 = setTimeout(() => { setTimer(0); setBouncing(true); }, 4000);
    const t5 = setTimeout(() => { setBouncing(false); setRevealed(true); }, 4300);
    const t6 = setTimeout(onDone, 6300);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); clearTimeout(t4); clearTimeout(t5); clearTimeout(t6); };
  }, []);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      <style>{`
        @keyframes cardBounce { 0%,100% { transform: scale(1); } 50% { transform: scale(1.04); } }
        @keyframes shrinkBar { from { width: 100%; } to { width: 0%; } }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
      `}</style>
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 7, marginBottom: 14 }}>
        <span style={{
          width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
          background: timer <= 1 ? 'var(--accent)' : AC.fg,
          boxShadow: timer <= 1 ? '0 0 8px var(--accent-glow-strong)' : 'none',
          transition: 'background 200ms',
        }} />
        <span style={{ fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace", fontSize: 18, fontWeight: 500, fontVariantNumeric: 'tabular-nums', color: timer <= 1 ? 'var(--accent)' : AC.fg, transition: 'color 200ms' }}>
          0:{String(timer).padStart(2, '0')}
        </span>
      </div>
      <div style={{
        background: AC.surface, border: `1px solid ${AC.borderStr}`,
        borderRadius: 16, padding: '28px 32px 20px',
        display: 'flex', flexDirection: 'column', gap: 12,
        margin: '0 16px',
        animation: bouncing ? 'cardBounce 300ms ease-out both' : 'none',
      }}>
        <div style={{ fontWeight: 800, fontSize: 22, color: AC.fg, letterSpacing: '-0.025em', lineHeight: 1.2 }}>
          {SPEED_CARDS[0]}
        </div>
        {revealed ? (
          <div style={{ paddingTop: 10, borderTop: `1px solid ${AC.border}`, animation: 'fadeIn 250ms ease both' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace", fontSize: 12, color: AC.fg3 }}>-&gt;</span>
              <span style={{ fontSize: 14, color: AC.fg2, fontWeight: 500 }}>{SPEED_ANSWERS[0]}</span>
            </div>
          </div>
        ) : (
          <div style={{ fontSize: 11.5, color: AC.fg3, fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace" }}>press any key to reveal</div>
        )}
      </div>
      {/* Bar zone — countdown bar for Speed, consistent position with other modes */}
      <div style={{ height: 2, margin: '8px 16px 0', background: AC.s3, borderRadius: 999, overflow: 'hidden' }}>
        {!revealed && (
          <div style={{ height: '100%', borderRadius: 999, background: timer <= 1 ? 'var(--accent)' : AC.fg, transition: 'background 200ms', animation: 'shrinkBar 4s linear both' }} />
        )}
      </div>
      <div style={{ margin: '12px 16px 0' }}>
        {revealed ? (
          <div style={{ display: 'flex', gap: 10, animation: 'fadeIn 250ms ease both' }}>
            <div style={{ flex: 1, height: 50, borderRadius: 10, background: AC.surface, border: `1px solid ${AC.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: 'default' }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
              </svg>
              <span style={{ fontWeight: 600, fontSize: 13.5, color: AC.fg }}>Forgot</span>
              <span style={{ fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace", fontSize: 10, color: AC.fg3, padding: '1px 5px', background: AC.s2, border: `1px solid ${AC.border}`, borderRadius: 4 }}>←</span>
            </div>
            <div style={{ flex: 1, height: 50, borderRadius: 10, background: AC.fg, color: AC.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: 'default' }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12"/>
              </svg>
              <span style={{ fontWeight: 600, fontSize: 13.5 }}>Got it</span>
              <span style={{ fontFamily: "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace", fontSize: 10, padding: '1px 5px', background: 'rgba(0,0,0,0.15)', borderRadius: 4 }}>→</span>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
};

/* ============================================================
   StudyModes container - fade transition between modes
   ============================================================ */
const StudyModes = () => {
  const [active,   setActive]  = useSMSt('classic');
  const [visible,  setVisible] = useSMSt(true);
  const pausedUntil = useSMRef(0);

  const switchTo = (id) => {
    if (id === active) return;
    pausedUntil.current = Date.now() + 20000;
    setVisible(false);
    setTimeout(() => { setActive(id); setVisible(true); }, 300);
  };

  const goNext = () => {
    if (Date.now() < pausedUntil.current) return;
    setVisible(false);
    setTimeout(() => {
      setActive((a) => { const idx = STUDY_MODES.findIndex((m) => m.id === a); return STUDY_MODES[(idx + 1) % STUDY_MODES.length].id; });
      setVisible(true);
    }, 300);
  };

  const mode = STUDY_MODES.find((m) => m.id === active);

  return (
    <section className="section" style={{ borderTop: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 48 }}>
      <Reveal>
        <div className="study-modes-header" style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 40, alignItems: 'end' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 640 }}>
            <span className="eyebrow">Study modes</span>
            <h2 className="h-display">Three ways <span className="dim">to lock it in.</span></h2>
          </div>
          <p style={{ margin: 0, fontSize: 16, lineHeight: 1.6, color: 'var(--fg-2)', maxWidth: 380, letterSpacing: '-0.011em' }}>
            Different cards reward different techniques. Recall ships every mode worth using and gets out of the way.
          </p>
        </div>
      </Reveal>

      <Reveal delay={100}>
        <div className="study-modes-tabs" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, borderBottom: '1px solid var(--border)' }}>
          {STUDY_MODES.map((m) => {
            const isActive = m.id === active;
            return (
              <button key={m.id} onClick={() => switchTo(m.id)}
                style={{
                  padding: '20px 4px', textAlign: 'left', background: 'transparent', border: 'none', cursor: 'pointer',
                  borderBottom: `2px solid ${isActive ? m.color : 'transparent'}`,
                  color: isActive ? m.color : 'var(--fg-3)',
                  transition: 'color var(--dur-2) var(--ease-out), border-color var(--dur-2) var(--ease-out)',
                  fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 22, letterSpacing: '-0.025em',
                  display: 'flex', flexDirection: 'column', gap: 4,
                }}
                onMouseEnter={(e) => { if (!isActive) e.currentTarget.style.color = 'var(--fg-2)'; }}
                onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.color = 'var(--fg-3)'; }}
              >
                <span>{m.label}</span>
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 400, fontSize: 13, color: 'var(--fg-3)', letterSpacing: '-0.011em' }}>{m.blurb}</span>
              </button>
            );
          })}
        </div>
      </Reveal>

      <Reveal delay={160}>
        <div className="study-modes-content" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.35fr) minmax(0, 1fr)', gap: 32, alignItems: 'start' }}>
          {/* Preview pane - fades between modes */}
          <div style={{
            height: 420, overflow: 'hidden',
            opacity: visible ? 1 : 0,
            transition: 'opacity 300ms ease',
          }}>
            {active === 'classic' && <ClassicMode onDone={goNext} />}
            {active === 'typed'   && <TypedMode   onDone={goNext} />}
            {active === 'speed'   && <SpeedMode   onDone={goNext} />}
          </div>
          {/* Description pane */}
          <div style={{
            display: 'flex', flexDirection: 'column', gap: 18, padding: '24px 0 0 0',
            opacity: visible ? 1 : 0,
            transition: 'opacity 300ms ease',
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Auto-cycling demo</span>
            <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 32, letterSpacing: '-0.025em', color: 'var(--fg)' }}>{mode.label}</h3>
            <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: 'var(--fg-2)', letterSpacing: '-0.011em' }}>
              {active === 'classic'
                ? 'The fastest path to recall. See the front, reveal the answer, grade honestly. The algorithm schedules each card at exactly the right interval.'
                : active === 'typed'
                ? 'Typing forces commitment. The app matches your answer generously so a missing accent or typo will not mark you wrong. Best for languages and specific terminology.'
                : 'Four seconds per card. A countdown timer drives urgency. When time runs out, grade yourself: Got it or Forgot. Best for high-frequency vocab and quick drills.'}
            </p>
          </div>
        </div>
      </Reveal>
    </section>
  );
};

Object.assign(window, { StudyModes });
