// Shared bits used by all three directions.
const { useState, useEffect, useRef, useMemo } = React;

// --- tiny utilities ---
window.cx = (...parts) => parts.filter(Boolean).join(' ');
window.fmtTime = (s) => {
  const m = Math.floor(s / 60);
  const ss = String(s % 60).padStart(2, '0');
  return `${m}:${ss}`;
};
window.fmtCount = (n) => {
  if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'B';
  return String(n);
};

// Subtle striped placeholder — used when we want a board preview and don't
// want to hand-draw game-specific art. Monospace explainer inside.
window.Placeholder = function Placeholder({ label, h = 120, tone = '#e8e8e0' }) {
  const id = useMemo(() => 'p' + Math.random().toString(36).slice(2, 8), []);
  return (
    <div style={{
      height: h, borderRadius: 10, background: tone,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
      fontSize: 10, letterSpacing: 0.4, color: 'rgba(0,0,0,0.4)',
      backgroundImage: 'repeating-linear-gradient(45deg, rgba(0,0,0,0.035) 0 6px, transparent 6px 12px)',
    }}>[{label}]</div>
  );
};

// Streak flame, used across directions
window.StreakBadge = function StreakBadge({ n, size = 16 }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontVariantNumeric: 'tabular-nums', fontWeight: 700, fontSize: size * 0.8,
    }}>
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden>
        <path d="M12 3c2 4 5 5 5 9a5 5 0 0 1-10 0c0-2 1-3 2-4 0 2 1 3 2 3 0-3-1-5 1-8z"
          fill="currentColor" />
      </svg>
      {n}
    </span>
  );
};

// A tiny real-looking Kelimely row (solved) — used as ambient art
window.TileRow = function TileRow({ letters, states, size = 22, gap = 3 }) {
  const colors = {
    c: '#3a9e5c', p: '#c79a1b', a: '#d0d0c8', e: 'transparent', f: '#ffffff',
  };
  const textColors = { c: '#fff', p: '#fff', a: '#555', e: 'transparent', f: '#222' };
  const borderColors = { c: 'transparent', p: 'transparent', a: 'transparent', e: '#d0d0c8', f: '#9a9a92' };
  return (
    <div style={{ display: 'inline-flex', gap }}>
      {letters.map((l, i) => {
        const s = states[i] || 'e';
        return (
          <span key={i} style={{
            width: size, height: size, borderRadius: 4,
            background: colors[s], color: textColors[s],
            border: s === 'e' || s === 'f' ? `1.5px solid ${borderColors[s]}` : 'none',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 800, fontSize: size * 0.55, textTransform: 'uppercase',
            fontFamily: 'Inter, system-ui, sans-serif',
          }}>{l}</span>
        );
      })}
    </div>
  );
};

// --- THEMES ---
// Each direction supports a light + dark variant consistent with the live app's
// tokens in src/style.css (paper-white / deep navy).
window.THEMES = {
  light: {
    bg: '#f5f5f0', bg2: '#edeee8', paper: '#fbfbf6',
    ink: '#1f1f1a', inkSoft: '#6a6a62', line: '#dddcd3',
    accent: '#1f1f1a',
  },
  dark: {
    bg: '#0c0d12', bg2: '#141620', paper: '#181a24',
    ink: '#e8ebf3', inkSoft: '#8088a0', line: '#232636',
    accent: '#e8ebf3',
  },
};

// Keep the player's "position" persistent across reloads
window.useLocal = function useLocal(key, initial) {
  const [v, setV] = useState(() => {
    try {
      const raw = localStorage.getItem(key);
      return raw == null ? initial : JSON.parse(raw);
    } catch { return initial; }
  });
  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(v)); } catch {}
  }, [key, v]);
  return [v, setV];
};

// Shared top chrome used in all three directions — matches the live app's
// "Kelimely" wordmark + find-a-word link + theme switch structure.
window.AppHeader = function AppHeader({ theme, setTheme, T, variant }) {
  const isDark = theme === 'dark';
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 40,
      background: T.bg + 'ee',
      backdropFilter: 'blur(10px)',
      borderBottom: `1px solid ${T.line}`,
    }}>
      <div style={{
        maxWidth: 1200, margin: '0 auto',
        padding: '14px 24px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 38, height: 38, borderRadius: 10,
            background: `linear-gradient(135deg, #5ECEAB, #6B9CF5 50%, #A685F2)`,
            display: 'grid', placeItems: 'center',
            color: '#fff', fontWeight: 900, fontFamily: 'Fraunces, Georgia, serif',
            fontSize: 20, letterSpacing: -0.5,
          }}>K</div>
          <div style={{ lineHeight: 1.1 }}>
            <div style={{
              fontFamily: 'Fraunces, Georgia, serif',
              fontWeight: 700, fontSize: 22,
              color: T.ink, letterSpacing: -0.3,
            }}>kelimely</div>
            <div style={{ fontSize: 11, color: T.inkSoft, letterSpacing: 0.2 }}>
              Türkçe kelime oyunları · {variant}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <a href="#" onClick={e => e.preventDefault()} style={{
            fontSize: 12, fontWeight: 600, color: T.inkSoft,
            textDecoration: 'none', padding: '7px 12px',
            border: `1px solid ${T.line}`, borderRadius: 8,
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <svg width="13" height="13" viewBox="0 0 20 20" fill="none">
              <circle cx="8.5" cy="8.5" r="5.5" stroke="currentColor" strokeWidth="1.8" />
              <line x1="12.5" y1="12.5" x2="17" y2="17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
            </svg>
            Kelime Bulucu
          </a>
          <button onClick={() => setTheme(isDark ? 'light' : 'dark')} style={{
            width: 36, height: 36, borderRadius: 8,
            border: `1px solid ${T.line}`, background: T.paper,
            color: T.ink, cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
            {isDark
              ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
              : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>}
          </button>
        </div>
      </div>
    </header>
  );
};
