/* global React */
const { useState: useFGState, useEffect: useFGEffect } = React;
const _fgReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

/* ── Shared app-chrome tokens ────────────────────────────────── */
const _C = {
  bg:     'var(--bg)',
  s2:     'var(--surface-2)',
  s3:     'var(--surface-3)',
  border: 'var(--border)',
  bStr:   'var(--border-strong)',
  fg:     'var(--fg)',
  fg2:    'var(--fg-2)',
  fg3:    'var(--fg-3)',
};

/* ── Cell wrapper ────────────────────────────────────────────── */
const FGCell = ({ num, wide, children, delay = 0, style = {} }) => {
  const ref = React.useRef(null);
  useFGEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (_fgReduced) return;
    el.style.opacity = '0';
    el.style.transform = 'translateY(18px)';
    el.style.transition = 'opacity 0.65s cubic-bezier(0.22,1,0.36,1), transform 0.65s cubic-bezier(0.22,1,0.36,1)';
    el.dataset.fgDelay = String(delay);
    const io = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      setTimeout(() => {
        el.style.opacity = '1';
        el.style.transform = 'none';
      }, delay);
      io.disconnect();
    }, { threshold: 0.08, rootMargin: '0px 0px -40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <div
      ref={ref}
      className={`fg-cell${wide ? ' fg-cell-wide' : ''}`}
      style={style}
    >
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 10,
        background: 'var(--accent-cool-gradient)',
        WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text',
        letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 32,
      }}>{num}</div>
      {children}
    </div>
  );
};

/* ── CELL 1 (wide): FSRS-6 + flip card demo ─────────────────── */
const Cell1FSRS = () => {
  const [flipped, setFlipped] = useFGState(false);

  return (
    <div className="fg-cell-inner" style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60, alignItems: 'center',
    }}>
      {/* Text side */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <h2 style={{
          margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700,
          fontSize: 'clamp(28px, 3.2vw, 40px)', lineHeight: 1.1,
          letterSpacing: '-0.03em', color: 'var(--fg)',
        }}>Powered by FSRS-6.</h2>
        <p style={{
          margin: 0, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.7,
          color: 'var(--fg-3)', letterSpacing: '-0.005em', maxWidth: 380,
        }}>
          The same algorithm as Anki, rebuilt from the ground up. Shows cards exactly when you're about to forget them — not a minute sooner.
        </p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', boxShadow: '0 0 8px rgba(255,107,107,0.5)' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'rgba(255,107,107,0.75)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>FSRS-6 algorithm</span>
        </div>
      </div>

      {/* Flip card demo */}
      <div
        role="button"
        aria-label={flipped ? 'Showing answer — click to reset' : 'Click to reveal answer'}
        tabIndex={0}
        onClick={() => setFlipped((f) => !f)}
        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') setFlipped((f) => !f); }}
        style={{
          cursor: 'pointer', perspective: 1000,
          height: 220, userSelect: 'none',
        }}
      >
        <div className={`flip-card-inner${flipped ? ' flipped' : ''}`} style={{ width: '100%', height: '100%', position: 'relative' }}>
          {/* Front */}
          <div className="flip-card-face" style={{
            position: 'absolute', inset: 0,
            background: _C.s2, border: `1px solid ${_C.bStr}`,
            borderRadius: 16, padding: 28,
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
          }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: _C.fg3, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Front</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, letterSpacing: '-0.02em', color: _C.fg, textAlign: 'center' }}>
              What is the capital of Japan?
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: _C.fg3, textAlign: 'right', letterSpacing: '0.06em' }}>click to flip</div>
          </div>
          {/* Back */}
          <div className="flip-card-face flip-card-back" style={{
            position: 'absolute', inset: 0,
            background: _C.s2, border: '1px solid rgba(255,107,107,0.25)',
            borderRadius: 16, padding: 28,
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
          }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: _C.fg3, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Answer</div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 32, letterSpacing: '-0.03em', color: 'var(--fg)', marginBottom: 8 }}>Tokyo</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: _C.fg3 }}>東京 · Tōkyō</div>
            </div>
            {/* Rating row */}
            <div style={{ display: 'flex', gap: 6 }}>
              {[['Again', '< 1m', false], ['Hard', '6m', false], ['Good', '1d', true], ['Easy', '4d', false]].map(([lbl, hint, hi]) => (
                <div key={lbl} style={{
                  flex: 1, padding: '7px 0', borderRadius: 8, textAlign: 'center',
                  background: hi ? 'rgba(255,107,107,0.15)' : _C.s3,
                  border: hi ? '1px solid rgba(255,107,107,0.3)' : `1px solid ${_C.border}`,
                  display: 'flex', flexDirection: 'column', gap: 2,
                }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: hi ? 'var(--accent)' : _C.fg2, letterSpacing: '-0.01em' }}>{lbl}</span>
                  <span style={{ fontSize: 9, color: _C.fg3, fontFamily: 'monospace' }}>{hint}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

/* ── CELL 2 (half): 7 card types ──────────────────────────────── */
const CARD_TYPES = ['Basic', 'Reverse', 'Cloze', 'Multiple choice', 'True / False', 'Code', 'Image'];

const Cell2CardTypes = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 20, height: '100%' }}>
    <div>
      <h2 style={{
        margin: '0 0 16px', fontFamily: 'var(--font-display)', fontWeight: 700,
        fontSize: 'clamp(24px, 2.8vw, 34px)', lineHeight: 1.1, letterSpacing: '-0.03em', color: 'var(--fg)',
      }}>Seven card types.</h2>
      <p style={{
        margin: 0, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.65, color: 'var(--fg-3)', letterSpacing: '-0.005em',
      }}>
        Basic flash cards, cloze deletions, multiple choice, code blocks, images, and more.
      </p>
    </div>
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 4 }}>
      {CARD_TYPES.map((t, i) => (
        <div key={t} style={{
          padding: '6px 13px', borderRadius: 999, fontSize: 13, fontWeight: 500,
          background: i === 2 ? 'rgba(255,107,107,0.1)' : _C.s2,
          border: `1px solid ${i === 2 ? 'rgba(255,107,107,0.25)' : _C.border}`,
          color: i === 2 ? 'rgba(255,107,107,0.85)' : _C.fg2,
          letterSpacing: '-0.011em',
        }}>{t}</div>
      ))}
    </div>
  </div>
);

