// Game Boy shell primitives: screen, dialog box, menu, pixel button, d-pad
const { useState, useEffect, useRef } = React;

// --- Pixel Button (pressable, with shadow offset) ---
function PxButton({ children, onClick, tone = 'dark', style = {}, big = false, accent = false }) {
  const [pressed, setPressed] = useState(false);
  const bg = accent ? 'var(--accent)' : (tone === 'dark' ? 'var(--ink)' : 'var(--light)');
  const fg = accent ? 'var(--paper)' : (tone === 'dark' ? 'var(--light)' : 'var(--ink)');
  return (
    <button
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      onClick={onClick}
      style={{
        fontFamily: "'Press Start 2P', monospace",
        fontSize: big ? 14 : 10,
        letterSpacing: '0.08em',
        padding: big ? '16px 22px' : '10px 14px',
        background: bg,
        color: fg,
        border: '3px solid var(--ink)',
        borderRadius: 0,
        boxShadow: pressed ? 'none' : '4px 4px 0 var(--ink)',
        transform: pressed ? 'translate(4px,4px)' : 'none',
        cursor: 'pointer',
        textTransform: 'uppercase',
        imageRendering: 'pixelated',
        ...style,
      }}
    >
      {children}
    </button>
  );
}

// --- GB Screen: green LCD panel with 4px inner border ---
function GBScreen({ children, style = {}, flat = false }) {
  return (
    <div
      className="gb-screen"
      style={{
        position: 'relative',
        background: 'var(--light)',
        border: '4px solid var(--ink)',
        boxShadow: flat ? 'none' : '6px 6px 0 var(--ink)',
        padding: 20,
        imageRendering: 'pixelated',
        ...style,
      }}
    >
      {/* inner 1px rule */}
      <div style={{
        position: 'absolute', inset: 6,
        border: '1px solid var(--dark)',
        pointerEvents: 'none',
      }} />
      <div style={{ position: 'relative' }}>{children}</div>
    </div>
  );
}

// --- Dialog box: classic Pokémon-style speech panel ---
function DialogBox({ children, title, style = {} }) {
  return (
    <div style={{
      background: 'var(--light)',
      border: '3px solid var(--ink)',
      padding: '14px 18px 18px',
      position: 'relative',
      fontFamily: "'VT323', monospace",
      fontSize: 22,
      lineHeight: 1.2,
      color: 'var(--ink)',
      ...style,
    }}>
      <div style={{
        position: 'absolute', inset: 4,
        border: '1px solid var(--dark)',
        pointerEvents: 'none',
      }} />
      {title && (
        <div style={{
          fontFamily: "'Press Start 2P', monospace",
          fontSize: 9,
          letterSpacing: '0.1em',
          textTransform: 'uppercase',
          borderBottom: '1px solid var(--dark)',
          paddingBottom: 6,
          marginBottom: 10,
          position: 'relative',
        }}>{title}</div>
      )}
      <div style={{ position: 'relative' }}>{children}</div>
    </div>
  );
}

