// Direction A — Storybook Sketch
// Cream paper, hand-drawn wobbly borders (SVG turbulence filter), crayon
// scribble accents. Patrick Hand + Caveat. Drifting sketched leaves.

const sketchSubjects = {
  math:    { label: 'Math',    ink: '#D9602B', fill: '#FFE6D2' },
  words:   { label: 'Words',   ink: '#3E8E5A', fill: '#DDF0DF' },
  science: { label: 'Science', ink: '#2E5C8A', fill: '#D6E5F2' },
  world:   { label: 'World',   ink: '#B0431F', fill: '#F4D7C5' },
  music:   { label: 'Music',   ink: '#8A4FB3', fill: '#E8D9F2' },
  code:    { label: 'Code',    ink: '#B8861A', fill: '#F4E6BD' },
  focus:   { label: 'Focus',   ink: '#1F7A7A', fill: '#CFEAEA' },
};

// Tiny crayon doodles — one per subject. Kept abstract on purpose: an
// acorn for math, a quill for words, a beaker for science, a globe for
// world, a music note, a bracket for code.
const sketchDoodles = {
  math: (
    <svg viewBox="0 0 80 80" width="100%" height="100%">
      <ellipse cx="40" cy="50" rx="20" ry="22" fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinecap="round" />
      <path d="M22 32 Q40 22 58 32 Q56 38 40 38 Q24 38 22 32 Z" fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinejoin="round" />
      <path d="M40 22 L40 14" stroke="#5a3a1a" strokeWidth="2.5" strokeLinecap="round" />
      <path d="M30 50 Q40 56 50 50" fill="none" stroke="#5a3a1a" strokeWidth="2" strokeLinecap="round" />
    </svg>
  ),
  words: (
    <svg viewBox="0 0 80 80" width="100%" height="100%">
      <path d="M18 62 L52 28 L60 36 L26 70 Z" fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinejoin="round" />
      <path d="M52 28 Q56 20 64 22 Q66 28 60 36" fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinecap="round" />
      <path d="M18 62 L14 72 L26 70" fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinejoin="round" />
    </svg>
  ),
  science: (
    <svg viewBox="0 0 80 80" width="100%" height="100%">
      <path d="M32 18 L32 36 L20 62 Q20 70 30 70 L50 70 Q60 70 60 62 L48 36 L48 18 Z" fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinejoin="round" />
      <path d="M28 18 L52 18" stroke="#5a3a1a" strokeWidth="2.5" strokeLinecap="round" />
      <circle cx="34" cy="54" r="2.5" fill="#5a3a1a" />
      <circle cx="44" cy="60" r="2" fill="#5a3a1a" />
    </svg>
  ),
  world: (
    <svg viewBox="0 0 80 80" width="100%" height="100%">
      <circle cx="40" cy="40" r="24" fill="none" stroke="#5a3a1a" strokeWidth="2.5" />
      <ellipse cx="40" cy="40" rx="10" ry="24" fill="none" stroke="#5a3a1a" strokeWidth="2" />
      <path d="M16 40 L64 40" stroke="#5a3a1a" strokeWidth="2" />
      <path d="M22 28 Q34 32 46 26 Q56 30 60 26" fill="none" stroke="#5a3a1a" strokeWidth="1.5" />
    </svg>
  ),
  music: (
    <svg viewBox="0 0 80 80" width="100%" height="100%">
      <path d="M30 56 L30 22 L58 18 L58 50" fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinejoin="round" />
      <ellipse cx="24" cy="56" rx="8" ry="6" fill="#5a3a1a" />
      <ellipse cx="52" cy="50" rx="8" ry="6" fill="#5a3a1a" />
    </svg>
  ),
  code: (
    <svg viewBox="0 0 80 80" width="100%" height="100%">
      <path d="M28 22 L14 40 L28 58" fill="none" stroke="#5a3a1a" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M52 22 L66 40 L52 58" fill="none" stroke="#5a3a1a" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M44 18 L36 62" stroke="#5a3a1a" strokeWidth="2.5" strokeLinecap="round" />
    </svg>
  ),
  focus: (
    <svg viewBox="0 0 80 80" width="100%" height="100%">
      <path d="M8 40 Q24 22 40 22 Q56 22 72 40 Q56 58 40 58 Q24 58 8 40 Z"
            fill="none" stroke="#5a3a1a" strokeWidth="2.5" strokeLinejoin="round" />
      <circle cx="50" cy="40" r="11" fill="none" stroke="#5a3a1a" strokeWidth="2" />
      <circle cx="52" cy="40" r="5" fill="#5a3a1a" />
      <circle cx="48" cy="37" r="1.6" fill="#fffaf0" />
      <circle cx="20" cy="36" r="1.4" fill="#5a3a1a" opacity="0.55" />
      <circle cx="14" cy="44" r="1.2" fill="#5a3a1a" opacity="0.4" />
    </svg>
  ),
};

