// Variant B — "Color Pop" — vibrant, modern kids-app feel
// Soft pastel-saturated palette, big rounded shapes, playful but contemporary.

const B_BG       = '#FFF8E7';     // warm cream
const B_INK      = '#2A2A35';
const B_PRIMARY  = '#FF6B6B';     // coral red
const B_SECONDARY = '#4ECDC4';    // teal
const B_YELLOW   = '#FFD93D';
const B_PURPLE   = '#A06CD5';
const B_GREEN    = '#6BCB77';

const B_PALETTE = [B_PRIMARY, B_SECONDARY, B_YELLOW, B_PURPLE, B_GREEN, '#FF9F68'];

function BScreen({ children, bg = B_BG }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      background: bg,
      color: B_INK,
      fontFamily: "'Quicksand', system-ui, sans-serif",
      position: 'relative',
      overflow: 'hidden',
    }}>{children}</div>
  );
}

// Floating pastel blobs in background — adds depth without being childish-tacky
function BBlobs() {
  return (
    <svg style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} viewBox="0 0 1064 1064" preserveAspectRatio="none">
      <circle cx="100" cy="120" r="120" fill={B_YELLOW} opacity="0.25" />
      <circle cx="950" cy="200" r="90" fill={B_SECONDARY} opacity="0.22" />
      <circle cx="80" cy="900" r="140" fill={B_PURPLE} opacity="0.18" />
      <circle cx="980" cy="950" r="100" fill={B_PRIMARY} opacity="0.2" />
    </svg>
  );
}

function BBackBtn({ onBack }) {
  return (
    <button onClick={() => { sfx.tap(); onBack(); }} style={{
      position: 'absolute', top: 24, left: 24,
      width: 64, height: 64,
      border: 'none', background: '#fff',
      borderRadius: '50%', fontSize: 32,
      cursor: 'pointer', zIndex: 10,
      boxShadow: '0 4px 12px rgba(0,0,0,0.12)',
    }}>←</button>
  );
}

// ---------- IDLE ----------
function BIdle({ onStart, brandName, tagline }) {
  const [bounce, setBounce] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setBounce(b => b+1), 700); return () => clearInterval(t); }, []);
  return (
    <BScreen bg={`linear-gradient(180deg, ${B_BG} 0%, #FFE8D6 100%)`}>
      <BBlobs />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center', position: 'relative' }}>

        {/* Logo wordmark with each letter colored */}
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 110, letterSpacing: 2, lineHeight: 1, display: 'flex', gap: 4 }}>
          {(brandName || 'DIBUJÍN').split('').map((ch, i) => (
            <span key={i} style={{ color: B_PALETTE[i % B_PALETTE.length], display: 'inline-block', transform: `translateY(${i % 2 ? -6 : 6}px)` }}>{ch}</span>
          ))}
        </div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 600, fontSize: 32, marginTop: 24, color: B_INK, opacity: 0.75 }}>{tagline || '¡imprimí, pintá, jugá!'}</div>

        {/* Mascot — tiny illustrated character */}
        <div style={{ marginTop: 50, transform: `translateY(${bounce % 2 ? -8 : 0}px)`, transition: 'transform .35s' }}>
          <BMascot />
        </div>

        <button onClick={() => { sfx.tap(); onStart(); }} style={{
          marginTop: 60,
          padding: '32px 72px',
          border: 'none', background: B_PRIMARY, color: '#fff',
          borderRadius: 999,
          fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 36, letterSpacing: 2,
          cursor: 'pointer',
          boxShadow: '0 10px 0 #C44848, 0 14px 30px rgba(0,0,0,0.15)',
          display: 'flex', alignItems: 'center', gap: 18,
        }}>
          <span style={{ fontSize: 44 }}>👋</span>
          ¡EMPEZAR!
        </button>
      </div>
    </BScreen>
  );
}