/* ── CELL 3 (half): Buy once pricing ──────────────────────────── */
const Cell3Pricing = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
    <div>
      <h2 style={{
        margin: '0 0 16px', fontFamily: 'var(--font-display)', fontWeight: 700,
        fontSize: 'clamp(24px, 2.8vw, 34px)', lineHeight: 1.1, letterSpacing: '-0.03em', color: 'var(--fg)',
      }}>Buy it once.</h2>
      <p style={{
        margin: 0, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.65, color: 'var(--fg-3)', letterSpacing: '-0.005em',
      }}>
        No subscriptions. No locked features. Pay once, use forever.
      </p>
    </div>
    <div style={{
      display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4,
    }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: _C.fg3, textDecoration: 'line-through' }}>$24</span>
      <span style={{
        fontFamily: 'var(--font-display)', fontWeight: 800,
        fontSize: 'clamp(48px, 6vw, 72px)', letterSpacing: '-0.045em', color: 'var(--fg)', lineHeight: 1,
      }}>$12</span>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: _C.fg3, letterSpacing: '0.04em' }}>AUD</span>
    </div>
    <div style={{
      display: 'inline-flex', alignSelf: 'flex-start', padding: '4px 12px', borderRadius: 999,
      background: 'rgba(255,107,107,0.1)', border: '1px solid rgba(255,107,107,0.25)',
      fontFamily: 'var(--font-mono)', fontSize: 10, color: 'rgba(255,107,107,0.8)',
      letterSpacing: '0.07em', textTransform: 'uppercase',
    }}>First 100 users · 50% off</div>
  </div>
);

/* ── CELL 4 (wide): Stats visualization ───────────────────────── */
const STATS_DATA = [
  { day: 'Mon', cards: 42, due: 14 },
  { day: 'Tue', cards: 67, due: 22 },
  { day: 'Wed', cards: 31, due: 8  },
  { day: 'Thu', cards: 89, due: 31 },
  { day: 'Fri', cards: 54, due: 18 },
  { day: 'Sat', cards: 76, due: 25 },
  { day: 'Sun', cards: 48, due: 16 },
];
const STATS_MAX = 100;

const Cell4Stats = () => (
  <div className="fg-cell-inner" style={{
    display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60, alignItems: 'center',
  }}>
    {/* Bar chart */}
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: _C.fg3, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Cards reviewed this week</div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 100 }}>
        {STATS_DATA.map(({ day, cards }) => (
          <div key={day} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, height: '100%', justifyContent: 'flex-end' }}>
            <div style={{
              width: '100%', borderRadius: '4px 4px 0 0',
              height: `${(cards / STATS_MAX) * 100}%`,
              background: day === 'Thu'
                ? 'linear-gradient(to top, var(--accent), var(--accent-warm))'
                : 'rgba(255,255,255,0.07)',
              transition: 'height 0.6s cubic-bezier(0.22,1,0.36,1)',
            }} />
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: _C.fg3, letterSpacing: '0.06em' }}>{day}</div>
          </div>
        ))}
      </div>
    </div>

    {/* Text side */}
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <h2 style={{
        margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700,
        fontSize: 'clamp(24px, 2.8vw, 34px)', lineHeight: 1.1, letterSpacing: '-0.03em', color: 'var(--fg)',
      }}>Know your progress.</h2>
      <p style={{
        margin: 0, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.7, color: 'var(--fg-3)', letterSpacing: '-0.005em',
      }}>
        Streak tracking, card maturity, per-deck stats, and forecast. See exactly what's coming and how far you've come.
      </p>
      {/* Summary chips */}
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        {[['407', 'cards this week'], ['94%', 'retention'], ['18', 'day streak']].map(([val, lbl]) => (
          <div key={lbl} style={{
            display: 'flex', flexDirection: 'column', gap: 3,
            padding: '12px 18px', background: _C.s2,
            border: `1px solid ${_C.border}`, borderRadius: 12,
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 20, color: 'var(--fg)', letterSpacing: '-0.02em' }}>{val}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: _C.fg3, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{lbl}</span>
          </div>
        ))}
      </div>
    </div>
  </div>
);

