// Variant A — "Garabato" — coherent with the physical totem (B/W + 1 accent)
// Hand-drawn / sketchbook feel, single coral accent, generous white space.

const A_ACCENT = '#E85A4F';   // warm coral
const A_INK    = '#1a1a1a';
const A_PAPER  = '#fafaf6';
const A_DASH   = 'rgba(26,26,26,0.18)';

// Wrapper for any screen in this variant
function AScreen({ children, bg = A_PAPER }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      background: bg,
      color: A_INK,
      fontFamily: "'Quicksand', system-ui, sans-serif",
      position: 'relative',
      overflow: 'hidden',
    }}>
      {children}
    </div>
  );
}

// Decorative doodles in the corners (very light, like the physical totem)
function ADoodles() {
  return (
    <svg style={{ position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.6 }} viewBox="0 0 1064 1064" preserveAspectRatio="none">
      {/* corner stars */}
      <g stroke={A_INK} strokeWidth="2" fill="none" strokeLinecap="round">
        <path d="M60 80 L72 80 M66 74 L66 86" />
        <path d="M996 100 L1008 100 M1002 94 L1002 106" />
        <path d="M40 980 L52 980 M46 974 L46 986" />
        <path d="M1000 990 L1014 990 M1007 983 L1007 997" />
        {/* hearts */}
        <path d="M80 200 q-8 -10 0 -16 q8 -6 12 6 q4 -12 12 -6 q8 6 0 16 q-6 8 -12 10 q-6 -2 -12 -10 z" fill="none" />
        <path d="M970 850 q-8 -10 0 -16 q8 -6 12 6 q4 -12 12 -6 q8 6 0 16 q-6 8 -12 10 q-6 -2 -12 -10 z" fill="none" />
      </g>
    </svg>
  );
}

function ABrand({ name, tag }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontFamily: "'Quicksand', sans-serif", fontWeight: 300, fontSize: 36, letterSpacing: 4, lineHeight: 1 }}>ESTACIÓN</div>
      <div style={{ fontFamily: "'Quicksand', sans-serif", fontWeight: 700, fontSize: 56, letterSpacing: 2, lineHeight: 1, marginTop: 4 }}>{name || 'CREATIVA'}</div>
      <div style={{ fontFamily: "'Caveat', cursive", fontSize: 26, color: A_INK, marginTop: 10, opacity: 0.8 }}>{tag || 'Imaginá, creá, dibujá…'}</div>
    </div>
  );
}

// ---------- IDLE ----------
function AIdle({ onStart, brandName, tagline }) {
  return (
    <AScreen>
      <ADoodles />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '60px 40px', textAlign: 'center', position: 'relative' }}>

        <div style={{ fontFamily: "'Caveat', cursive", fontSize: 42, color: A_INK, opacity: 0.7 }}>¡hola, artista!</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 300, fontSize: 64, letterSpacing: 6, marginTop: 18 }}>ESTACIÓN</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 110, letterSpacing: 3, lineHeight: 0.95, marginTop: -6 }}>{brandName || 'CREATIVA'}</div>
        <div style={{ fontFamily: "'Caveat', cursive", fontSize: 38, marginTop: 24, color: A_INK }}>{tagline || 'imaginá, creá, dibujá…'}</div>
        <div style={{ fontFamily: "'Caveat', cursive", fontSize: 32, color: A_INK, opacity: 0.7 }}>y dale color al mundo</div>

        {/* big tap-to-start area */}
        <button
          onClick={() => { sfx.tap(); onStart(); }}
          style={{
            marginTop: 80,
            padding: '32px 60px',
            border: `3px solid ${A_INK}`,
            borderRadius: 999,
            background: A_ACCENT,
            color: '#fff',
            fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 32, letterSpacing: 2,
            cursor: 'pointer',
            boxShadow: `6px 6px 0 ${A_INK}`,
            display: 'flex', alignItems: 'center', gap: 16,
          }}>
          <span style={{ fontSize: 40 }}>👆</span>
          TOCÁ PARA EMPEZAR
        </button>

        {/* sketch motifs */}
        <div style={{ position: 'absolute', left: 40, bottom: 60, opacity: 0.85 }}>
          <LineArt kind="bear" stroke={A_INK} size={140} />
        </div>
        <div style={{ position: 'absolute', right: 40, bottom: 60, opacity: 0.85 }}>
          <LineArt kind="unicorn" stroke={A_INK} size={140} />
        </div>
      </div>
    </AScreen>
  );
}