function SketchLogo() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <img src="oak-ed.svg" alt="Oak-Ed" style={{ height: 56, width: 'auto', display: 'block' }} />
      <span style={{
        fontFamily: '"Caveat", cursive', fontWeight: 700, fontSize: 30,
        color: '#7a5a3a', borderLeft: '2px solid rgba(58,34,16,0.18)',
        paddingLeft: 12, lineHeight: 1,
      }}>games</span>
    </div>
  );
}

function SketchLeaf({ x, y, rot, dur, delay, color }) {
  return (
    <svg
      width="34" height="34" viewBox="0 0 40 40"
      style={{
        position: 'absolute', left: x, top: y,
        animation: `sketchDrift ${dur}s linear ${delay}s infinite`,
        transform: `rotate(${rot}deg)`, opacity: 0.55,
      }}
    >
      <path d="M20 4 Q34 16 30 30 Q22 38 14 32 Q6 24 10 14 Q14 8 20 4 Z"
            fill="none" stroke={color} strokeWidth="1.6" filter="url(#sketchRough)" />
      <path d="M20 4 Q22 18 18 32" stroke={color} strokeWidth="1.2" fill="none" />
    </svg>
  );
}

function SketchCard({ game, onClick }) {
  const subj = sketchSubjects[game.subject];
  const disabled = !game.playable;
  return (
    <button
      onClick={disabled ? undefined : onClick}
      disabled={disabled}
      style={{
        position: 'relative', textAlign: 'left', padding: 14,
        background: '#fffaf0', border: 'none',
        cursor: disabled ? 'default' : 'pointer',
        borderRadius: 8, fontFamily: 'inherit',
        opacity: disabled ? 0.45 : 1,
        filter: disabled ? 'grayscale(0.6)' : 'none',
      }}
    >
      {/* Wobbly hand-drawn border */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}
           preserveAspectRatio="none">
        <rect x="3" y="3" width="calc(100% - 6px)" height="calc(100% - 6px)"
              rx="10" ry="10" fill="none" stroke="#3a2210" strokeWidth="2"
              filter="url(#sketchRough)" />
      </svg>
      {/* Illustration well */}
      <div style={{
        height: 110, borderRadius: 6, background: subj.fill,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 12, position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ width: 78, height: 78 }}>{sketchDoodles[game.subject]}</div>
        {/* subject pill, top-right of well */}
        <span style={{
          position: 'absolute', top: 8, right: 10,
          fontFamily: '"Patrick Hand", cursive', fontSize: 13, color: subj.ink,
          padding: '2px 9px', border: `1.5px solid ${subj.ink}`, borderRadius: 12,
          background: '#fffaf0', lineHeight: 1.4,
        }}>{subj.label}</span>
      </div>
      <h3 style={{
        fontFamily: '"Caveat", cursive', fontWeight: 700, fontSize: 26,
        color: '#3a2210', margin: '0 0 4px', lineHeight: 1.05,
      }}>{game.name}</h3>
      <p style={{
        fontFamily: '"Patrick Hand", cursive', fontSize: 15, color: '#5a4a3a',
        margin: '0 0 10px', lineHeight: 1.25, minHeight: 38,
      }}>{game.desc}</p>
      {disabled ? (
        <div style={{
          fontFamily: '"Patrick Hand", cursive', fontSize: 14, color: '#9a8a7a',
          lineHeight: 1,
        }}>coming soon</div>
      ) : (
        <div style={{
          fontFamily: '"Patrick Hand", cursive', fontSize: 15, color: subj.ink,
          display: 'flex', alignItems: 'center', gap: 4, lineHeight: 1,
        }}>
          play
          <svg width="22" height="12"><path d="M2 6 L18 6 M14 2 L18 6 L14 10"
               stroke={subj.ink} strokeWidth="2" fill="none" strokeLinecap="round" /></svg>
        </div>
      )}
    </button>
  );
}