/* ── CELL 5 (half): Study modes ───────────────────────────────── */
const MODES = [
  { label: 'Classic',     desc: 'Flip and grade',      dot: 'var(--accent-warm)' },
  { label: 'Type',        desc: 'Type your answer',    dot: 'var(--fg-3)' },
  { label: 'Speed round', desc: '4 seconds per card',  dot: 'var(--accent)' },
];

const Cell5Modes = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 20, height: '100%' }}>
    <div>
      <h2 style={{
        margin: '0 0 16px', fontFamily: 'var(--font-display)', fontWeight: 700,
        fontSize: 'clamp(24px, 2.8vw, 34px)', lineHeight: 1.1, letterSpacing: '-0.03em', color: 'var(--fg)',
      }}>Three study modes.</h2>
      <p style={{
        margin: 0, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.65, color: 'var(--fg-3)', letterSpacing: '-0.005em',
      }}>
        Learn the way that suits you — or switch it up for variety.
      </p>
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 4 }}>
      {MODES.map((m) => (
        <div key={m.label} style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '13px 16px', borderRadius: 10,
          background: _C.s2, border: `1px solid ${_C.border}`,
        }}>
          <div style={{ width: 7, height: 7, borderRadius: '50%', background: m.dot, flexShrink: 0 }} />
          <span style={{ fontSize: 14, fontWeight: 600, color: _C.fg, letterSpacing: '-0.011em' }}>{m.label}</span>
          <span style={{ fontSize: 12, color: _C.fg3, letterSpacing: '-0.01em', marginLeft: 'auto' }}>{m.desc}</span>
        </div>
      ))}
    </div>
  </div>
);

/* ── CELL 6 (half): Import ────────────────────────────────────── */
const Cell6Import = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
    <div>
      <h2 style={{
        margin: '0 0 16px', fontFamily: 'var(--font-display)', fontWeight: 700,
        fontSize: 'clamp(24px, 2.8vw, 34px)', lineHeight: 1.1, letterSpacing: '-0.03em', color: 'var(--fg)',
      }}>Import your decks.</h2>
      <p style={{
        margin: 0, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.65, color: 'var(--fg-3)', letterSpacing: '-0.005em',
      }}>
        Bring your existing cards over. Supports Anki .apkg files and plain CSV.
      </p>
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 4 }}>
      {[
        { name: 'Anki', ext: '.apkg', color: 'var(--accent-warm)' },
        { name: 'CSV',  ext: '.csv',  color: 'var(--fg-2)' },
      ].map(({ name, ext, color }) => (
        <div key={name} style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '13px 16px', borderRadius: 10,
          background: _C.s2, border: `1px solid ${_C.border}`,
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 6, background: `${color}20`,
            border: `1px solid ${color}40`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-mono)', fontSize: 8, color, fontWeight: 600, letterSpacing: '0.04em',
          }}>{name}</div>
          <span style={{ fontSize: 14, fontWeight: 600, color: _C.fg, letterSpacing: '-0.011em' }}>{name}</span>
          <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: _C.fg3, marginLeft: 'auto' }}>{ext}</span>
        </div>
      ))}
    </div>
  </div>
);

/* ── Main grid ────────────────────────────────────────────────── */
const FeaturesGrid = () => (
  <div id="features" style={{ padding: '0 0 0 0', maxWidth: 1200, margin: '0 auto', paddingLeft: 32, paddingRight: 32 }}>
    <div className="fg-grid">
      <FGCell num="01" wide delay={0}>
        <Cell1FSRS />
      </FGCell>

      <FGCell num="02" delay={100}>
        <Cell2CardTypes />
      </FGCell>

      <FGCell num="03" delay={200}>
        <Cell3Pricing />
      </FGCell>

      <FGCell num="04" wide delay={150}>
        <Cell4Stats />
      </FGCell>

      <FGCell num="05" delay={100}>
        <Cell5Modes />
      </FGCell>

      <FGCell num="06" delay={200}>
        <Cell6Import />
      </FGCell>
    </div>
  </div>
);

/* Keep legacy export for sub-pages */
const FEATURE_ROWS_DATA = [];

Object.assign(window, { FeaturesGrid, FEATURE_ROWS_DATA });