// Friendly mascot — abstract pencil-character
function BMascot() {
  return (
    <svg width="200" height="200" viewBox="0 0 200 200">
      <ellipse cx="100" cy="180" rx="60" ry="8" fill={B_INK} opacity="0.15" />
      {/* body — pencil with a face */}
      <rect x="60" y="60" width="80" height="100" rx="40" fill={B_YELLOW} />
      <rect x="60" y="60" width="80" height="20" rx="40" fill={B_PRIMARY} />
      {/* eyes */}
      <circle cx="82" cy="105" r="8" fill="#fff" />
      <circle cx="118" cy="105" r="8" fill="#fff" />
      <circle cx="84" cy="107" r="4" fill={B_INK} />
      <circle cx="120" cy="107" r="4" fill={B_INK} />
      {/* smile */}
      <path d="M82 130 Q100 142 118 130" stroke={B_INK} strokeWidth="3" fill="none" strokeLinecap="round" />
      {/* arms */}
      <path d="M60 110 Q40 100 35 80" stroke={B_INK} strokeWidth="4" fill="none" strokeLinecap="round" />
      <path d="M140 110 Q160 100 165 80" stroke={B_INK} strokeWidth="4" fill="none" strokeLinecap="round" />
      {/* tip */}
      <path d="M70 60 L100 30 L130 60 Z" fill="#F4D082" stroke={B_INK} strokeWidth="2" />
      <path d="M88 45 L100 30 L112 45 Z" fill={B_INK} />
    </svg>
  );
}

// ---------- SCAN ----------
function BScan({ onScanned, onBack, demo }) {
  const [pulse, setPulse] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setPulse(p => p+1), 600); return () => clearInterval(t); }, []);
  return (
    <BScreen>
      <BBlobs />
      <BBackBtn onBack={onBack} />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{
          background: B_YELLOW, color: B_INK,
          padding: '8px 24px', borderRadius: 999,
          fontFamily: 'Quicksand', fontWeight: 700, fontSize: 22, letterSpacing: 2,
        }}>PASO 1 DE 3</div>

        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 60, letterSpacing: 1, marginTop: 30, lineHeight: 1.1 }}>MOSTRÁ TU<br/>CUPÓN</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 500, fontSize: 28, marginTop: 12, opacity: 0.7 }}>al lector de abajo 👇</div>

        {/* coupon illustration with QR + animated rays */}
        <div style={{ marginTop: 40, position: 'relative' }}>
          <div style={{
            width: 280, height: 200,
            background: '#fff',
            borderRadius: 18,
            boxShadow: '0 12px 30px rgba(0,0,0,0.15)',
            display: 'flex', alignItems: 'center', padding: 20, gap: 18,
            transform: `rotate(${pulse % 2 ? -3 : -1}deg)`,
            transition: 'transform .4s',
          }}>
            <div style={{ width: 120, height: 120, background: B_INK, borderRadius: 8, display: 'grid', gridTemplate: 'repeat(7, 1fr) / repeat(7, 1fr)', padding: 8, gap: 2 }}>
              {Array.from({length:49}).map((_,i) => <div key={i} style={{ background: Math.random()>0.5 ? '#fff' : 'transparent' }}/> )}
            </div>
            <div style={{ flex: 1, textAlign: 'left' }}>
              <div style={{ fontFamily: 'Quicksand', fontWeight: 700, fontSize: 24, color: B_PRIMARY }}>CUPÓN</div>
              <div style={{ fontFamily: 'Quicksand', fontWeight: 500, fontSize: 14, marginTop: 6 }}>1 dibujo gratis</div>
              <div style={{ fontFamily: 'Quicksand', fontWeight: 500, fontSize: 12, opacity: 0.5, marginTop: 8 }}>#A7B8C9</div>
            </div>
          </div>
        </div>

        {/* big animated arrow down */}
        <svg width="100" height="120" viewBox="0 0 100 120" style={{ marginTop: 30 }}>
          <g transform={`translate(0 ${pulse % 2 ? 8 : 0})`}>
            <path d="M50 10 L50 90 M20 65 L50 95 L80 65" stroke={B_PRIMARY} strokeWidth="10" strokeLinecap="round" strokeLinejoin="round" fill="none" />
          </g>
        </svg>

        {/* Atajo para usar sin lector (p.ej. desde la computadora). En modo demo no
            imprime; fuera de demo imprime de verdad y registra el cupón como (manual). */}
        <button onClick={() => { sfx.scan(); onScanned(); }} style={{
          marginTop: 20, padding: '10px 22px',
          border: 'none', background: 'transparent',
          fontFamily: 'Quicksand', fontSize: 14, color: B_INK, opacity: 0.4, cursor: 'pointer',
          textDecoration: 'underline',
        }}>{demo ? 'simular escaneo (demo)' : 'entrar sin escanear'}</button>
      </div>
    </BScreen>
  );
}