function SketchArtboard() {
  const [q, setQ] = React.useState('');
  const [active, setActive] = React.useState('all');

  const filtered = window.GAMES.filter(g => {
    if (active !== 'all' && g.subject !== active) return false;
    if (q && !(g.name + ' ' + g.desc).toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  // Random leaves — stable across renders
  const leaves = React.useMemo(() => Array.from({ length: 9 }, (_, i) => ({
    x: 80 + (i * 137) % 1100,
    y: -40 - (i * 73) % 200,
    rot: (i * 47) % 360,
    dur: 18 + (i % 5) * 4,
    delay: -(i * 2.3),
    color: ['#D9602B', '#B8861A', '#3E8E5A', '#B0431F'][i % 4],
  })), []);

  return (
    <div style={{
      position: 'relative', width: '100%', height: '100%',
      background: '#FFF6E5',
      backgroundImage: `radial-gradient(circle at 1px 1px, rgba(58,34,16,0.08) 1px, transparent 0)`,
      backgroundSize: '14px 14px',
      fontFamily: '"Patrick Hand", cursive', overflow: 'hidden',
    }}>
      {/* SVG defs: roughen filter */}
      <svg width="0" height="0" style={{ position: 'absolute' }}>
        <defs>
          <filter id="sketchRough">
            <feTurbulence type="fractalNoise" baseFrequency="0.02" numOctaves="2" seed="3" />
            <feDisplacementMap in="SourceGraphic" scale="2.5" />
          </filter>
        </defs>
      </svg>

      {/* Drifting leaves */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
        {leaves.map((l, i) => <SketchLeaf key={i} {...l} />)}
      </div>

      <div style={{ position: 'relative', padding: '32px clamp(16px, 4vw, 48px) 40px' }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexWrap: 'wrap', gap: 16, marginBottom: 24,
        }}>
          <SketchLogo />
          <div style={{ position: 'relative', width: '100%', maxWidth: 280 }}>
            <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}
                 preserveAspectRatio="none">
              <rect x="2" y="2" width="calc(100% - 4px)" height="calc(100% - 4px)"
                    rx="22" ry="22" fill="#fffaf0" stroke="#3a2210" strokeWidth="2"
                    filter="url(#sketchRough)" />
            </svg>
            <input
              value={q}
              onChange={e => setQ(e.target.value)}
              placeholder="Find a game…"
              style={{
                position: 'relative', width: '100%', boxSizing: 'border-box',
                padding: '10px 16px 10px 40px', background: 'transparent',
                border: 'none', outline: 'none',
                fontFamily: '"Patrick Hand", cursive', fontSize: 18, color: '#3a2210',
              }}
            />
            <svg style={{ position: 'absolute', left: 14, top: 12 }} width="18" height="18">
              <circle cx="7" cy="7" r="5" fill="none" stroke="#3a2210" strokeWidth="1.8" />
              <path d="M11 11 L16 16" stroke="#3a2210" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          </div>
        </div>

        {/* Hello strip */}
        <div style={{ marginBottom: 22 }}>
          <h1 style={{
            fontFamily: '"Caveat", cursive', fontWeight: 700, fontSize: 'clamp(32px, 7vw, 56px)',
            color: '#3a2210', margin: 0, lineHeight: 1,
          }}>
            Pick a game to play
            <svg width="120" height="14" style={{ display: 'block', marginTop: -4 }}>
              <path d="M4 8 Q30 2 60 9 Q90 14 116 6" stroke="#D9602B" strokeWidth="3" fill="none" strokeLinecap="round" />
            </svg>
          </h1>
        </div>

        {/* Subject chips */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 22, flexWrap: 'wrap' }}>
          {['all', ...Object.keys(sketchSubjects)].map(k => {
            const isActive = active === k;
            const subj = k === 'all'
              ? { label: 'All', ink: '#3a2210', fill: '#fffaf0' }
              : sketchSubjects[k];
            return (
              <button
                key={k}
                onClick={() => setActive(k)}
                style={{
                  position: 'relative', padding: '8px 18px', cursor: 'pointer',
                  background: isActive ? subj.ink : subj.fill,
                  color: isActive ? '#fffaf0' : subj.ink,
                  border: 'none', borderRadius: 22,
                  fontFamily: '"Patrick Hand", cursive', fontSize: 17,
                }}
              >
                <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}
                     preserveAspectRatio="none">
                  <rect x="2" y="2" width="calc(100% - 4px)" height="calc(100% - 4px)"
                        rx="22" ry="22" fill="none" stroke={subj.ink} strokeWidth="2"
                        filter="url(#sketchRough)" />
                </svg>
                <span style={{ position: 'relative' }}>{subj.label}</span>
              </button>
            );
          })}
        </div>

        {/* Grid */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))',
          gap: 18,
        }}>
          {filtered.map(g => <SketchCard key={g.id} game={g} onClick={() => { window.location.href = '/' + g.id + '/'; }} />)}
        </div>

        {filtered.length === 0 && (
          <div style={{
            textAlign: 'center', marginTop: 60, fontFamily: '"Caveat", cursive',
            fontSize: 32, color: '#7a5a3a',
          }}>
            no games found — try another word
          </div>
        )}
      </div>
    </div>
  );
}

window.SketchArtboard = SketchArtboard;
