// screens.jsx — wszystkie ekrany finalnej strony urodzinowej Klaudii
// Styl: V1 Vintage Postcard. Teksty po polsku.
// Paleta z PostcardTheme (import z illustrations, tu zdefiniowana lokalnie)

const T = {
  bg: '#f4ead4',
  ink: '#2a1810',
  burgundy: '#7a1f2a',
  navy: '#1f3a5f',
  accent: '#c8342b',
  mustard: '#d4a028',
  paper: '#fcf5e3',
  paperDark: '#efe2be',
  shadow: 'rgba(42,24,16,0.18)',
};

// ───────────────────────── Layout wrapper ─────────────────────────
function Page({ children, noBorder }) {
  return (
    <div style={{
      position:'relative',
      width:'100%', height:'100%',
      background:T.bg, color:T.ink,
      fontFamily:'"Cormorant Garamond", Georgia, serif',
      overflow:'hidden',
    }}>
      <div style={{position:'absolute', inset:0, opacity:0.12, backgroundImage:'radial-gradient(circle, #2a1810 0.6px, transparent 0.6px)', backgroundSize:'8px 8px', pointerEvents:'none'}}/>
      {!noBorder && <div style={{position:'absolute', inset:20, border:`2px dashed ${T.burgundy}`, pointerEvents:'none', borderRadius:2}}/>}
      {children}
    </div>
  );
}

function PolkaButton({ children, onClick, variant='primary', style }) {
  const bg = variant === 'primary' ? T.burgundy : T.paper;
  const fg = variant === 'primary' ? T.paper : T.ink;
  return (
    <button onClick={onClick} style={{
      background:bg, color:fg, border:`2px solid ${T.ink}`, padding:'12px 26px',
      fontFamily:'"Cormorant Garamond", serif', fontSize:15, letterSpacing:'0.18em', textTransform:'uppercase',
      cursor:'pointer', boxShadow:`4px 4px 0 ${T.ink}`, transition:'transform .12s, box-shadow .12s',
      ...style,
    }}
    onMouseDown={e=>{e.currentTarget.style.transform='translate(2px,2px)';e.currentTarget.style.boxShadow=`2px 2px 0 ${T.ink}`;}}
    onMouseUp={e=>{e.currentTarget.style.transform='';e.currentTarget.style.boxShadow=`4px 4px 0 ${T.ink}`;}}
    onMouseLeave={e=>{e.currentTarget.style.transform='';e.currentTarget.style.boxShadow=`4px 4px 0 ${T.ink}`;}}
    >{children}</button>
  );
}