// ---------- CATEGORY ----------
function BCategory({ onPick, onBack }) {
  return (
    <BScreen>
      <BBlobs />
      <BBackBtn onBack={onBack} />
      <div style={{ padding: '50px 50px 20px', textAlign: 'center' }}>
        <div style={{ background: B_YELLOW, color: B_INK, display: 'inline-block', padding: '6px 20px', borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 20, letterSpacing: 2 }}>PASO 2 DE 3</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 56, letterSpacing: 1, marginTop: 16, lineHeight: 1.1 }}>¿QUÉ TE GUSTA?</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, padding: '20px 40px 40px' }}>
        {activeCategories().map((c, i) => (
          <button key={c.id}
            onClick={() => { sfx.pick(); onPick(c.id); }}
            style={{
              background: B_PALETTE[i % B_PALETTE.length],
              border: 'none',
              borderRadius: 24,
              padding: '30px 16px',
              cursor: 'pointer',
              boxShadow: '0 8px 0 rgba(0,0,0,0.18), 0 12px 24px rgba(0,0,0,0.12)',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
              fontFamily: 'inherit',
              color: '#fff',
              transition: 'transform .1s',
            }}
            onMouseDown={(e)=>{e.currentTarget.style.transform='translateY(4px)'; e.currentTarget.style.boxShadow='0 4px 0 rgba(0,0,0,0.18)';}}
            onMouseUp={(e)=>{e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow='0 8px 0 rgba(0,0,0,0.18), 0 12px 24px rgba(0,0,0,0.12)';}}
          >
            <div style={{ fontSize: 80, lineHeight: 1, filter: 'drop-shadow(0 4px 0 rgba(0,0,0,0.15))' }}>{c.emoji}</div>
            <div style={{ fontFamily: 'Quicksand', fontWeight: 700, fontSize: 30, letterSpacing: 1, color: '#fff' }}>{c.label}</div>
          </button>
        ))}
      </div>
    </BScreen>
  );
}

// ---------- CATALOG ----------
function BCatalog({ category, theme, onPick, onBack }) {
  const isVariants = !!theme;
  const cat = CATEGORIES.find(c => c.id === category);
  const items = isVariants ? (theme.variants || [theme]) : (DRAWINGS[category] || []);
  const idx = Math.max(0, CATEGORIES.findIndex(c => c.id === category));
  const accent = B_PALETTE[idx % B_PALETTE.length];
  return (
    <BScreen>
      <BBlobs />
      <BBackBtn onBack={onBack} />
      <div style={{ padding: '50px 50px 14px', textAlign: 'center' }}>
        <div style={{ background: B_YELLOW, color: B_INK, display: 'inline-block', padding: '6px 20px', borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 20, letterSpacing: 2 }}>{isVariants ? 'CASI LISTO' : 'PASO 3 DE 3'}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, marginTop: 14 }}>
          {!isVariants && <span style={{ fontSize: 56 }}>{cat?.emoji}</span>}
          <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 52, letterSpacing: 1, color: accent }}>{isVariants ? theme.name : cat?.label}</div>
        </div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 500, fontSize: 24, marginTop: 6, opacity: 0.7 }}>{isVariants ? 'tocá cuál imprimir' : 'tocá tu favorito'}</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 22, padding: '20px 40px 40px', maxHeight: 800, overflowY: 'auto' }}>
        {items.map(d => (
          <button key={d.id}
            onClick={() => { sfx.pick(); onPick(d); }}
            style={{
              background: '#fff',
              border: 'none',
              borderRadius: 22,
              padding: 18,
              cursor: 'pointer',
              boxShadow: `0 8px 0 ${accent}, 0 14px 30px rgba(0,0,0,0.10)`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              fontFamily: 'inherit',
            }}>
            <div style={{ width: '100%', aspectRatio: '1 / 1', display: 'grid', placeItems: 'center', background: B_BG, borderRadius: 14 }}>
              <DrawingArt drawing={d} stroke={B_INK} size={170} />
            </div>
            <div style={{ fontFamily: 'Quicksand', fontWeight: 700, fontSize: 24, color: B_INK, marginTop: 4 }}>{d.name}</div>
          </button>
        ))}
      </div>
    </BScreen>
  );
}