// ---------- SCAN ----------
function AScan({ onScanned, onBack, scanError, demo }) {
  const [pulse, setPulse] = React.useState(0);
  React.useEffect(() => { const t = setInterval(() => setPulse(p => p + 1), 800); return () => clearInterval(t); }, []);
  return (
    <AScreen>
      <ADoodles />
      <ABackBtn onBack={onBack} />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{ fontFamily: "'Caveat'", fontSize: 44, marginBottom: 8 }}>paso 1</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 56, letterSpacing: 1, lineHeight: 1.1 }}>MOSTRÁ TU CUPÓN</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 400, fontSize: 28, marginTop: 12, opacity: 0.7 }}>al lector de abajo</div>

        {/* big illustrated arrow pointing down */}
        <div style={{ marginTop: 60, position: 'relative' }}>
          <svg width="320" height="320" viewBox="0 0 320 320">
            <defs>
              <pattern id="dots" patternUnits="userSpaceOnUse" width="10" height="10">
                <circle cx="2" cy="2" r="1" fill={A_INK} opacity="0.3" />
              </pattern>
            </defs>
            <rect x="60" y="40" width="200" height="200" rx="16" fill="none" stroke={A_INK} strokeWidth="3" strokeDasharray="6 6" />
            <rect x="60" y="40" width="200" height="200" rx="16" fill="url(#dots)" />
            <text x="160" y="155" textAnchor="middle" fontFamily="Quicksand" fontWeight="700" fontSize="22" fill={A_INK}>tu cupón</text>
            <text x="160" y="180" textAnchor="middle" fontFamily="Caveat" fontSize="22" fill={A_INK}>con QR</text>
            {/* downward animated arrow */}
            <g transform={`translate(160 ${265 + (pulse % 2 ? 8 : 0)})`}>
              <path d="M0 -20 L0 20 M-15 5 L0 20 L15 5" fill="none" stroke={A_ACCENT} strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" />
            </g>
          </svg>
        </div>

        {scanError
          ? <div style={{ marginTop: 50, fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 28, color: '#d64541' }}>
              ✋ {scanError}<div style={{ fontFamily: "'Caveat'", fontSize: 28, fontWeight: 400, opacity: 0.7, marginTop: 4 }}>pedile ayuda a un grande</div>
            </div>
          : <div style={{ marginTop: 50, fontFamily: "'Caveat'", fontSize: 36, color: A_ACCENT }}>¿no tenés? pedile a un grande 🙋</div>}

        {/* 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: 40, padding: '14px 28px',
          border: `2px dashed ${A_INK}`, background: 'transparent',
          borderRadius: 999, fontFamily: 'Quicksand', fontSize: 16, color: A_INK, opacity: 0.5, cursor: 'pointer',
        }}>{demo ? 'simular escaneo (demo)' : 'entrar sin escanear'}</button>
      </div>
    </AScreen>
  );
}

// ---------- CATEGORY ----------
function ACategory({ onPick, onBack }) {
  return (
    <AScreen>
      <ADoodles />
      <ABackBtn onBack={onBack} />
      <div style={{ padding: '70px 50px 30px', textAlign: 'center' }}>
        <div style={{ fontFamily: "'Caveat'", fontSize: 38, opacity: 0.7 }}>paso 2</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 52, letterSpacing: 1, lineHeight: 1.1 }}>¿QUÉ QUERÉS HACER?</div>
        <div style={{ fontFamily: "'Caveat'", fontSize: 28, marginTop: 8, opacity: 0.65 }}>tocá una opción</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28, padding: '20px 50px 50px' }}>
        {activeCategories().map(c => (
          <button key={c.id}
            onClick={() => { sfx.pick(); onPick(c.id); }}
            style={{
              background: '#fff',
              border: `3px solid ${A_INK}`,
              borderRadius: 20,
              padding: '28px 20px',
              cursor: 'pointer',
              boxShadow: `5px 5px 0 ${A_INK}`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
              fontFamily: 'inherit',
              transition: 'transform .1s',
            }}
            onMouseDown={(e)=>e.currentTarget.style.transform='translate(2px,2px)'}
            onMouseUp={(e)=>e.currentTarget.style.transform=''}
          >
            <div style={{ fontSize: 80, lineHeight: 1 }}>{c.emoji}</div>
            <div style={{ fontFamily: 'Quicksand', fontWeight: 700, fontSize: 28, letterSpacing: 1 }}>{c.label}</div>
            <div style={{ fontFamily: 'Caveat', fontSize: 22, opacity: 0.7 }}>{c.sub}</div>
          </button>
        ))}
      </div>
    </AScreen>
  );
}

// ---------- CATALOG / VARIANTS ----------
// Two modes: with `category` it lists the themes of a category; with `theme`
// it lists that theme's variants. Same grid layout for both.
function ACatalog({ category, theme, onPick, onBack }) {
  const isVariants = !!theme;
  const cat = CATEGORIES.find(c => c.id === category);
  const items = isVariants ? (theme.variants || [theme]) : (DRAWINGS[category] || []);
  const emoji = isVariants ? null : cat?.emoji;
  const titleText = isVariants ? theme.name : cat?.label;
  return (
    <AScreen>
      <ADoodles />
      <ABackBtn onBack={onBack} />
      <div style={{ padding: '70px 50px 20px', textAlign: 'center' }}>
        <div style={{ fontFamily: "'Caveat'", fontSize: 36, opacity: 0.7 }}>{isVariants ? 'casi listo' : 'paso 3'}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, marginTop: 4 }}>
          {emoji && <span style={{ fontSize: 56 }}>{emoji}</span>}
          <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 48, letterSpacing: 1 }}>{titleText}</div>
        </div>
        <div style={{ fontFamily: "'Caveat'", fontSize: 28, marginTop: 6, opacity: 0.65 }}>{isVariants ? 'elegí cuál imprimir' : 'elegí tu favorito'}</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 16, padding: '10px 28px 30px', maxHeight: 830, overflowY: 'auto', alignContent: 'start' }}>
        {items.map(d => (
          <button key={d.id}
            onClick={() => { sfx.pick(); onPick(d); }}
            style={{
              background: '#fff',
              border: `2.5px solid ${A_INK}`,
              borderRadius: 14,
              padding: 12,
              cursor: 'pointer',
              boxShadow: `4px 4px 0 ${A_INK}`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              fontFamily: 'inherit',
            }}>
            <div style={{ width: '100%', aspectRatio: '1 / 1', display: 'grid', placeItems: 'center', background: A_PAPER, borderRadius: 8, border: `1px dashed ${A_DASH}` }}>
              <DrawingArt drawing={d} stroke={A_INK} size={120} />
            </div>
            <div style={{ fontFamily: 'Caveat', fontSize: 26 }}>{d.name}</div>
          </button>
        ))}
      </div>
    </AScreen>
  );
}

// ---------- CONFIRM ----------
function AConfirm({ drawing, onPrint, onBack }) {
  return (
    <AScreen>
      <ADoodles />
      <ABackBtn onBack={onBack} />
      <div style={{ padding: '80px 50px 30px', textAlign: 'center' }}>
        <div style={{ fontFamily: "'Caveat'", fontSize: 36, opacity: 0.7 }}>paso 4</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 52, letterSpacing: 1 }}>¿LO IMPRIMIMOS?</div>
      </div>
      <div style={{ padding: '20px 50px', display: 'flex', justifyContent: 'center' }}>
        <div style={{
          width: 380, height: 480,
          background: '#fff',
          border: `3px solid ${A_INK}`,
          borderRadius: 14,
          boxShadow: `8px 8px 0 ${A_INK}`,
          display: 'grid', placeItems: 'center',
          padding: 30,
          transform: 'rotate(-3deg)',
        }}>
          <DrawingArt drawing={drawing} stroke={A_INK} size={300} />
        </div>
      </div>
      <div style={{ textAlign: 'center', fontFamily: 'Caveat', fontSize: 38, marginTop: 30 }}>{drawing?.name}</div>

      <div style={{ display: 'flex', gap: 24, justifyContent: 'center', marginTop: 50 }}>
        <button onClick={() => { sfx.tap(); onBack(); }} style={{
          padding: '24px 36px',
          border: `3px solid ${A_INK}`, background: '#fff', color: A_INK,
          borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 24, letterSpacing: 1,
          boxShadow: `4px 4px 0 ${A_INK}`, cursor: 'pointer',
        }}>← OTRO</button>
        <button onClick={() => { sfx.print(); onPrint(); }} style={{
          padding: '24px 48px',
          border: `3px solid ${A_INK}`, background: A_ACCENT, color: '#fff',
          borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 28, letterSpacing: 1,
          boxShadow: `4px 4px 0 ${A_INK}`, cursor: 'pointer',
        }}>¡SÍ, IMPRIMIR! 🖨️</button>
      </div>
    </AScreen>
  );
}

// ---------- PRINTING ----------
function APrinting({ 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 (
    <AScreen bg={A_PAPER}>
      <ADoodles />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 56, letterSpacing: 1 }}>IMPRIMIENDO…</div>
        <div style={{ fontFamily: "'Caveat'", fontSize: 38, marginTop: 8, opacity: 0.7 }}>esperá un segundito</div>

        {/* paper coming out animation */}
        <div style={{ marginTop: 60, width: 360, height: 460, position: 'relative' }}>
          {/* printer top */}
          <div style={{ position: 'absolute', top: 0, left: 30, right: 30, height: 50, background: A_INK, borderRadius: '8px 8px 0 0', display: 'grid', placeItems: 'center' }}>
            <div style={{ width: 200, height: 6, background: '#444', borderRadius: 3 }}/>
          </div>
          {/* the paper drawing reveal */}
          <div style={{
            position: 'absolute', top: 50, left: 50, width: 260, height: progress * 3.6,
            background: '#fff', border: `2px solid ${A_INK}`, borderTop: 'none',
            overflow: 'hidden', transition: 'height .08s linear',
          }}>
            <div style={{ width: 260, height: 360, padding: 20, boxSizing: 'border-box' }}>
              <DrawingArt drawing={drawing} stroke={A_INK} size={220} />
            </div>
          </div>
          {/* big countdown */}
          <div style={{ position: 'absolute', right: -10, top: '50%', fontFamily: 'Quicksand', fontWeight: 700, fontSize: 80, color: A_ACCENT }}>
            {seconds}s
          </div>
        </div>

        <div style={{ width: 460, marginTop: 50 }}>
          <div style={{ height: 16, background: '#fff', border: `2px solid ${A_INK}`, borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${progress}%`, background: A_ACCENT, transition: 'width .08s linear' }}/>
          </div>
        </div>
      </div>
    </AScreen>
  );
}

// ---------- PICKUP ----------
function APickup({ drawing, onRestart }) {
  return (
    <AScreen>
      <ADoodles />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{ fontSize: 100 }}>🎉</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 70, letterSpacing: 1, lineHeight: 1 }}>¡LISTO!</div>
        <div style={{ fontFamily: "'Caveat'", fontSize: 44, marginTop: 12 }}>retirá tu dibujo</div>
        <div style={{ marginTop: 30, fontSize: 80 }}>👇</div>
        <div style={{ marginTop: 20, fontFamily: 'Quicksand', fontWeight: 600, fontSize: 28, opacity: 0.7 }}>de la ranura de abajo</div>

        <button onClick={() => { sfx.tap(); onRestart(); }} style={{
          marginTop: 80,
          padding: '20px 36px',
          border: `3px solid ${A_INK}`, background: '#fff',
          borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 22, letterSpacing: 1,
          boxShadow: `4px 4px 0 ${A_INK}`, cursor: 'pointer',
        }}>VOLVER AL INICIO</button>
      </div>
    </AScreen>
  );
}

// ---------- ERROR (impresión falló) ----------
function AError({ drawing, error, reqId, onRetry, onRestart }) {
  return (
    <AScreen bg={A_PAPER}>
      <ADoodles />
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center' }}>
        <div style={{ fontSize: 100 }}>😕</div>
        <div style={{ fontFamily: "'Quicksand'", fontWeight: 700, fontSize: 56, letterSpacing: 1, lineHeight: 1.1, marginTop: 8 }}>UPS, NO SALIÓ</div>
        <div style={{ fontFamily: "'Caveat'", fontSize: 40, marginTop: 14, opacity: 0.8 }}>no pudimos imprimir tu dibujo</div>
        <div style={{ fontFamily: 'Quicksand', fontWeight: 600, fontSize: 24, marginTop: 24, opacity: 0.7, 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: `3px solid ${A_INK}`, background: '#fff', color: A_INK,
            borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 22, letterSpacing: 1,
            boxShadow: `4px 4px 0 ${A_INK}`, cursor: 'pointer',
          }}>VOLVER AL INICIO</button>
          <button onClick={() => { sfx.print(); onRetry(); }} style={{
            padding: '22px 44px',
            border: `3px solid ${A_INK}`, background: A_ACCENT, color: '#fff',
            borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 26, letterSpacing: 1,
            boxShadow: `4px 4px 0 ${A_INK}`, 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>
    </AScreen>
  );
}

// ---------- BACK BUTTON ----------
function ABackBtn({ onBack }) {
  return (
    <button onClick={() => { sfx.tap(); onBack(); }} style={{
      position: 'absolute', top: 24, left: 24,
      padding: '14px 22px',
      border: `2.5px solid ${A_INK}`, background: '#fff',
      borderRadius: 999, fontFamily: 'Quicksand', fontWeight: 700, fontSize: 18, letterSpacing: 1,
      cursor: 'pointer', zIndex: 10,
    }}>← ATRÁS</button>
  );
}

Object.assign(window, { AIdle, AScan, ACategory, ACatalog, AConfirm, APrinting, AError, APickup,
  A_ACCENT, A_INK, A_PAPER });
