/* global React */
// game.jsx — Načepuj si: hold-to-pour beer mini-game.
// Three modes (šnyt / hladinka / mlíko), randomized.
// Hold the button → beer + foam fill at constant rate (foam grows faster while pouring fast).
// Release to lock score. Overflow = 0. Score 0–100 based on closeness to target zone for both liquid level + foam ratio.
// Vrchní Bohouš announces mode beforehand and judges after.

const { useState, useEffect, useRef, useCallback } = React;

// ============ MODE DEFINITIONS ==========================================
// Each mode targets a (liquidPct, foamPct) — values are % of glass height.
// Glass interior is 0..100 (bottom..rim). Liquid fills from bottom; foam sits on top of liquid.
const MODES = {
  hladinka: {
    name: 'HLADINKA',
    cz: 'klasická plzeňská — tři prsty pěny',
    targetLiquid: 70,    // beer fills to 70% of glass
    targetFoam: 22,      // foam adds 22% on top → total 92% (with 8% headroom)
    tolerance: 8,        // ±points for full score
    intro: 'Dnes čepujeme HLADINKU. Tři prsty pěny. Klasiku.',
    perfect: 'Hladinka jako od Pilsnera. Čepujte pořád.',
    good: 'Slušná hladinka. Tomáš souhlasí.',
    okay: 'Trochu mimo, ale pivo to je.',
    bad: 'To by ve Vinohradech vrátili.',
  },
  snyt: {
    name: 'ŠNYT',
    cz: 'půl piva, půl pěny — na rozkoukání',
    targetLiquid: 45,
    targetFoam: 40,
    tolerance: 9,
    intro: 'Dnes čepujeme ŠNYT. Půl pěny. Na rozkoukání.',
    perfect: 'Šnyt jako učebnice. Tomáš slzí.',
    good: 'Pěkný šnyt, mladej.',
    okay: 'Šnyt to spíš nebyl, ale uznám to.',
    bad: 'To není šnyt, to je nedoraz.',
  },
  mliko: {
    name: 'MLÍKO',
    cz: 'celý půllitr pěna — pro dámy a začátečníky',
    targetLiquid: 18,
    targetFoam: 70,
    tolerance: 10,
    intro: 'Dnes čepujeme MLÍKO. Pěna až po okraj. Žádné fórky.',
    perfect: 'Mlíko jako sníh. Tomáš tleská.',
    good: 'Mlíko to je. Trošku moc piva, ale uznám.',
    okay: 'Mlíko se zbytky čaje. Lze.',
    bad: 'To je půl piva, ne mlíko. Smutné.',
  },
};

// ============ POURING PHYSICS ===========================================
// Liquid rate: 60 units per second (so 100% in ~1.67s — short, tense).
// Foam rate: 18 units per second when pouring (slower than liquid).
// When NOT pouring, foam continues to grow slightly for ~400ms (settling), then stops.
const LIQUID_RATE = 60; // %/s
const FOAM_RATE_POUR = 22; // %/s during pour
const FOAM_RATE_SETTLE = 8; // %/s in 400ms after release
const SETTLE_MS = 400;

// ============ SCORING ====================================================
function calcScore(state, mode) {
  const { liquid, foam, overflowed } = state;
  if (overflowed) return { score: 0, dist: 999 };
  const liquidErr = Math.abs(liquid - mode.targetLiquid);
  const foamErr = Math.abs(foam - mode.targetFoam);
  // Liquid worth 60, foam worth 40
  const liquidScore = Math.max(0, 60 - (liquidErr / mode.tolerance) * 30);
  const foamScore = Math.max(0, 40 - (foamErr / mode.tolerance) * 20);
  const score = Math.round(Math.max(0, Math.min(100, liquidScore + foamScore)));
  const dist = liquidErr + foamErr;
  return { score, dist };
}
function judgeText(score, mode, overflowed) {
  if (overflowed) return 'Dnes si skoč radši jen pro vejce.';
  if (score >= 92) return mode.perfect;
  if (score >= 75) return mode.good;
  if (score >= 50) return mode.okay;
  return mode.bad;
}