// ---------- CONFIRM ----------
function BConfirm({ drawing, onPrint, onBack }) {
  return (
    <BScreen>
      <BBlobs />
      <BBackBtn onBack={onBack} />
      <div style={{ padding: '70px 50px 20px', textAlign: 'center' }}>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 60, letterSpacing: 1 }}>¿LO IMPRIMIMOS?</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 500, fontSize: 26, marginTop: 8, opacity: 0.7 }}>elegiste: <b>{drawing?.name}</b></div>
      </div>
      <div style={{ padding: '30px 50px', display: 'flex', justifyContent: 'center' }}>
        <div style={{
          width: 380, height: 480,
          background: '#fff',
          border: 'none',
          borderRadius: 20,
          boxShadow: `0 16px 0 ${B_SECONDARY}, 0 22px 40px rgba(0,0,0,0.15)`,
          display: 'grid', placeItems: 'center',
          padding: 30,
        }}>
          <DrawingArt drawing={drawing} stroke={B_INK} size={300} />
        </div>
      </div>

      <div style={{ display: 'flex', gap: 24, justifyContent: 'center', marginTop: 60 }}>
        <button onClick={() => { sfx.tap(); onBack(); }} style={{
          padding: '24px 32px',
          border: `3px solid ${B_INK}`, background: '#fff', color: B_INK,
          borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 22, letterSpacing: 1,
          cursor: 'pointer',
        }}>← OTRO</button>
        <button onClick={() => { sfx.print(); onPrint(); }} style={{
          padding: '24px 56px',
          border: 'none', background: B_GREEN, color: '#fff',
          borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 30, letterSpacing: 1,
          boxShadow: '0 8px 0 #4A9956',
          cursor: 'pointer',
        }}>¡SÍ! 🖨️</button>
      </div>
    </BScreen>
  );
}

// ---------- PRINTING ----------
function BPrinting({ drawing, result, onDone, printMs = 8000 }) {
  const [progress, setProgress] = React.useState(0);
  React.useEffect(() => {
    const step = 8000 / printMs;   // 0→100 en printMs ms (tick fijo de 80ms)
    const t = setInterval(() => setProgress(p => {
      // Se frena cerca del final hasta que el backend confirme (OK o error), para no
      // pasar a "retirá tu dibujo" si en realidad la impresora falló.
      if (p >= 92 && result == null) return 92;
      if (p >= 100) { clearInterval(t); setTimeout(onDone, 600); return 100; }
      return p + step;
    }), 80);
    return () => clearInterval(t);
  }, [result, printMs]);
  const seconds = Math.max(1, Math.ceil((100 - progress) / 100 * (printMs / 1000)));
  return (
    <BScreen bg={`linear-gradient(180deg, ${B_BG} 0%, #FFE8D6 100%)`}>
      <BBlobs />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 60, letterSpacing: 1, color: B_PRIMARY }}>¡IMPRIMIENDO!</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 500, fontSize: 28, marginTop: 8, opacity: 0.75 }}>tu dibujo está saliendo…</div>

        {/* paper coming out */}
        <div style={{ marginTop: 50, width: 340, height: 460, position: 'relative' }}>
          <div style={{ position: 'absolute', top: 0, left: 20, right: 20, height: 60, background: B_INK, borderRadius: '14px 14px 4px 4px', boxShadow: '0 6px 0 #1a1a25' }}>
            <div style={{ position: 'absolute', top: 22, left: '50%', transform: 'translateX(-50%)', width: 220, height: 8, background: B_PRIMARY, borderRadius: 4 }} />
          </div>
          <div style={{
            position: 'absolute', top: 60, left: 40, width: 260, height: progress * 3.6,
            background: '#fff', boxShadow: '0 6px 16px rgba(0,0,0,0.15)',
            overflow: 'hidden', transition: 'height .08s linear',
            borderRadius: '0 0 8px 8px',
          }}>
            <div style={{ width: 260, height: 360, padding: 20, boxSizing: 'border-box', display: 'grid', placeItems: 'center' }}>
              <DrawingArt drawing={drawing} stroke={B_INK} size={220} />
            </div>
          </div>
          <div style={{ position: 'absolute', right: -30, top: '45%', fontFamily: 'Quicksand', fontWeight: 700, fontSize: 90, color: B_PRIMARY }}>
            {seconds}<span style={{ fontSize: 40 }}>s</span>
          </div>
        </div>

        {/* progress dots */}
        <div style={{ display: 'flex', gap: 12, marginTop: 40 }}>
          {[0,1,2,3,4].map(i => (
            <div key={i} style={{
              width: 18, height: 18, borderRadius: '50%',
              background: progress > i*20 ? B_PALETTE[i] : 'rgba(0,0,0,0.1)',
              transition: 'background .2s',
            }}/>
          ))}
        </div>
      </div>
    </BScreen>
  );
}