// --- Menu with blinking ► cursor + keyboard nav ---
function Menu({ items, onSelect, style = {} }) {
  const [idx, setIdx] = useState(0);
  const [blink, setBlink] = useState(true);
  useEffect(() => {
    const t = setInterval(() => setBlink(b => !b), 500);
    return () => clearInterval(t);
  }, []);
  useEffect(() => {
    const handler = (e) => {
      if (e.key === 'ArrowDown') { setIdx(i => (i + 1) % items.length); e.preventDefault(); }
      else if (e.key === 'ArrowUp') { setIdx(i => (i - 1 + items.length) % items.length); e.preventDefault(); }
      else if (e.key === 'Enter' || e.key === 'z' || e.key === 'Z') {
        onSelect(items[idx].key, idx); e.preventDefault();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [items, idx, onSelect]);
  return (
    <div style={{
      fontFamily: "'Press Start 2P', monospace",
      fontSize: 12,
      lineHeight: 1.8,
      background: 'var(--light)',
      border: '3px solid var(--ink)',
      padding: '14px 16px',
      position: 'relative',
      minWidth: 220,
      ...style,
    }}>
      <div style={{ position: 'absolute', inset: 4, border: '1px solid var(--dark)', pointerEvents: 'none' }} />
      {items.map((it, i) => (
        <div
          key={it.key}
          onMouseEnter={() => setIdx(i)}
          onClick={() => onSelect(it.key, i)}
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 10,
            cursor: 'pointer',
            color: 'var(--ink)',
            padding: '4px 0',
            position: 'relative',
          }}
        >
          <span style={{
            width: 14,
            display: 'inline-block',
            visibility: i === idx && blink ? 'visible' : 'hidden',
          }}>►</span>
          <span style={{ textTransform: 'uppercase', letterSpacing: '0.05em' }}>{it.label}</span>
          {it.meta && (
            <span style={{ marginLeft: 'auto', fontFamily: "'VT323',monospace", fontSize: 18, color: 'var(--dark)' }}>
              {it.meta}
            </span>
          )}
        </div>
      ))}
    </div>
  );
}

// --- Pixel progress bar (for £50k → £500k) ---
function PxBar({ value = 0.12, max = 1, style = {} }) {
  const pct = Math.max(0, Math.min(1, value / max));
  const cells = 20;
  const filled = Math.round(pct * cells);
  return (
    <div style={{
      display: 'flex', gap: 2,
      background: 'var(--light)',
      border: '2px solid var(--ink)',
      padding: 3,
      ...style,
    }}>
      {Array.from({ length: cells }).map((_, i) => (
        <div key={i} style={{
          flex: 1, height: 16,
          background: i < filled ? 'var(--ink)' : 'transparent',
        }} />
      ))}
    </div>
  );
}

// --- Stat block: big pixel number + tiny label ---
function StatBlock({ value, label, sub, style = {} }) {
  return (
    <div style={{
      border: '3px solid var(--ink)',
      background: 'var(--paper)',
      padding: '14px 16px',
      boxShadow: '4px 4px 0 var(--ink)',
      minWidth: 180,
      ...style,
    }}>
      <div style={{
        fontFamily: "'Press Start 2P', monospace",
        fontSize: 9,
        letterSpacing: '0.1em',
        textTransform: 'uppercase',
        color: 'var(--dark)',
        marginBottom: 8,
      }}>{label}</div>
      <div style={{
        fontFamily: "'Press Start 2P', monospace",
        fontSize: 22,
        color: 'var(--ink)',
        lineHeight: 1,
        marginBottom: 4,
      }}>{value}</div>
      {sub && (
        <div style={{
          fontFamily: "'VT323', monospace",
          fontSize: 16,
          color: 'var(--dark)',
        }}>{sub}</div>
      )}
    </div>
  );
}

// --- Section head: newspaper-style double rule ---
function SectionHead({ kicker, title, byline }) {
  return (
    <div style={{ margin: '48px 0 16px' }}>
      <div style={{
        fontFamily: "'Press Start 2P', monospace",
        fontSize: 10,
        letterSpacing: '0.18em',
        color: 'var(--dark)',
        marginBottom: 10,
      }}>— {kicker} —</div>
      <div style={{ borderTop: '3px double var(--rule)', borderBottom: '1px solid var(--rule)', padding: '12px 0' }}>
        <h2 style={{
          margin: 0,
          fontFamily: "'Old Standard TT', serif",
          fontSize: 56,
          fontWeight: 700,
          letterSpacing: '-0.01em',
          lineHeight: 0.95,
          color: 'var(--ink)',
        }}>{title}</h2>
        {byline && (
          <div style={{
            marginTop: 8,
            fontFamily: "'Old Standard TT', serif",
            fontStyle: 'italic',
            fontSize: 18,
            color: 'var(--dark)',
          }}>{byline}</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PxButton, GBScreen, DialogBox, Menu, PxBar, StatBlock, SectionHead });