// ============ VRCHNÍ BOHOUŠ =============================================
function VrchniBohous({ phase, message }) {
  // phases: 'intro' | 'pouring' | 'judge' | 'idle'
  const mood = phase === 'judge' ? (message.includes('vejce') ? 'angry' : message.includes('Pilsnera') || message.includes('slzí') || message.includes('tleská') ? 'happy' : 'neutral') : 'neutral';
  // Česká pošta colors: yellow #FFCC00, blue #00428B
  return (
    <div style={vbStyles.wrap}>
      {/* Tomáš avatar — illustrated, in Česká pošta uniform */}
      <div style={vbStyles.avatar}>
        <svg viewBox="0 0 120 150" width="120" height="150">
          {/* head */}
          <ellipse cx="60" cy="46" rx="30" ry="33" fill="#F4D6B0" stroke="#1A1613" strokeWidth="3"/>
          {/* hair — short brown crop */}
          <path d="M 30 38 Q 32 18 60 14 Q 88 18 90 38 Q 86 28 60 26 Q 34 28 30 38 Z" fill="#5A3A20" stroke="#1A1613" strokeWidth="2.5"/>
          {/* sideburns */}
          <path d="M 32 42 L 34 56 L 38 54 L 36 42 Z" fill="#5A3A20" stroke="#1A1613" strokeWidth="1.5"/>
          <path d="M 88 42 L 86 56 L 82 54 L 84 42 Z" fill="#5A3A20" stroke="#1A1613" strokeWidth="1.5"/>
          {/* ears */}
          <ellipse cx="30" cy="50" rx="4" ry="6" fill="#F4D6B0" stroke="#1A1613" strokeWidth="2"/>
          <ellipse cx="90" cy="50" rx="4" ry="6" fill="#F4D6B0" stroke="#1A1613" strokeWidth="2"/>
          {/* eyebrows — react to mood */}
          {mood === 'angry' ? (
            <>
              <path d="M 42 42 L 52 46" stroke="#1A1613" strokeWidth="3" strokeLinecap="round"/>
              <path d="M 78 42 L 68 46" stroke="#1A1613" strokeWidth="3" strokeLinecap="round"/>
            </>
          ) : mood === 'happy' ? (
            <>
              <path d="M 42 42 Q 47 36 52 42" stroke="#1A1613" strokeWidth="3" strokeLinecap="round" fill="none"/>
              <path d="M 68 42 Q 73 36 78 42" stroke="#1A1613" strokeWidth="3" strokeLinecap="round" fill="none"/>
            </>
          ) : (
            <>
              <line x1="42" y1="44" x2="52" y2="44" stroke="#1A1613" strokeWidth="3" strokeLinecap="round"/>
              <line x1="68" y1="44" x2="78" y2="44" stroke="#1A1613" strokeWidth="3" strokeLinecap="round"/>
            </>
          )}
          {/* eyes */}
          <circle cx="48" cy="52" r="2.5" fill="#1A1613"/>
          <circle cx="72" cy="52" r="2.5" fill="#1A1613"/>
          {/* nose */}
          <path d="M 60 58 Q 56 64 58 68 L 62 68 Q 64 64 60 58" fill="#E8B58A" stroke="#1A1613" strokeWidth="2" strokeLinejoin="round"/>
          {/* mouth — depends on mood */}
          {mood === 'angry' ? (
            <path d="M 50 78 Q 60 74 70 78" stroke="#1A1613" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
          ) : mood === 'happy' ? (
            <path d="M 50 76 Q 60 84 70 76" stroke="#1A1613" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
          ) : (
            <line x1="52" y1="78" x2="68" y2="78" stroke="#1A1613" strokeWidth="2.5" strokeLinecap="round"/>
          )}
          {/* slight stubble dots */}
          <circle cx="46" cy="72" r="0.8" fill="#1A1613"/>
          <circle cx="74" cy="72" r="0.8" fill="#1A1613"/>
          <circle cx="50" cy="76" r="0.8" fill="#1A1613"/>
          <circle cx="70" cy="76" r="0.8" fill="#1A1613"/>

          {/* NECK */}
          <rect x="50" y="79" width="20" height="12" fill="#F4D6B0" stroke="#1A1613" strokeWidth="2.5"/>

          {/* ČESKÁ POŠTA T-SHIRT — yellow, with blue collar trim */}
          <path d="M 22 102 L 50 91 L 60 96 L 70 91 L 98 102 L 100 145 L 20 145 Z" fill="#FFCC00" stroke="#1A1613" strokeWidth="3" strokeLinejoin="round"/>
          {/* collar — blue trim */}
          <path d="M 50 91 L 60 96 L 70 91 L 65 100 L 60 102 L 55 100 Z" fill="#00428B" stroke="#1A1613" strokeWidth="2"/>
          {/* sleeve trim */}
          <path d="M 22 102 L 30 100 L 32 114 L 24 116 Z" fill="#00428B" stroke="#1A1613" strokeWidth="2"/>
          <path d="M 98 102 L 90 100 L 88 114 L 96 116 Z" fill="#00428B" stroke="#1A1613" strokeWidth="2"/>
          {/* ČESKÁ POŠTA logo on chest — stylized post-horn icon + text */}
          <g transform="translate(60, 122)">
            {/* tiny post-horn circle */}
            <circle cx="0" cy="-3" r="6" fill="#00428B" stroke="#1A1613" strokeWidth="1.5"/>
            <path d="M -3 -5 Q 0 -8 3 -5 L 3 -1 Q 0 1 -3 -1 Z" fill="#FFCC00" stroke="#1A1613" strokeWidth="1"/>
            <circle cx="3.5" cy="-3" r="1" fill="#FFCC00"/>
            {/* text below */}
            <text x="0" y="10" fontFamily="Archivo Black, sans-serif" fontSize="6" fill="#00428B" textAnchor="middle" letterSpacing="0.3">ČESKÁ</text>
            <text x="0" y="17" fontFamily="Archivo Black, sans-serif" fontSize="6" fill="#00428B" textAnchor="middle" letterSpacing="0.3">POŠTA</text>
          </g>
          {/* dotted shading on shirt */}
          <g opacity="0.25">
            <circle cx="30" cy="120" r="0.8" fill="#1A1613"/>
            <circle cx="34" cy="126" r="0.8" fill="#1A1613"/>
            <circle cx="32" cy="132" r="0.8" fill="#1A1613"/>
            <circle cx="28" cy="138" r="0.8" fill="#1A1613"/>
            <circle cx="36" cy="138" r="0.8" fill="#1A1613"/>
          </g>
        </svg>
      </div>
      {/* speech bubble */}
      <div style={vbStyles.bubble}>
        <div style={vbStyles.bubbleArrow}/>
        <div style={vbStyles.bubbleName}>VRCHNÍ TOMÁŠ</div>
        <div style={vbStyles.bubbleText}>{message}</div>
      </div>
    </div>
  );
}
const vbStyles = {
  wrap: { display:'flex', alignItems:'flex-start', gap:14 },
  avatar: { flexShrink:0, background:'var(--shell-cool)', border:'4px solid var(--ink)', boxShadow:'4px 4px 0 var(--ink)', padding:'8px 8px 0' },
  bubble: { position:'relative', flex:1, background:'var(--foam)', border:'4px solid var(--ink)', padding:'14px 18px', boxShadow:'4px 4px 0 var(--paprika)', minHeight:80 },
  bubbleArrow: { position:'absolute', left:-14, top:24, width:0, height:0, borderTop:'10px solid transparent', borderBottom:'10px solid transparent', borderRight:'14px solid var(--ink)' },
  bubbleName: { fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.16em', color:'var(--paprika)', fontWeight:700 },
  bubbleText: { fontFamily:'var(--font-serif)', fontStyle:'italic', fontSize:18, color:'var(--ink)', marginTop:6, lineHeight:1.35 },
};

// ============ GLASS VIEW =================================================
// Renders the live glass with current liquid + foam levels.
// Also draws the target zone overlay.
function GlassView({ liquid, foam, mode, overflowed, showTarget }) {
  // Glass viewBox 0..400 wide, 0..520 tall. Interior usable y: 60 (rim) → 500 (bottom). 440px tall.
  const interiorTop = 60;
  const interiorBottom = 500;
  const interiorH = interiorBottom - interiorTop; // 440
  // Convert % to y (0% = bottom, 100% = top)
  const liquidTopY = interiorBottom - (liquid / 100) * interiorH;
  const foamTopY = interiorBottom - ((liquid + foam) / 100) * interiorH;
  const targetLiquidY = interiorBottom - (mode.targetLiquid / 100) * interiorH;
  const targetTotalY = interiorBottom - ((mode.targetLiquid + mode.targetFoam) / 100) * interiorH;
  const tol = (mode.tolerance / 100) * interiorH;

  return (
    <svg viewBox="0 0 400 540" style={{ width:'100%', height:'100%', maxHeight:'70vh' }}>
      <defs>
        <pattern id="game-dots" width="6" height="6" patternUnits="userSpaceOnUse">
          <circle cx="3" cy="3" r="1" fill="rgba(26,22,19,0.5)"/>
        </pattern>
        <clipPath id="game-glass-clip">
          <path d="M 70 60 L 330 60 L 308 500 L 92 500 Z"/>
        </clipPath>
      </defs>

      {/* Glass back */}
      <path d="M 70 60 L 330 60 L 308 500 L 92 500 Z" fill="var(--foam)" stroke="var(--ink)" strokeWidth="5"/>

      {/* Target zone overlay (faint) */}
      {showTarget && !overflowed && (
        <g clipPath="url(#game-glass-clip)" opacity="0.8">
          {/* target liquid zone — yellow dashed band */}
          <line x1="70" y1={targetLiquidY} x2="330" y2={targetLiquidY} stroke="var(--paprika)" strokeWidth="2.5" strokeDasharray="8 6"/>
          <text x="338" y={targetLiquidY + 4} fontFamily="JetBrains Mono, monospace" fontSize="10" fontWeight="700" fill="var(--paprika)">PIVO</text>
          {/* target total (top of foam) — white dashed */}
          <line x1="70" y1={targetTotalY} x2="330" y2={targetTotalY} stroke="var(--paprika)" strokeWidth="2.5" strokeDasharray="8 6"/>
          <text x="338" y={targetTotalY + 4} fontFamily="JetBrains Mono, monospace" fontSize="10" fontWeight="700" fill="var(--paprika)">PĚNA</text>
        </g>
      )}

      {/* Liquid + foam */}
      <g clipPath="url(#game-glass-clip)">
        {liquid > 0 && (
          <>
            <rect x="70" y={liquidTopY} width="260" height={interiorBottom - liquidTopY} fill="var(--yolk)"/>
            <rect x="220" y={liquidTopY} width="110" height={interiorBottom - liquidTopY} fill="url(#game-dots)" opacity="0.35"/>
            <rect x="84" y={liquidTopY + 6} width="14" height={Math.max(0, interiorBottom - liquidTopY - 12)} fill="rgba(255,253,245,0.5)"/>
          </>
        )}
        {foam > 0 && (
          <g>
            <rect x="70" y={foamTopY} width="260" height={liquidTopY - foamTopY} fill="var(--foam)"/>
            {/* bumpy top */}
            {[...Array(22)].map((_, i) => {
              const fx = 74 + i * 12;
              const fr = 4 + ((i * 7) % 5);
              return <circle key={i} cx={fx} cy={foamTopY} r={fr} fill="var(--foam)" stroke="var(--ink)" strokeWidth="1.5"/>;
            })}
            <rect x="70" y={foamTopY} width="260" height={liquidTopY - foamTopY} fill="url(#game-dots)" opacity="0.15"/>
          </g>
        )}
      </g>

      {/* Glass front */}
      <path d="M 70 60 L 330 60 L 308 500 L 92 500 Z" fill="none" stroke="var(--ink)" strokeWidth="5"/>
      <path d="M 84 76 L 96 76 L 93 488 L 83 488 Z" fill="rgba(255,255,255,0.6)"/>

      {/* Overflow splash */}
      {overflowed && (
        <g>
          <path d="M 60 60 Q 50 40 40 30" stroke="var(--foam)" strokeWidth="6" fill="none" strokeLinecap="round"/>
          <path d="M 340 60 Q 350 40 360 30" stroke="var(--foam)" strokeWidth="6" fill="none" strokeLinecap="round"/>
          <circle cx="40" cy="28" r="6" fill="var(--foam)" stroke="var(--ink)" strokeWidth="2"/>
          <circle cx="360" cy="28" r="6" fill="var(--foam)" stroke="var(--ink)" strokeWidth="2"/>
          <circle cx="30" cy="20" r="3" fill="var(--foam)" stroke="var(--ink)" strokeWidth="1.5"/>
          <circle cx="370" cy="20" r="3" fill="var(--foam)" stroke="var(--ink)" strokeWidth="1.5"/>
        </g>
      )}

      {/* Embossed wordmark */}
      <text x="200" y="290" fontFamily="Archivo Black, sans-serif" fontSize="22" fill="var(--ink)" textAnchor="middle" letterSpacing="-1" opacity="0.4">PIVO</text>
      <text x="200" y="316" fontFamily="Fraunces, Georgia, serif" fontWeight="900" fontStyle="italic" fontSize="32" fill="var(--ink)" textAnchor="middle" opacity="0.4">&amp;</text>
      <text x="200" y="346" fontFamily="Archivo Black, sans-serif" fontSize="22" fill="var(--ink)" textAnchor="middle" letterSpacing="-1" opacity="0.4">VEJCE</text>
    </svg>
  );
}

// ============ BEER GAME ==================================================
function BeerGame() {
  const [modeKey, setModeKey] = useState('hladinka');
  const mode = MODES[modeKey];
  const [phase, setPhase] = useState('intro'); // intro | ready | pouring | judge
  const [liquid, setLiquid] = useState(0);
  const [foam, setFoam] = useState(0);
  const [overflowed, setOverflowed] = useState(false);
  const [score, setScore] = useState(null);
  const [bestScore, setBestScore] = useState(() => {
    if (typeof localStorage !== 'undefined') {
      const v = localStorage.getItem('pv_beergame_best');
      return v ? parseInt(v) : null;
    }
    return null;
  });
  const [judgeMsg, setJudgeMsg] = useState('');
  const rafRef = useRef(null);
  const stateRef = useRef({ liquid: 0, foam: 0, pouring: false, lastTs: 0, settleStart: 0 });

  // Pick mode on mount
  useEffect(() => {
    pickNewMode();
    // eslint-disable-next-line
  }, []);

  const pickNewMode = useCallback(() => {
    const keys = Object.keys(MODES);
    const next = keys[Math.floor(Math.random() * keys.length)];
    setModeKey(next);
    setLiquid(0); setFoam(0); setOverflowed(false); setScore(null);
    stateRef.current = { liquid: 0, foam: 0, pouring: false, lastTs: 0, settleStart: 0 };
    setPhase('intro');
    // Auto-advance to ready after 1.6s so user can read announcement
    setTimeout(() => setPhase('ready'), 1600);
  }, []);

  // Animation loop
  const tick = useCallback((ts) => {
    const s = stateRef.current;
    if (!s.lastTs) s.lastTs = ts;
    const dt = (ts - s.lastTs) / 1000;
    s.lastTs = ts;
    if (s.pouring) {
      s.liquid += LIQUID_RATE * dt;
      s.foam += FOAM_RATE_POUR * dt;
    } else if (s.settleStart && (ts - s.settleStart) < SETTLE_MS) {
      // brief foam settle after release
      s.foam += FOAM_RATE_SETTLE * dt;
    }
    // Overflow check
    const total = s.liquid + s.foam;
    if (total > 100) {
      s.liquid = Math.min(s.liquid, 100);
      s.foam = Math.min(s.foam, 100 - s.liquid);
      setLiquid(s.liquid);
      setFoam(s.foam);
      setOverflowed(true);
      finishPour(true);
      return;
    }
    setLiquid(s.liquid);
    setFoam(s.foam);
    rafRef.current = requestAnimationFrame(tick);
  }, []);

  const startPour = (e) => {
    if (phase !== 'ready') return;
    e.preventDefault();
    setPhase('pouring');
    stateRef.current.pouring = true;
    stateRef.current.lastTs = 0;
    rafRef.current = requestAnimationFrame(tick);
  };
  const stopPour = (e) => {
    if (phase !== 'pouring') return;
    e && e.preventDefault();
    stateRef.current.pouring = false;
    stateRef.current.settleStart = performance.now();
    // Let settle phase run to completion, then finish
    setTimeout(() => {
      cancelAnimationFrame(rafRef.current);
      finishPour(false);
    }, SETTLE_MS + 60);
  };
  const finishPour = (didOverflow) => {
    cancelAnimationFrame(rafRef.current);
    const s = stateRef.current;
    const result = calcScore({ liquid: s.liquid, foam: s.foam, overflowed: didOverflow }, mode);
    setScore(result.score);
    setJudgeMsg(judgeText(result.score, mode, didOverflow));
    setPhase('judge');
    if (!didOverflow && (bestScore === null || result.score > bestScore)) {
      setBestScore(result.score);
      if (typeof localStorage !== 'undefined') localStorage.setItem('pv_beergame_best', String(result.score));
    }
  };

  // Cleanup
  useEffect(() => () => cancelAnimationFrame(rafRef.current), []);

  // Bohouš message by phase
  const bohousMsg = phase === 'intro' ? mode.intro
    : phase === 'ready' ? `Drž tlačítko a čepuj. Pusť, až bude ${mode.name.toLowerCase()} hotová.`
    : phase === 'pouring' ? 'Klid. Ruka nesmí cuknout.'
    : phase === 'judge' ? judgeMsg
    : '';

  return (
    <section style={bgStyles.wrap} id="hra">
      <div style={bgStyles.headerRow}>
        <div style={bgStyles.headBlock}>
          <div style={bgStyles.eyebrow}>★ MINI-HRA · BETA ★</div>
          <h2 style={bgStyles.h2}>NAČEPUJ&nbsp;SI.</h2>
          <p style={bgStyles.lede}><em>Drž tlačítko. Pusť včas. Trefit hladinku není legrace.</em></p>
        </div>
        {bestScore !== null && (
          <div style={bgStyles.bestPill}>
            <span style={bgStyles.bestL}>NEJLEPŠÍ</span>
            <span style={bgStyles.bestN}>{bestScore}</span>
            <span style={bgStyles.bestS}>/100</span>
          </div>
        )}
      </div>

      <div style={bgStyles.layout} className="bg-layout">
        {/* LEFT — Bohouš + status */}
        <div style={bgStyles.left}>
          <VrchniBohous phase={phase} message={bohousMsg}/>
          <div style={bgStyles.modeChips}>
            {Object.entries(MODES).map(([k, m]) => (
              <div key={k} style={{
                ...bgStyles.chip,
                ...(k === modeKey ? bgStyles.chipActive : {}),
              }}>
                <div style={bgStyles.chipName}>{m.name}</div>
                <div style={bgStyles.chipNote}>{m.cz}</div>
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT — Glass + button */}
        <div style={bgStyles.right}>
          <div style={bgStyles.glassBox}>
            <GlassView liquid={liquid} foam={foam} mode={mode} overflowed={overflowed} showTarget={phase !== 'judge' || !overflowed}/>
          </div>
          <div style={bgStyles.controls}>
            {phase === 'judge' ? (
              <div style={bgStyles.scoreBlock}>
                <div style={bgStyles.scoreRow}>
                  <div style={bgStyles.scoreNum}>{score}</div>
                  <div style={bgStyles.scoreOf}>/ 100</div>
                </div>
                <div style={{...bgStyles.stamp, ...(overflowed ? bgStyles.stampBad : score >= 92 ? bgStyles.stampGood : score >= 75 ? bgStyles.stampOK : bgStyles.stampMeh)}}>
                  {overflowed ? 'PŘETEKLO' : score >= 92 ? 'PERFEKTNÍ' : score >= 75 ? 'SLUŠNÉ' : score >= 50 ? 'PRŮMĚR' : 'POVADLÉ'}
                </div>
                <button onClick={pickNewMode} style={bgStyles.bigBtn}>JEŠTĚ JEDNOU →</button>
                {/* Future: leaderboard CTA */}
                <p style={bgStyles.future}>Brzy: žebříček nejlepších čepařů.</p>
              </div>
            ) : (
              <button
                style={{
                  ...bgStyles.bigBtn,
                  ...(phase === 'pouring' ? bgStyles.bigBtnActive : {}),
                  ...(phase === 'intro' ? bgStyles.bigBtnDisabled : {}),
                }}
                onMouseDown={startPour}
                onMouseUp={stopPour}
                onMouseLeave={phase === 'pouring' ? stopPour : undefined}
                onTouchStart={startPour}
                onTouchEnd={stopPour}
                disabled={phase === 'intro'}
              >
                {phase === 'intro' ? mode.intro.split('.')[0] + '...' : phase === 'pouring' ? '🍺  ČEPUJEŠ...  🍺' : 'DRŽ — ČEPUJ'}
              </button>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

const bgStyles = {
  wrap: { background:'var(--shell-warm)', padding:'72px 48px', borderBottom:'6px solid var(--ink)', position:'relative' },
  headerRow: { display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:24, marginBottom:36, flexWrap:'wrap' },
  headBlock: {},
  eyebrow: { fontFamily:'var(--font-mono)', fontSize:12, letterSpacing:'0.24em', color:'var(--paprika)', fontWeight:700, marginBottom:14 },
  h2: { fontFamily:'var(--font-display)', fontSize:'clamp(48px, 8vw, 92px)', letterSpacing:'-0.02em', color:'var(--ink)', margin:0, lineHeight:0.92 },
  lede: { fontFamily:'var(--font-serif)', fontSize:18, color:'var(--ink-soft)', marginTop:14, maxWidth:520 },
  bestPill: { display:'flex', alignItems:'baseline', gap:8, background:'var(--ink)', color:'var(--yolk)', border:'4px solid var(--ink)', boxShadow:'5px 5px 0 var(--paprika)', padding:'14px 20px' },
  bestL: { fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.18em', fontWeight:700, color:'var(--shell)' },
  bestN: { fontFamily:'var(--font-display)', fontSize:42, color:'var(--yolk)', lineHeight:1, marginLeft:4 },
  bestS: { fontFamily:'var(--font-mono)', fontSize:14, color:'var(--shell)' },

  layout: { display:'grid', gridTemplateColumns:'1fr 1fr', gap:36, alignItems:'stretch' },
  left: { display:'flex', flexDirection:'column', gap:24 },
  right: { display:'flex', flexDirection:'column', gap:18 },

  modeChips: { display:'flex', flexDirection:'column', gap:10 },
  chip: { background:'var(--foam)', border:'3px solid var(--ink)', padding:'12px 16px', boxShadow:'3px 3px 0 var(--ink)', opacity:0.55, transition:'opacity 200ms, transform 200ms' },
  chipActive: { opacity:1, transform:'translate(-2px, -2px)', boxShadow:'5px 5px 0 var(--paprika)', background:'var(--yolk-soft)' },
  chipName: { fontFamily:'var(--font-display)', fontSize:20, color:'var(--ink)', letterSpacing:'-0.01em' },
  chipNote: { fontFamily:'var(--font-serif)', fontStyle:'italic', fontSize:14, color:'var(--ink-mute)', marginTop:2 },

  glassBox: { background:'var(--shell-cool)', border:'4px solid var(--ink)', boxShadow:'6px 6px 0 var(--ink)', padding:24, display:'flex', justifyContent:'center', alignItems:'center', minHeight:380 },
  controls: { display:'flex', flexDirection:'column', gap:12 },
  bigBtn: { fontFamily:'var(--font-display)', fontSize:24, padding:'22px 24px', border:'4px solid var(--ink)', background:'var(--ink)', color:'var(--yolk)', boxShadow:'6px 6px 0 var(--paprika)', cursor:'pointer', letterSpacing:'0.02em', userSelect:'none', WebkitUserSelect:'none', WebkitTouchCallout:'none', touchAction:'manipulation' },
  bigBtnActive: { background:'var(--paprika)', color:'var(--foam)', transform:'translate(3px, 3px)', boxShadow:'3px 3px 0 var(--paprika)' },
  bigBtnDisabled: { opacity:0.5, cursor:'not-allowed' },

  scoreBlock: { background:'var(--foam)', border:'4px solid var(--ink)', boxShadow:'6px 6px 0 var(--paprika)', padding:'24px 24px 20px', display:'flex', flexDirection:'column', gap:14, alignItems:'flex-start' },
  scoreRow: { display:'flex', alignItems:'baseline', gap:6 },
  scoreNum: { fontFamily:'var(--font-display)', fontSize:88, color:'var(--ink)', lineHeight:1, letterSpacing:'-0.04em' },
  scoreOf: { fontFamily:'var(--font-mono)', fontSize:18, color:'var(--ink-mute)' },
  stamp: { fontFamily:'var(--font-mono)', fontWeight:700, fontSize:13, letterSpacing:'0.16em', padding:'8px 14px', border:'3px solid currentColor', transform:'rotate(-3deg)', alignSelf:'flex-start' },
  stampGood: { color:'var(--paprika)' },
  stampOK: { color:'#5A7D2E' },
  stampMeh: { color:'var(--ink-mute)' },
  stampBad: { color:'var(--paprika)', background:'var(--paprika)', borderColor:'var(--paprika)', WebkitTextStroke:'0', /* invert */ },
  future: { fontFamily:'var(--font-serif)', fontStyle:'italic', fontSize:13, color:'var(--ink-mute)', margin:0 },
};

// inject responsive CSS for game
if (typeof document !== 'undefined' && !document.getElementById('beergame-keyframes')) {
  const st = document.createElement('style');
  st.id = 'beergame-keyframes';
  st.textContent = `
    @media (max-width: 820px) {
      .bg-layout { grid-template-columns: 1fr !important; gap: 24px !important; }
    }
    @media (max-width: 720px) {
      #hra { padding: 48px 22px !important; }
    }
  `;
  document.head.appendChild(st);
}

Object.assign(window, { BeerGame });