// ---------- PICKUP ----------
function BPickup({ drawing, onRestart }) {
  return (
    <BScreen bg={`linear-gradient(180deg, ${B_YELLOW} 0%, ${B_BG} 50%)`}>
      <BBlobs />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{ fontSize: 120 }}>🎉</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 90, letterSpacing: 2, lineHeight: 1, color: B_PRIMARY }}>¡LISTO!</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 600, fontSize: 36, marginTop: 16 }}>retirá tu dibujo</div>

        {/* big animated arrow down */}
        <svg width="120" height="160" viewBox="0 0 120 160" style={{ marginTop: 30 }}>
          <path d="M60 10 L60 130 M20 95 L60 135 L100 95" stroke={B_PRIMARY} strokeWidth="14" strokeLinecap="round" strokeLinejoin="round" fill="none" />
        </svg>

        <div style={{ marginTop: 16, fontFamily: 'Quicksand', fontWeight: 600, fontSize: 26, opacity: 0.7 }}>de la ranura de abajo</div>

        <button onClick={() => { sfx.tap(); onRestart(); }} style={{
          marginTop: 60,
          padding: '20px 36px',
          border: 'none', background: B_INK, color: '#fff',
          borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 22, letterSpacing: 1,
          boxShadow: '0 6px 0 #000',
          cursor: 'pointer',
        }}>VOLVER AL INICIO</button>
      </div>
    </BScreen>
  );
}

// ---------- ERROR (impresión falló) ----------
function BError({ drawing, error, reqId, onRetry, onRestart }) {
  return (
    <BScreen bg={`linear-gradient(180deg, ${B_BG} 0%, #FFE0E0 100%)`}>
      <BBlobs />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{ fontSize: 120 }}>😕</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 60, letterSpacing: 1, lineHeight: 1.1, color: B_PRIMARY }}>¡UPS!</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 600, fontSize: 34, marginTop: 14 }}>no pudimos imprimir tu dibujo</div>
        <div style={{ fontFamily: 'Quicksand', fontWeight: 500, fontSize: 24, marginTop: 20, opacity: 0.75, maxWidth: 520 }}>
          Probá de nuevo o pedile ayuda a una persona del local.
        </div>

        <div style={{ display: 'flex', gap: 24, justifyContent: 'center', marginTop: 56 }}>
          <button onClick={() => { sfx.tap(); onRestart(); }} style={{
            padding: '22px 34px',
            border: 'none', background: '#fff', color: B_INK,
            borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 22, letterSpacing: 1,
            boxShadow: '0 6px 0 rgba(0,0,0,0.15)', cursor: 'pointer',
          }}>VOLVER AL INICIO</button>
          <button onClick={() => { sfx.print(); onRetry(); }} style={{
            padding: '22px 44px',
            border: 'none', background: B_PRIMARY, color: '#fff',
            borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 26, letterSpacing: 1,
            boxShadow: '0 6px 0 #000', cursor: 'pointer',
          }}>🔄 REINTENTAR</button>
        </div>

        {/* Pista técnica chica para el personal — no molesta al chico. */}
        {(error || reqId) && (
          <div style={{ marginTop: 40, fontFamily: 'monospace', fontSize: 13, opacity: 0.4 }}>
            {error ? `${error}` : ''}{reqId ? `  ·  ref ${reqId}` : ''}
          </div>
        )}
      </div>
    </BScreen>
  );
}

Object.assign(window, { BIdle, BScan, BCategory, BCatalog, BConfirm, BPrinting, BError, BPickup,
  B_BG, B_INK, B_PRIMARY, B_SECONDARY, B_YELLOW, B_PURPLE, B_GREEN });