// ───────────────────────── 1. Koperta ─────────────────────────
function ScreenEnvelope({ onNext }) {
  const [opened, setOpened] = React.useState(false);
  return (
    <Page>
      {/* Stemple */}
      <div style={{position:'absolute', top:44, right:44, display:'flex', flexDirection:'column', gap:10, alignItems:'flex-end', zIndex:2}}>
        <Stamp color={T.burgundy} rotate={-10}>Par Avion</Stamp>
        <Stamp color={T.navy} rotate={5}>25.04.2026</Stamp>
        <Stamp color={T.burgundy} rotate={-3}>Kraków</Stamp>
      </div>
      {/* Znaczek */}
      <div style={{position:'absolute', top:44, left:44, width:86, height:102, background:T.paper, border:`2px solid ${T.ink}`, padding:6, boxShadow:`2px 2px 0 ${T.ink}`, zIndex:2}}>
        <div style={{width:'100%', height:'100%', background:`repeating-linear-gradient(45deg, ${T.burgundy}, ${T.burgundy} 4px, ${T.paper} 4px, ${T.paper} 8px)`, display:'flex', alignItems:'center', justifyContent:'center'}}>
          <div style={{background:T.paper, padding:'3px 7px', fontSize:10, fontWeight:700, letterSpacing:'0.12em', border:`1px solid ${T.ink}`}}>USA · PL</div>
        </div>
      </div>

      <div style={{position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'40px 40px 80px', textAlign:'center'}}>
        <div style={{fontSize:12, letterSpacing:'0.3em', textTransform:'uppercase', color:T.burgundy, marginBottom:8}}>List dla</div>
        <div style={{fontSize:72, fontWeight:600, lineHeight:1, fontStyle:'italic', fontFamily:'"Great Vibes", cursive', color:T.burgundy}}>Klaudia</div>
        <div style={{fontSize:14, marginTop:6, color:T.navy, letterSpacing:'0.22em', textTransform:'uppercase'}}>24 urodziny</div>

        {/* koperta */}
        <div
          onClick={() => { if(!opened) setOpened(true); else onNext(); }}
          style={{
            marginTop:38, width:320, height:200, position:'relative', cursor:'pointer',
            filter:`drop-shadow(5px 7px 0 ${T.shadow})`,
            transform: opened ? 'translateY(-10px)' : 'translateY(0)',
            transition:'transform .6s cubic-bezier(.2,.8,.2,1)',
          }}>
          <svg viewBox="0 0 320 200" width="100%" height="100%" style={{overflow:'visible'}}>
            {/* koperta dół */}
            <rect x="0" y="30" width="320" height="170" fill={T.paper} stroke={T.ink} strokeWidth="2.5"/>
            {/* złożenia */}
            <path d="M0 200 L130 130 M320 200 L190 130" stroke={T.ink} strokeWidth="2" fill="none"/>
            {/* klapa */}
            <path
              d="M0 30 L160 130 L320 30 Z"
              fill={T.paperDark}
              stroke={T.ink}
              strokeWidth="2.5"
              style={{
                transformOrigin:'160px 30px',
                transform: opened ? 'rotateX(-180deg)' : 'rotateX(0)',
                transition:'transform .9s cubic-bezier(.2,.8,.2,1)',
              }}
            />
            {/* pieczęć woskowa */}
            {!opened && (
              <g>
                <circle cx="160" cy="115" r="22" fill={T.accent} stroke={T.ink} strokeWidth="2"/>
                <text x="160" y="122" textAnchor="middle" fill={T.paper} fontSize="22" fontFamily="'Great Vibes', cursive">K</text>
              </g>
            )}
            {/* list wystający */}
            {opened && (
              <g style={{animation:'letterRise 0.7s 0.3s both'}}>
                <rect x="35" y="50" width="250" height="120" fill="#fdf9ec" stroke={T.ink} strokeWidth="1.5"/>
                <g stroke={T.ink} strokeWidth="1" opacity="0.5">
                  <line x1="50" y1="75" x2="270" y2="75"/>
                  <line x1="50" y1="92" x2="260" y2="92"/>
                  <line x1="50" y1="109" x2="265" y2="109"/>
                  <line x1="50" y1="126" x2="255" y2="126"/>
                  <line x1="50" y1="143" x2="200" y2="143"/>
                </g>
                <text x="160" y="64" textAnchor="middle" fontFamily="'Great Vibes', cursive" fontSize="18" fill={T.burgundy}>Moja najdroższa Jammuś…</text>
              </g>
            )}
          </svg>
        </div>

        <div style={{marginTop:28, fontSize:14, letterSpacing:'0.18em', color:T.burgundy, textTransform:'uppercase', opacity:opened ? 0 : 1, transition:'opacity .3s'}}>
          kliknij kopertę
        </div>
        {opened && (
          <div style={{marginTop:20, animation:'fadeIn .6s .9s both'}}>
            <PolkaButton onClick={onNext}>Przeczytaj list →</PolkaButton>
          </div>
        )}
      </div>

      {/* maskotki */}
      <div style={{position:'absolute', bottom:40, left:48, zIndex:2}}>
        <Jamnik size={130} bodyColor="#8b4a2a" earColor="#5a2f1a" accent={T.accent}/>
      </div>
      <div style={{position:'absolute', bottom:52, right:60, zIndex:2}}>
        <Kruk size={100} bodyColor={T.ink} accent={T.accent}/>
      </div>
    </Page>
  );
}

// ───────────────────────── 2. List ─────────────────────────
function ScreenLetter({ onNext }) {
  return (
    <Page>
      <div style={{position:'absolute', inset:0, overflowY:'auto', padding:'60px 60px 120px', display:'flex', flexDirection:'column', alignItems:'center'}}>
        <div style={{maxWidth:640, width:'100%', background:T.paper, border:`2px solid ${T.ink}`, padding:'48px 54px', boxShadow:`6px 6px 0 ${T.shadow}`, position:'relative'}}>
          <div style={{position:'absolute', top:-18, left:40}}>
            <Stamp color={T.burgundy} rotate={-8}>Lotnicza · PL</Stamp>
          </div>
          <div style={{fontSize:11, letterSpacing:'0.3em', color:T.navy, textTransform:'uppercase', marginBottom:4}}>Kraków, 25 kwietnia 2026</div>
          <div style={{fontSize:44, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1, marginBottom:18}}>Moja najdroższa Jammuś,</div>
          <div style={{fontSize:17, lineHeight:1.7, fontFamily:'"Cormorant Garamond", serif'}}>
            dziś kończysz <i>twenty-four</i>, a ja wciąż nie mogę uwierzyć, ile radości potrafi się zmieścić w jednej osobie. Przygotowałem dla Ciebie taką małą przygodę. Kilka prezentów po drodze {'<3'}.
            <br/><br/>
            Pomiędzy prezentami są też malutkie zadania. Bez nich nie odblokujesz kolejnej niespodzianki. Ostrzegam: będzie dużo jamników.
            <br/><br/>
            <i>Good jamnik won't bite,</i> <b>but jamnikov will.</b>
            <br/><br/>
            All my love,
          </div>
          <div style={{fontSize:40, fontFamily:'"Great Vibes", cursive', color:T.burgundy, marginTop:8, textAlign:'right'}}>Twój Kruk</div>
        </div>
        <div style={{marginTop:32}}>
          <PolkaButton onClick={onNext}>Zaczynamy →</PolkaButton>
        </div>
      </div>
      <div style={{position:'absolute', top:36, right:44, transform:'rotate(12deg)'}}>
        <Kruk size={80} bodyColor={T.ink} accent={T.accent} pose="heart"/>
      </div>
    </Page>
  );
}

// ───────────────────────── 3. Prezent 1 — voucher okulary ─────────────────────────
function ScreenGift1({ onNext }) {
  return (
    <Page>
      <div style={{position:'absolute', inset:0, padding:'50px 50px', display:'flex', flexDirection:'column', alignItems:'center'}}>
        <div style={{textAlign:'center', marginBottom:28}}>
          <div style={{fontSize:11, letterSpacing:'0.35em', color:T.navy, textTransform:'uppercase'}}>Prezent pierwszy</div>
          <div style={{fontSize:46, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1.05, marginTop:6, whiteSpace:'nowrap'}}>Okulary z filtrem światła niebieskiego</div>
          <div style={{fontSize:14, color:T.ink, fontStyle:'italic', marginTop:8}}>dla najsłodszej nauczycielki angielskiego</div>
        </div>

        <div style={{width:'min(620px, 100%)', background:T.paper, border:`2px solid ${T.ink}`, padding:'28px 32px', boxShadow:`6px 6px 0 ${T.shadow}`, position:'relative'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', borderBottom:`1.5px dashed ${T.ink}`, paddingBottom:14, marginBottom:16}}>
            <div>
              <div style={{fontSize:10, letterSpacing:'0.25em', color:T.burgundy, textTransform:'uppercase'}}>Voucher · wizyta u okulisty</div>
              <div style={{fontSize:24, fontWeight:600, fontStyle:'italic', marginTop:2}}>Żeby jammusia nie bolały oczka</div>
            </div>
            <Stamp color={T.burgundy} rotate={8}>Opłacone</Stamp>
          </div>

          {/* okulary */}
          <div style={{display:'flex', justifyContent:'center', margin:'10px 0 16px'}}>
            <svg viewBox="0 0 240 80" width={240} height={80}>
              <circle cx="60" cy="40" r="28" fill={T.navy} fillOpacity="0.18" stroke={T.ink} strokeWidth="2.5"/>
              <circle cx="180" cy="40" r="28" fill={T.navy} fillOpacity="0.18" stroke={T.ink} strokeWidth="2.5"/>
              <path d="M88 40 Q120 30 152 40" stroke={T.ink} strokeWidth="2.5" fill="none"/>
              <path d="M32 40 L10 34 M208 40 L230 34" stroke={T.ink} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
              <path d="M48 28 L52 34 L58 36 L52 38 L48 44 L44 38 L38 36 L44 34 Z" fill={T.mustard} opacity="0.9"/>
            </svg>
          </div>

          <div style={{fontSize:16, lineHeight:1.6, fontFamily:'"Cormorant Garamond", serif', textAlign:'center'}}>
            Jammusiu, trza Ci kupić nowe oksy bo te już się rozlatują. Nie kupuję ich sam bo musisz je sobie sama wybrać, ale masz tutaj w cenie transport, zakup i huggs (te huggs to taki bonusik od kruka) {'<3'}
          </div>

          <div style={{display:'flex', justifyContent:'space-between', fontSize:10, marginTop:18, paddingTop:12, borderTop:`1.5px dashed ${T.ink}`, letterSpacing:'0.18em', textTransform:'uppercase', color:T.navy, fontFamily:'"Special Elite", monospace'}}>
            <span>Nr 24/0425</span>
            <span>Ważny: bez limitu</span>
            <span>Podpis: Kruk</span>
          </div>
        </div>

        <div style={{marginTop:26}}>
          <PolkaButton onClick={onNext}>Dalej →</PolkaButton>
        </div>
      </div>

      <div style={{position:'absolute', bottom:30, left:30}}>
        <Jamnik size={90} bodyColor="#8b4a2a" earColor="#5a2f1a" accent={T.accent} pose="love"/>
      </div>
      <div style={{position:'absolute', top:30, right:30, transform:'rotate(10deg)'}}>
        <Star size={34} color={T.mustard}/>
      </div>
    </Page>
  );
}

// ───────────────────────── 4. Gra — Trening Jumpnika ─────────────────────────
// Jamnik w 3 torach. Z kruka na górze spadają:
//   ♥ serce (+1)   🦴 kość (+1)   🔥 grzejniczek (-1)
// Cel: 15 pkt. Jeśli wynik spadnie poniżej zera — Game Over, restart.
function ScreenGame({ onNext }) {
  const LANES = 3;
  const GOAL = 15;
  const FALL_STEP = 0.58; // % areny / frame @60fps — szybszy spadek

  const [lane, setLane] = React.useState(1);
  const [score, setScore] = React.useState(0);
  const [items, setItems] = React.useState([]);
  const [phase, setPhase] = React.useState('intro'); // intro | playing | won | lost
  const [combo, setCombo] = React.useState(0);
  const [flash, setFlash] = React.useState(null);

  const laneRef = React.useRef(lane);
  React.useEffect(() => { laneRef.current = lane; }, [lane]);
  const scoreRef = React.useRef(0);
  const phaseRef = React.useRef(phase);
  React.useEffect(() => { phaseRef.current = phase; }, [phase]);

  const rafRef = React.useRef(null);
  const spawnRef = React.useRef(null);
  const lastTRef = React.useRef(0);

  const reset = () => { setScore(0); scoreRef.current = 0; setItems([]); setLane(1); setCombo(0); };
  const begin = () => { reset(); setPhase('playing'); };

  // Pętla rAF — płynnie
  React.useEffect(() => {
    if (phase !== 'playing') return;
    lastTRef.current = performance.now();

    const loop = (t) => {
      const dt = Math.min(50, t - lastTRef.current);
      lastTRef.current = t;
      const step = (dt / (1000 / 60)) * FALL_STEP;

      setItems(list => {
        const next = [];
        for (const it of list) {
          const ny = it.y + step;
          // strefa łapania
          if (ny > 80 && ny < 96 && it.lane === laneRef.current) {
            let pts = 0, label = '', good = true;
            if (it.kind === 'heart')  { pts =  1; label = '+1 ♥'; good = true; }
            if (it.kind === 'cold')   { pts =  1; label = '+1 ❄'; good = true; }
            if (it.kind === 'heater') { pts = -1; label = '−1 🔥'; good = false; }

            const ns = scoreRef.current + pts;
            scoreRef.current = ns;
            setScore(ns);
            if (pts > 0) setCombo(c => c + 1); else setCombo(0);
            setFlash({ good, label, id: Math.random() });

            if (ns < 0) setPhase('lost');
            else if (ns >= GOAL) setPhase('won');
            continue;
          }
          if (ny > 105) continue;
          next.push({ ...it, y: ny });
        }
        return next;
      });

      if (phaseRef.current === 'playing') rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);

    const spawn = () => {
      if (phaseRef.current !== 'playing') return;
      const r = Math.random();
      // 60% grzejniczek (🔥 −1), 20% cold (❄ +1), 20% serce (♥ +1)
      const kind = r < 0.60 ? 'heater' : r < 0.80 ? 'cold' : 'heart';
      setItems(list => [...list, {
        id: Math.random() + performance.now(),
        lane: Math.floor(Math.random() * LANES),
        y: -6,
        kind,
      }]);
      spawnRef.current = setTimeout(spawn, 450 + Math.random() * 400);
    };
    spawnRef.current = setTimeout(spawn, 400);

    return () => {
      cancelAnimationFrame(rafRef.current);
      clearTimeout(spawnRef.current);
    };
  }, [phase]);

  // Klawiatura
  React.useEffect(() => {
    const onKey = (e) => {
      if (phaseRef.current !== 'playing') return;
      if (e.key === 'ArrowLeft' || e.key === 'a') setLane(l => Math.max(0, l - 1));
      if (e.key === 'ArrowRight' || e.key === 'd') setLane(l => Math.min(LANES - 1, l + 1));
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // Flash auto-clear
  React.useEffect(() => {
    if (!flash) return;
    const t = setTimeout(() => setFlash(null), 400);
    return () => clearTimeout(t);
  }, [flash]);

  const glyph = (k) => k === 'heart' ? '♥' : k === 'cold' ? '❄' : '🔥';
  const iColor = (k) => k === 'heart' ? T.accent : k === 'cold' ? '#3a7ab0' : '#e86a2a';

  return (
    <Page>
      <div style={{position:'absolute', top:30, left:0, right:0, textAlign:'center'}}>
        <div style={{fontSize:11, letterSpacing:'0.35em', color:T.navy, textTransform:'uppercase'}}>przerywnik · mini-gra</div>
        <div style={{fontSize:46, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1, marginTop:4}}>Trening Jumpnika</div>
        <div style={{fontSize:13, fontStyle:'italic', color:T.ink, marginTop:4, maxWidth:720, margin:'4px auto 0'}}>
          <span style={{color:T.accent}}>♥ serce</span> <b>+1</b> &nbsp;·&nbsp; <span style={{color:'#3a7ab0'}}>❄ cold</span> <b>+1</b> &nbsp;·&nbsp; <span style={{color:'#e86a2a'}}>🔥 grzejniczek</span> <b>−1</b>. Zbierz <b>{GOAL}</b>, nie spadnij poniżej zera.
        </div>
      </div>

      {/* HUD */}
      <div style={{position:'absolute', top:152, left:0, right:0, display:'flex', justifyContent:'center', gap:32, fontFamily:'"Special Elite", monospace', fontSize:14, color:T.ink, letterSpacing:'0.15em', textTransform:'uppercase', whiteSpace:'nowrap'}}>
        <span>Wynik:&nbsp;<b style={{color: score < 0 ? T.burgundy : T.accent, fontSize:17}}>{score}&nbsp;/&nbsp;{GOAL}</b></span>
        <span>Combo:&nbsp;<b style={{color:T.navy}}>{combo}×</b></span>
      </div>

      {/* Arena */}
      <div style={{position:'absolute', top:195, left:60, right:60, bottom:80, background:T.paper, border:`2px solid ${T.ink}`, boxShadow:`6px 6px 0 ${T.shadow}`, overflow:'hidden'}}>
        <div style={{position:'absolute', inset:0, display:'flex'}}>
          {[0,1,2].map(i => (
            <div key={i}
              onClick={() => phase === 'playing' && setLane(i)}
              style={{
                flex:1, borderRight: i < 2 ? `1px dashed ${T.ink}33` : 'none',
                background: lane === i && phase === 'playing' ? `linear-gradient(to bottom, transparent, ${T.accent}18)` : 'transparent',
                cursor: phase === 'playing' ? 'pointer' : 'default',
                transition:'background .2s',
              }}/>
          ))}
        </div>

        {/* Kruk */}
        <div style={{position:'absolute', top:8, left:'50%', transform:'translateX(-50%)', opacity:0.85}}>
          <Kruk size={70} bodyColor={T.ink} accent={T.accent} pose="fly"/>
        </div>

        {/* Linia łapania */}
        <div style={{position:'absolute', left:0, right:0, top:'85%', height:2, background:`${T.burgundy}44`, borderTop:`1px dashed ${T.burgundy}`}}/>

        {/* Przedmioty */}
        {items.map(it => (
          <div key={it.id} style={{
            position:'absolute',
            left:`${(it.lane + 0.5) * (100/LANES)}%`,
            top:`${it.y}%`,
            transform:'translate(-50%, -50%)',
            fontSize: it.kind === 'heart' ? 34 : it.kind === 'cold' ? 32 : 30,
            color: iColor(it.kind),
            filter: it.kind === 'heart' ? `drop-shadow(1px 2px 0 ${T.ink}66)` : it.kind === 'heater' ? 'drop-shadow(0 0 8px #e86a2a88)' : it.kind === 'cold' ? 'drop-shadow(0 0 6px #7dc2f088)' : 'none',
            userSelect:'none',
            pointerEvents:'none',
            willChange:'top',
          }}>{glyph(it.kind)}</div>
        ))}

        {/* Jumpnik */}
        <div style={{
          position:'absolute',
          left:`${(lane + 0.5) * (100/LANES)}%`,
          bottom:14,
          transform:'translateX(-50%)',
          transition:'left .16s cubic-bezier(.3,1.4,.4,1)',
          animation:'jumpnikBounce 0.55s infinite ease-in-out',
        }}>
          <Jamnik size={95} bodyColor="#8b4a2a" earColor="#5a2f1a" accent={T.accent} pose="jump"/>
        </div>

        {/* Flash */}
        {flash && (
          <div key={flash.id} style={{
            position:'absolute', left:`${(lane + 0.5) * (100/LANES)}%`, top:'74%',
            transform:'translateX(-50%)',
            fontSize: 26, fontFamily:'"Special Elite", monospace', fontWeight:700,
            color: flash.good ? T.accent : '#b8421a',
            animation:'floatUp .7s forwards',
            pointerEvents:'none',
            textShadow:`1px 1px 0 ${T.paper}`,
            whiteSpace:'nowrap',
          }}>{combo >= 3 && flash.good ? `${flash.label} · ${combo}×!` : flash.label}</div>
        )}

        {/* Intro */}
        {phase === 'intro' && (
          <div style={{position:'absolute', inset:0, background:`${T.bg}ee`, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', padding:30}}>
            <div style={{fontSize:32, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1, whiteSpace:'nowrap'}}>Gotowa, Jammuś?</div>
            <div style={{fontSize:14, fontStyle:'italic', maxWidth:460, marginTop:18, lineHeight:1.55}}>
              Kruk zrzuca <span style={{color:T.accent}}>serca ♥</span>, <span style={{color:'#3a7ab0'}}>śnieżki ❄</span> i uwaga, <span style={{color:'#e86a2a'}}>grzejniczki 🔥</span>. Serca i cold: <b>+1</b>. Grzejniczek: <b>−1</b>. Zbierz <b>{GOAL}</b>, nie spadnij poniżej zera.
            </div>
            <div style={{marginTop:22}}>
              <PolkaButton onClick={begin}>Start! ♥</PolkaButton>
            </div>
          </div>
        )}

        {/* Lost */}
        {phase === 'lost' && (
          <div style={{position:'absolute', inset:0, background:`${T.bg}f2`, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', padding:30, animation:'fadeIn .4s both'}}>
            <div style={{fontSize:11, letterSpacing:'0.3em', color:T.burgundy, textTransform:'uppercase'}}>grzejniczek wygrał</div>
            <div style={{fontSize:44, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1.1, marginTop:6}}>Spróbuj jeszcze raz!</div>
            <div style={{fontSize:14, fontStyle:'italic', marginTop:8, color:T.ink, maxWidth:380, lineHeight:1.5}}>Wynik spadł poniżej zera. Jumpnik wierzy w Ciebie, jeszcze jedno podejście.</div>
            <div style={{marginTop:22}}>
              <PolkaButton onClick={begin}>Od nowa ↻</PolkaButton>
            </div>
          </div>
        )}

        {/* Won */}
        {phase === 'won' && (
          <div style={{position:'absolute', inset:0, background:`${T.bg}f0`, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center', padding:30, animation:'fadeIn .5s both'}}>
            <div style={{fontSize:11, letterSpacing:'0.3em', color:T.navy, textTransform:'uppercase'}}>Jumpnik wytrenowany</div>
            <div style={{fontSize:48, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1.1, marginTop:4}}>{GOAL} punktów miłości!</div>
            <div style={{fontSize:14, fontStyle:'italic', marginTop:8, color:T.ink}}>Wynik: {score}. Serce Jumpnika bije dla Ciebie ♥</div>
            <div style={{marginTop:22}}>
              <PolkaButton onClick={onNext}>Następny prezent →</PolkaButton>
            </div>
          </div>
        )}
      </div>
    </Page>
  );
}

// ───────────────────────── 5. Prezent 2 — Obiad ─────────────────────────
function ScreenGift2({ onNext }) {
  return (
    <Page>
      <div style={{position:'absolute', inset:0, padding:'50px 50px', display:'flex', flexDirection:'column', alignItems:'center'}}>
        <div style={{textAlign:'center', marginBottom:24}}>
          <div style={{fontSize:11, letterSpacing:'0.35em', color:T.navy, textTransform:'uppercase'}}>Prezent drugi</div>
          <div style={{fontSize:56, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1, marginTop:6}}>Obiad, jaki tylko chcesz</div>
          <div style={{fontSize:14, color:T.ink, fontStyle:'italic', marginTop:4}}>bez limitu budżetu, Ty wybierasz miejsce</div>
        </div>

        <div style={{width:'min(640px, 100%)', background:T.paper, border:`2px solid ${T.ink}`, padding:'30px 34px', boxShadow:`6px 6px 0 ${T.shadow}`, position:'relative'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', borderBottom:`1.5px dashed ${T.ink}`, paddingBottom:14, marginBottom:16}}>
            <div>
              <div style={{fontSize:10, letterSpacing:'0.25em', color:T.burgundy, textTransform:'uppercase'}}>Rezerwacja · kolacja urodzinowa</div>
              <div style={{fontSize:24, fontWeight:600, fontStyle:'italic', marginTop:2}}>Bawietka? A może coś jeszcze lepszego?</div>
            </div>
            <Stamp color={T.navy} rotate={-6}>Twój wybór</Stamp>
          </div>

          {/* menu-like divider with icon */}
          <div style={{display:'flex', justifyContent:'center', margin:'8px 0 14px', gap:18, alignItems:'center'}}>
            <svg viewBox="0 0 40 40" width={34} height={34}>
              <path d="M10 6 L10 22 Q10 26 14 26 L14 34" stroke={T.ink} strokeWidth="2" fill="none" strokeLinecap="round"/>
              <path d="M14 6 L14 18 M10 6 L10 14 M18 6 L18 14" stroke={T.ink} strokeWidth="1.5" fill="none" strokeLinecap="round"/>
              <path d="M28 6 Q24 10 24 16 Q24 20 28 22 L28 34" stroke={T.ink} strokeWidth="2" fill="none" strokeLinecap="round"/>
            </svg>
            <div style={{width:60, height:1, background:T.ink, opacity:0.4}}/>
            <div style={{fontFamily:'"Great Vibes", cursive', fontSize:26, color:T.burgundy}}>menu</div>
            <div style={{width:60, height:1, background:T.ink, opacity:0.4}}/>
            <svg viewBox="0 0 40 40" width={34} height={34}>
              <circle cx="20" cy="20" r="14" fill="none" stroke={T.ink} strokeWidth="2"/>
              <circle cx="20" cy="20" r="9" fill="none" stroke={T.ink} strokeWidth="1.3"/>
            </svg>
          </div>

          <div style={{fontSize:17, lineHeight:1.65, fontFamily:'"Cormorant Garamond", serif', textAlign:'center'}}>
            Wiem jammusiu, jak lubisz <b>Bawietkę</b>, tam zawsze znajdzie się dla nas stolik. Ale jeśli masz dziś ochotę na coś innego, absolutnie cokolwiek. Sushi, ramen, włoskie, stek, menu degustacyjne - no limit. Wybierz miejsce. Ja prowadzę, rezerwuję i płacę.
          </div>

          <div style={{display:'flex', justifyContent:'space-between', fontSize:10, marginTop:18, paddingTop:12, borderTop:`1.5px dashed ${T.ink}`, letterSpacing:'0.18em', textTransform:'uppercase', color:T.navy, fontFamily:'"Special Elite", monospace'}}>
            <span>Nr 24/0425/II</span>
            <span>Stolik dla dwojga</span>
            <span>Rezerwuje: Kruk</span>
          </div>
        </div>

        <div style={{marginTop:24}}>
          <PolkaButton onClick={onNext}>Wielki finał →</PolkaButton>
        </div>
      </div>
      <div style={{position:'absolute', bottom:30, right:40}}>
        <Jamnik size={100} bodyColor="#8b4a2a" earColor="#5a2f1a" accent={T.accent} pose="love"/>
      </div>
    </Page>
  );
}

// ───────────────────────── 6. Quiz ─────────────────────────
const QUIZ = [
  {
    q: 'Dokończ: "Good jamnik won\'t bite…"',
    options: ['…but jamnikov will.', '…but he will steal your heart.', '…but cats might.'],
    correct: 0,
    after: 'Oczywiście. Klasyk gatunku.',
  },
  {
    q: 'Jak Kruk czasem nazywa Klaudię?',
    options: ['Słoneczko', 'Jammuś', 'Myszka'],
    correct: 1,
    after: '♥ moja Jammuś.',
  },
  {
    q: 'Czym różni się zwykły jamnik od Jumpnika?',
    options: ['Jumpnik jest krótszy', 'Jumpnik skacze', 'Jumpnik ma okulary'],
    correct: 1,
    after: 'Skaczący jamnik. Naturalne zjawisko.',
  },
  {
    q: 'Z której strony łóżka ma spać Kruk?',
    options: ['Z prawej', 'Na środku', 'Z lewej'],
    correct: 2,
    after: 'Oczywiście. Lewa strona zawsze należała do Kruka.',
  },
  {
    q: 'Gdzie jest Neścik?',
    options: ['Na drzewie', 'W leżance', 'W mieszkanku'],
    correct: 0,
    anyCorrect: true,
    after: 'Tak! Neścik jest wszędzie jednocześnie. Magia.',
  },
];

function ScreenQuiz({ onNext }) {
  const [i, setI] = React.useState(0);
  const [picked, setPicked] = React.useState(null);
  const [score, setScore] = React.useState(0);
  const q = QUIZ[i];
  const done = i >= QUIZ.length;

  const pick = (idx) => {
    if (picked !== null) return;
    setPicked(idx);
    if (q.anyCorrect || idx === q.correct) setScore(s => s + 1);
  };
  const next = () => {
    setPicked(null);
    setI(n => n + 1);
  };

  if (done) {
    return (
      <Page>
        <div style={{position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:40, textAlign:'center'}}>
          <div style={{fontSize:12, letterSpacing:'0.35em', color:T.navy, textTransform:'uppercase'}}>wyniki quizu</div>
          <div style={{fontSize:84, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1, marginTop:6}}>
            {score} / {QUIZ.length}
          </div>
          <div style={{fontSize:20, fontStyle:'italic', color:T.ink, marginTop:14, maxWidth:500, lineHeight:1.5}}>
            Świetnie Ci poszło Jammyn ♥
          </div>
          <div style={{marginTop:32}}>
            <PolkaButton onClick={onNext}>Ostatni prezent →</PolkaButton>
          </div>
          <div style={{display:'flex', gap:20, marginTop:40}}>
            <Jamnik size={110} bodyColor="#8b4a2a" earColor="#5a2f1a" accent={T.accent} pose="love"/>
            <Kruk size={90} bodyColor={T.ink} accent={T.accent} pose="heart"/>
          </div>
        </div>
      </Page>
    );
  }

  return (
    <Page>
      <div style={{position:'absolute', inset:0, padding:'50px 60px', display:'flex', flexDirection:'column', alignItems:'center'}}>
        <div style={{textAlign:'center', marginBottom:24}}>
          <div style={{fontSize:11, letterSpacing:'0.35em', color:T.navy, textTransform:'uppercase'}}>quiz o nas</div>
          <div style={{fontSize:44, fontFamily:'"Great Vibes", cursive', color:T.burgundy, lineHeight:1, marginTop:2}}>Pytanie {i+1} z {QUIZ.length}</div>
        </div>

        <div style={{width:'min(600px, 100%)', background:T.paper, border:`2px solid ${T.ink}`, padding:'30px 34px', boxShadow:`6px 6px 0 ${T.shadow}`}}>
          <div style={{fontSize:22, fontFamily:'"Cormorant Garamond", serif', fontStyle:'italic', lineHeight:1.4, marginBottom:20, textAlign:'center'}}>
            {q.q}
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:12}}>
            {q.options.map((opt, idx) => {
              const isPicked = picked === idx;
              const isCorrect = q.anyCorrect ? (picked !== null) : idx === q.correct;
              const reveal = picked !== null;
              let bg = T.paper, fg = T.ink, border = T.ink;
              if (reveal && isCorrect) { bg = '#d4e6c8'; border = '#4a6a2a'; }
              else if (reveal && isPicked && !isCorrect) { bg = '#f0c8c8'; border = T.burgundy; }
              return (
                <button
                  key={idx}
                  onClick={() => pick(idx)}
                  disabled={picked !== null}
                  style={{
                    background:bg, color:fg, border:`2px solid ${border}`,
                    padding:'14px 18px', textAlign:'left',
                    fontFamily:'"Cormorant Garamond", serif', fontSize:17,
                    cursor:picked === null ? 'pointer' : 'default',
                    boxShadow:`3px 3px 0 ${T.ink}`,
                    transition:'all .2s',
                    display:'flex', alignItems:'center', gap:14,
                  }}>
                  <span style={{display:'inline-flex', alignItems:'center', justifyContent:'center', width:28, height:28, borderRadius:'50%', border:`1.5px solid ${T.ink}`, fontSize:13, fontWeight:700, fontFamily:'"Special Elite", monospace'}}>
                    {['A','B','C'][idx]}
                  </span>
                  {opt}
                  {reveal && isCorrect && <span style={{marginLeft:'auto', color:'#4a6a2a'}}>✓</span>}
                  {reveal && isPicked && !isCorrect && <span style={{marginLeft:'auto', color:T.burgundy}}>✗</span>}
                </button>
              );
            })}
          </div>
          {picked !== null && (
            <div style={{marginTop:18, fontSize:15, fontStyle:'italic', color:T.burgundy, textAlign:'center', animation:'fadeIn .4s both'}}>
              {q.after}
            </div>
          )}
        </div>

        {picked !== null && (
          <div style={{marginTop:24, animation:'fadeIn .4s .2s both'}}>
            <PolkaButton onClick={next}>{i === QUIZ.length - 1 ? 'Zobacz wynik →' : 'Kolejne pytanie →'}</PolkaButton>
          </div>
        )}
      </div>
    </Page>
  );
}

// ───────────────────────── 7. Finał ─────────────────────────
function ScreenFinal({ onRestart }) {
  const [hearts, setHearts] = React.useState([]);
  React.useEffect(() => {
    const iv = setInterval(() => {
      setHearts(h => [...h.slice(-16), { id: Math.random(), x: Math.random()*100, dur: 3+Math.random()*2, size: 14+Math.random()*18, delay: Math.random()*1 }]);
    }, 600);
    return () => clearInterval(iv);
  }, []);
  return (
    <Page>
      {/* spadające serca */}
      <div style={{position:'absolute', inset:0, pointerEvents:'none', overflow:'hidden'}}>
        {hearts.map(h => (
          <div key={h.id} style={{
            position:'absolute', left:`${h.x}%`, top:'-40px',
            fontSize:h.size, color:T.accent,
            animation:`fall ${h.dur}s ${h.delay}s linear forwards`,
          }}>♥</div>
        ))}
      </div>
      <div style={{position:'absolute', inset:40, border:`4px double ${T.burgundy}`, pointerEvents:'none'}}/>

      <div style={{position:'absolute', inset:0, overflow:'auto', display:'flex', flexDirection:'column', alignItems:'center', textAlign:'center', padding:'50px 40px'}}>
        <div style={{fontSize:12, letterSpacing:'0.35em', textTransform:'uppercase', color:T.navy}}>Koniec listu</div>

        <div style={{display:'flex', gap:30, alignItems:'flex-end', animation:'bounce 2.4s ease-in-out infinite', marginTop:28}}>
          <Jamnik size={140} bodyColor="#8b4a2a" earColor="#5a2f1a" accent={T.accent} pose="love"/>
          <Kruk size={110} bodyColor={T.ink} accent={T.accent} pose="heart"/>
        </div>

        <div style={{fontSize:'clamp(56px, 11vw, 110px)', fontFamily:'"Great Vibes", cursive', lineHeight:1.1, color:T.burgundy, animation:'reveal 1.2s both', textShadow:`3px 3px 0 ${T.paper}`, whiteSpace:'nowrap', marginTop:24}}>
          Kocham Cię
        </div>
        <div style={{fontSize:19, fontStyle:'italic', color:T.ink, maxWidth:540, lineHeight:1.6, animation:'reveal 1s .6s both', marginTop:28}}>
          Wszystkiego najlepszego, Jammuś. Bądź moja na zawsze. Twój Kruk
        </div>
        <div style={{fontSize:13, letterSpacing:'0.3em', color:T.burgundy, animation:'reveal 1s 1.2s both', marginTop:28}}>
          25.04.2026
        </div>

        <div style={{animation:'reveal 1s 1.8s both', marginTop:32, marginBottom:20}}>
          <PolkaButton variant="secondary" onClick={onRestart} style={{fontSize:12}}>Zacznij od nowa</PolkaButton>
        </div>
      </div>
    </Page>
  );
}

Object.assign(window, { ScreenEnvelope, ScreenLetter, ScreenGift1, ScreenGame, ScreenGift2, ScreenQuiz, ScreenFinal, T });
