/* ─────────────────────────────────────────────────────────────────────────
   AnimatedPhone — upgraded with connector spine + per-screen animations
   Screens use Editorial Folklor palette (fixed MF tokens, not brand palette).
   ───────────────────────────────────────────────────────────────────────── */

const { useState: usePh, useEffect: useEffPh, useRef: useRefPh } = React;

/* Role-coded pill colors */
const ROLE_COLORS = {
  diner:   { bg: 'rgba(181,88,30,.18)',  border: 'rgba(181,88,30,.5)',  text: '#F0C4A0', dot: '#B5581E' },
  admin:   { bg: 'rgba(196,154,60,.18)', border: 'rgba(196,154,60,.5)', text: '#F5DFA0', dot: '#C49A3C' },
  kitchen: { bg: 'rgba(45,74,42,.35)',   border: 'rgba(90,140,80,.5)',  text: '#A8D4A0', dot: '#5A8C50' },
  qr:      { bg: 'rgba(181,88,30,.18)',  border: 'rgba(181,88,30,.5)',  text: '#F0C4A0', dot: '#B5581E' },
};

const SCREENS = [
  { key: 'browse',  label: 'Comensal · Menú',   role: 'diner',   render: () => <ScrGuestBrowse /> },
  { key: 'detail',  label: 'Comensal · Plato',  role: 'diner',   render: () => <ScrDishDetail /> },
  { key: 'admin',   label: 'Admin · Pedidos',   role: 'admin',   render: () => <ScrAdmin /> },
  { key: 'kitchen', label: 'Cocina · Tickets',  role: 'kitchen', render: () => <ScrKitchen /> },
  { key: 'qr',      label: 'Comensal · QR',     role: 'qr',      render: () => <ScrQR /> },
];

/* ── Status bar (shared across screens) ─────────────────── */
function StatusBar({ light = false, time = '9:41', color }) {
  const c = color || (light ? 'rgba(255,255,255,0.95)' : '#1C1B17');
  return (
    <div className="status-bar" style={{ color: c }}>
      <span style={{ fontWeight: 600, fontSize: 14 }}>{time}</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <svg width="17" height="11" viewBox="0 0 17 11" fill={c}>
          <rect x="0"  y="7" width="3" height="4"  rx="0.5"/>
          <rect x="5"  y="5" width="3" height="6"  rx="0.5"/>
          <rect x="10" y="3" width="3" height="8"  rx="0.5"/>
          <rect x="15" y="0" width="3" height="11" rx="0.5" opacity="0.45"/>
        </svg>
        <svg width="15" height="11" viewBox="0 0 15 11" fill={c}>
          <path d="M7.5 0C4.6 0 2 1.1 0 2.9l1.6 1.7C3.2 3.2 5.2 2.4 7.5 2.4s4.3.8 5.9 2.2L15 2.9C13 1.1 10.4 0 7.5 0z"/>
          <path d="M7.5 4.7c-1.8 0-3.4.6-4.6 1.7L4.5 8c.8-.7 1.9-1.1 3-1.1s2.2.4 3 1.1L12.1 6.4C10.9 5.3 9.3 4.7 7.5 4.7z"/>
          <path d="M7.5 9c-.8 0-1.5.3-2 .8L7.5 11l2-1.2c-.5-.5-1.2-.8-2-.8z"/>
        </svg>
        <svg width="26" height="12" viewBox="0 0 26 12" fill="none">
          <rect x="0.5" y="0.5" width="22" height="11" rx="3" stroke={c} strokeOpacity="0.55"/>
          <rect x="2"   y="2"   width="18" height="8"  rx="1.5" fill={c}/>
          <rect x="23.5" y="3.5" width="2" height="5" rx="1" fill={c} opacity="0.55"/>
        </svg>
      </span>
    </div>
  );
}

/* ── SCREEN 1 — Guest browse ─────────────────────────────── */
function ScrGuestBrowse() {
  const DEMO_ITEMS = [
    { swatch: '#8B6B47', name: 'Guacamole de la casa',    price: '$145' },
    { swatch: '#B5581E', name: 'Mole negro de la abuela', price: '$285' },
    { swatch: '#2D4A2A', name: 'Pescado a la talla',      price: '$320' },
    { swatch: '#C49A3C', name: 'Cochinita pibil',         price: '$265', agotado: true },
  ];
  return (
    <div style={{ position: 'absolute', inset: 0, background: '#FBF9F4', fontFamily: 'var(--mf-sans)' }}>
      <StatusBar color="#1C1B17" />
      <div style={{ padding: '4px 20px 12px', textAlign: 'center', borderBottom: '1px solid #D8D3C8' }}>
        <div style={{ fontSize: 8, letterSpacing: '0.3em', color: '#B5581E', fontWeight: 600, textTransform: 'uppercase' }}>
          Cocina de temporada
        </div>
        <div style={{ fontFamily: 'var(--mf-serif)', fontStyle: 'italic', fontSize: 20, lineHeight: 1.05, marginTop: 4, color: '#1C1B17' }}>
          La Terraza
        </div>
        <div style={{ fontSize: 8, letterSpacing: '0.22em', color: '#8C8880', marginTop: 4, textTransform: 'uppercase' }}>Mesa 12</div>
      </div>

      <div style={{ display: 'flex', gap: 14, padding: '10px 20px 6px', fontSize: 10, borderBottom: '1px solid #D8D3C8' }}>
        {['Entradas','Fuertes','Postres','Bebidas'].map((tab, i) => (
          <span key={tab} style={{
            color: i === 1 ? '#B5581E' : '#8C8880',
            borderBottom: i === 1 ? '1.5px solid #B5581E' : 'none',
            paddingBottom: 6, fontWeight: i === 1 ? 600 : 400,
            letterSpacing: '0.04em',
          }}>{tab}</span>
        ))}
      </div>

      <div style={{ padding: '8px 16px', display: 'flex', flexDirection: 'column', gap: 1 }}>
        {DEMO_ITEMS.map((item, i) => (
          <div key={item.name} className="mf-row" style={{
            padding: '10px 8px',
            borderBottom: '1px solid #F2EEE5',
            display: 'flex', alignItems: 'center', gap: 10,
            opacity: item.agotado ? 0.5 : undefined,
          }}>
            <div style={{ width: 32, height: 32, background: item.swatch, flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: 'var(--mf-serif)', fontStyle: 'italic',
                fontSize: 12, color: '#1C1B17',
                textDecoration: item.agotado ? 'line-through' : 'none',
              }}>{item.name}</div>
              {item.agotado && (
                <span style={{
                  fontSize: 8, fontWeight: 600, textTransform: 'uppercase',
                  letterSpacing: '0.08em', color: '#8C8880',
                  border: '1px solid #D8D3C8', padding: '1px 5px',
                }}>Agotado</span>
              )}
            </div>
            <div style={{ fontSize: 11, fontWeight: 500, color: '#4A4740', whiteSpace: 'nowrap' }}>{item.price}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── SCREEN 2 — Dish detail ──────────────────────────────── */
function ScrDishDetail() {
  return (
    <div style={{ position: 'absolute', inset: 0, background: '#FBF9F4', fontFamily: 'var(--mf-sans)' }}>
      <StatusBar color="#1C1B17" />

      {/* Dish image area */}
      <div style={{
        height: 130, background: '#2D4A2A',
        position: 'relative', overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {/* Sweep overlay */}
        <div className="mf-dish-sweep" style={{
          position: 'absolute', inset: 0,
          background: '#3D6438',
        }} />
        {/* Dish emoji */}
        <div className="mf-dish-emoji" style={{ fontSize: 52, position: 'relative', zIndex: 1 }}>🍗</div>
      </div>

      <div style={{ padding: '16px 20px 20px' }}>
        <div className="mf-dish-name" style={{
          fontFamily: 'var(--mf-serif)', fontStyle: 'italic',
          fontSize: 18, color: '#1C1B17', lineHeight: 1.1, marginBottom: 6,
        }}>Mole negro de la abuela</div>

        <div className="mf-dish-price" style={{
          fontSize: 16, fontWeight: 600,
          color: '#B5581E', marginBottom: 10,
          fontFamily: 'var(--mf-sans)',
        }}>$285</div>

        <div className="mf-dish-tags" style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
          {['Sin gluten', 'Picante'].map((tag, i) => (
            <span key={tag} style={{
              fontSize: 9, padding: '3px 8px',
              border: `1px solid ${i === 0 ? '#5A8C50' : '#B5581E'}`,
              color: i === 0 ? '#5A8C50' : '#B5581E',
              fontFamily: 'var(--mf-sans)', fontWeight: 500,
            }}>{tag}</span>
          ))}
        </div>

        <p className="mf-dish-desc" style={{
          fontSize: 10, fontWeight: 300, lineHeight: 1.55,
          color: '#8C8880', margin: '0 0 16px',
          fontFamily: 'var(--mf-sans)',
        }}>
          Pollo orgánico bañado en mole negro de 32 ingredientes. Receta familiar desde 1985.
        </p>

        <div className="mf-dish-cta" style={{
          background: '#2D4A2A', color: '#FBF9F4',
          padding: '12px 16px', textAlign: 'center',
          fontSize: 12, fontWeight: 600,
          fontFamily: 'var(--mf-sans)',
          textTransform: 'uppercase', letterSpacing: '0.04em',
        }}>+ Agregar al pedido</div>
      </div>
    </div>
  );
}

/* ── SCREEN 3 — Admin orders ─────────────────────────────── */
function ScrAdmin() {
  return (
    <div style={{ position: 'absolute', inset: 0, background: '#0F0F0D', fontFamily: 'var(--mf-sans)' }}>
      <StatusBar light color="rgba(255,255,255,0.9)" />
      <div style={{ padding: '4px 20px 12px' }}>
        <div style={{ fontSize: 9, letterSpacing: '0.18em', color: '#C49A3C', fontWeight: 600, textTransform: 'uppercase' }}>
          Pedidos activos
        </div>
        <div style={{ fontFamily: 'var(--mf-serif)', fontStyle: 'italic', fontSize: 22, color: '#F5F3EE', lineHeight: 1.1, marginTop: 2 }}>
          7 mesas
        </div>
      </div>

      <div style={{ padding: '0 14px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {/* Completed card */}
        <div style={{
          background: '#1A1A17', border: '1px solid #2a2a26',
          padding: '10px 12px', opacity: 0.45,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontFamily: 'var(--mf-serif)', fontStyle: 'italic', fontSize: 14, color: '#F5F3EE' }}>Mesa 3</div>
            <span style={{
              fontSize: 8, padding: '2px 7px', color: '#5A8C50',
              border: '1px solid #5A8C50', fontWeight: 600,
              textTransform: 'uppercase', letterSpacing: '0.08em',
            }}>Entregado</span>
          </div>
          <div style={{ fontSize: 10, color: '#666', marginTop: 4 }}>Guacamole · Agua de jamaica</div>
        </div>

        {/* New incoming card — animates in */}
        <div className="mf-admin-new" style={{
          background: '#1A1A17', border: '1px solid #2a2a26', padding: '10px 12px',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontFamily: 'var(--mf-serif)', fontStyle: 'italic', fontSize: 14, color: '#F5F3EE' }}>Mesa 8</div>
            <span className="mf-badge-new" style={{
              fontSize: 8, padding: '2px 7px', color: '#F5DFA0',
              border: '1px solid rgba(196,154,60,.4)', fontWeight: 600,
              textTransform: 'uppercase', letterSpacing: '0.08em',
              background: 'rgba(196,154,60,.25)',
            }}>Nuevo</span>
          </div>
          <div style={{ marginTop: 6, display: 'flex', flexDirection: 'column', gap: 3 }}>
            {['1× Mole negro · $285', '2× Agua de jamaica · $110', '1× Cochinita pibil · $265'].map(line => (
              <div key={line} style={{ fontSize: 10, color: '#999', display: 'flex', justifyContent: 'space-between' }}>
                <span>{line.split('·')[0]}</span>
                <span style={{ color: '#C49A3C' }}>{line.split('·')[1]}</span>
              </div>
            ))}
          </div>
          <div style={{
            marginTop: 8, paddingTop: 8, borderTop: '1px solid #2a2a26',
            display: 'flex', justifyContent: 'space-between',
            fontSize: 11, fontWeight: 600, color: '#F5F3EE',
            fontFamily: 'var(--mf-sans)',
          }}>
            <span>Total</span><span>$660</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── SCREEN 4 — Kitchen tickets ──────────────────────────── */
function ScrKitchen() {
  return (
    <div style={{ position: 'absolute', inset: 0, background: '#0A1A09', fontFamily: 'var(--mf-sans)', borderTop: '2px solid #1E3A1C' }}>
      <StatusBar light color="rgba(168,212,160,0.9)" />
      <div style={{ padding: '0 18px 10px' }}>
        <div style={{ fontSize: 8, letterSpacing: '0.18em', color: '#5A8C50', fontWeight: 600, textTransform: 'uppercase' }}>
          Ticket #47
        </div>
        <div style={{ fontFamily: 'var(--mf-serif)', fontStyle: 'italic', fontSize: 18, color: '#A8D4A0', lineHeight: 1.1, marginTop: 2 }}>
          Mesa 4
        </div>
      </div>

      <div style={{ padding: '0 14px', display: 'flex', flexDirection: 'column', gap: 6 }}>
        {/* Row 1 — will be checked */}
        <div className="mf-ck1" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid rgba(90,140,80,0.15)' }}>
          <div className="mf-ck-box" style={{
            width: 16, height: 16, borderRadius: 3,
            border: '1px solid #3A6A38', background: 'transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <span className="mf-ck-icon" style={{ fontSize: 10, color: '#A8D4A0', lineHeight: 1 }}>✓</span>
          </div>
          <span style={{ fontSize: 12, color: '#A8D4A0', fontFamily: 'var(--mf-sans)', fontWeight: 300 }}>1× Mole negro</span>
          <span style={{ marginLeft: 'auto', fontSize: 8, padding: '2px 6px', background: 'rgba(181,88,30,.2)', color: '#F0C4A0', letterSpacing: '0.08em', textTransform: 'uppercase' }}>caliente</span>
        </div>

        {/* Row 2 — will be checked */}
        <div className="mf-ck2" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid rgba(90,140,80,0.15)' }}>
          <div className="mf-ck-box" style={{
            width: 16, height: 16, borderRadius: 3,
            border: '1px solid #3A6A38', background: 'transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <span className="mf-ck-icon" style={{ fontSize: 10, color: '#A8D4A0', lineHeight: 1 }}>✓</span>
          </div>
          <span style={{ fontSize: 12, color: '#A8D4A0', fontFamily: 'var(--mf-sans)', fontWeight: 300 }}>1× Cochinita pibil</span>
          <span style={{ marginLeft: 'auto', fontSize: 8, padding: '2px 6px', background: 'rgba(181,88,30,.2)', color: '#F0C4A0', letterSpacing: '0.08em', textTransform: 'uppercase' }}>caliente</span>
        </div>

        {/* Row 3 — stays unchecked */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', opacity: 0.4 }}>
          <div style={{
            width: 16, height: 16, borderRadius: 3,
            border: '1px solid #3A6A38', background: 'transparent', flexShrink: 0,
          }} />
          <span style={{ fontSize: 12, color: '#A8D4A0', fontFamily: 'var(--mf-sans)', fontWeight: 300 }}>2× Agua de jamaica</span>
          <span style={{ marginLeft: 'auto', fontSize: 8, padding: '2px 6px', background: 'rgba(90,140,80,.15)', color: '#A8D4A0', letterSpacing: '0.08em', textTransform: 'uppercase' }}>fría</span>
        </div>
      </div>

      <div style={{
        position: 'absolute', bottom: 16, left: 14, right: 14,
        fontSize: 10, color: '#5A8C50', letterSpacing: '0.08em',
        fontFamily: 'var(--mf-sans)', fontWeight: 500,
      }}>⏱ 04:32 en cocina</div>
    </div>
  );
}

/* ── SCREEN 5 — QR code ──────────────────────────────────── */
function ScrQR() {
  return (
    <div style={{
      position: 'absolute', inset: 0, background: '#FBF9F4',
      fontFamily: 'var(--mf-sans)',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
    }}>
      <StatusBar color="#1C1B17" />

      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 16,
        padding: '0 24px',
      }}>
        <div style={{
          fontSize: 9, fontWeight: 600, textTransform: 'uppercase',
          letterSpacing: '0.2em', color: '#8C8880',
          fontFamily: 'var(--mf-sans)',
        }}>Escanea para ver el menú</div>

        {/* QR code */}
        <div style={{ position: 'relative' }}>
          <QRPattern />
          <div className="mf-qr-scan" style={{
            position: 'absolute',
            left: 4, right: 4, height: 2,
            background: 'rgba(181,88,30,.7)',
            top: 4,
          }} />
        </div>

        <div className="mf-qr-url" style={{
          fontSize: 10, fontWeight: 500,
          color: '#2D4A2A', fontFamily: 'var(--mf-sans)',
          letterSpacing: '0.02em',
        }}>menufactory.mx/laterraza</div>

        <div className="mf-qr-stat" style={{
          fontSize: 9, color: '#8C8880',
          fontFamily: 'var(--mf-sans)',
        }}>143 escaneos hoy</div>
      </div>
    </div>
  );
}

function QRPattern() {
  return (
    <div style={{
      width: 120, height: 120, padding: 8, background: '#fff',
      border: '1px solid #D8D3C8',
      display: 'grid', gridTemplateColumns: 'repeat(9, 1fr)', gap: 1.5,
      boxSizing: 'border-box',
    }}>
      {Array.from({ length: 81 }).map((_, i) => {
        const r = Math.floor(i / 9), c = i % 9;
        const isTL = r < 3 && c < 3;
        const isTR = r < 3 && c > 5;
        const isBL = r > 5 && c < 3;
        /* finder pattern corners — render once as spanning cell */
        if (isTL && r === 0 && c === 0) return <div key={i} style={{ gridColumn:'1/4', gridRow:'1/4', border:'2.5px solid #1C1B17', borderRadius: 1 }} />;
        if (isTR && r === 0 && c === 6) return <div key={i} style={{ gridColumn:'7/10', gridRow:'1/4', border:'2.5px solid #1C1B17', borderRadius: 1 }} />;
        if (isBL && r === 6 && c === 0) return <div key={i} style={{ gridColumn:'1/4', gridRow:'7/10', border:'2.5px solid #1C1B17', borderRadius: 1 }} />;
        if (isTL || isTR || isBL) return null;
        const filled = (i * 31 + 7) % 5 > 1;
        return <div key={i} style={{ background: filled ? '#1C1B17' : 'transparent', aspectRatio: '1', borderRadius: 0.5 }} />;
      })}
    </div>
  );
}

/* ── AnimatedPhone wrapper ───────────────────────────────── */
function AnimatedPhone({ scale = 1, autoCycle = true }) {
  const [idx, setIdx]        = usePh(0);
  const [prev, setPrev]      = usePh(-1);
  const [signaling, setSign] = usePh(-1);
  const idxRef               = useRefPh(0);

  useEffPh(() => { idxRef.current = idx; }, [idx]);

  function advance(nextIdx) {
    const from = idxRef.current;
    setSign(from);
    setTimeout(() => setSign(-1), 520);
    setPrev(from);
    setIdx(nextIdx);
  }

  useEffPh(() => {
    if (!autoCycle) return;
    const id = setInterval(() => {
      const from = idxRef.current;
      const next = (from + 1) % SCREENS.length;
      setSign(from);
      setTimeout(() => setSign(-1), 520);
      setPrev(from);
      setIdx(next);
    }, 3400);
    return () => clearInterval(id);
  }, [autoCycle]);

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      {/* Phone shell */}
      <div className="phone" style={{ transform: `scale(${scale})`, transformOrigin: 'top center' }}>
        <div className="phone-inner" style={{ background: '#1C1B17' }}>
          {SCREENS.map((s, i) => (
            <div
              key={s.key}
              className={`ph-screen${i === idx ? ' active' : ''}`}
              style={{
                position: 'absolute', inset: 0,
                opacity: i === idx ? 1 : 0,
                transform: i === idx
                  ? 'scale(1) translateX(0)'
                  : i === prev
                    ? 'scale(0.97) translateX(-8px)'
                    : 'scale(1.03) translateX(8px)',
                transition: 'opacity 620ms cubic-bezier(.2,.7,.3,1), transform 700ms cubic-bezier(.2,.7,.3,1)',
                pointerEvents: i === idx ? 'auto' : 'none',
              }}
            >
              {s.render()}
            </div>
          ))}
        </div>
      </div>

      {/* Connector spine + pill nav */}
      <div style={{
        position: 'absolute', top: 38, right: -104,
        display: 'flex', flexDirection: 'column', gap: 0,
        transform: `scale(${1 / scale})`,
        transformOrigin: 'top right',
      }}>
        {SCREENS.map((s, i) => {
          const rc = ROLE_COLORS[s.role];
          const isActive = i === idx;
          const isSignaling = i === signaling;
          const isLast = i === SCREENS.length - 1;
          return (
            <div key={s.key} style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start' }}>
              {/* Connector column */}
              <div style={{
                width: 18, display: 'flex', flexDirection: 'column',
                alignItems: 'center', paddingTop: 12,
              }}>
                {/* Dot */}
                <div style={{
                  width: 8, height: 8, borderRadius: '50%',
                  background: isActive ? rc.dot : 'rgba(251,249,244,0.12)',
                  transform: isActive ? 'scale(1.4)' : 'scale(1)',
                  transition: 'all 220ms ease',
                  flexShrink: 0,
                }} />
                {/* Line + signal dot */}
                {!isLast && (
                  <div style={{ width: 1, height: 44, background: 'rgba(251,249,244,0.08)', position: 'relative', marginTop: 2 }}>
                    {isSignaling && (
                      <div className="mf-signal" style={{
                        position: 'absolute', left: -2,
                        width: 5, height: 5, borderRadius: '50%',
                        background: rc.dot,
                      }} />
                    )}
                  </div>
                )}
              </div>

              {/* Pill button */}
              <button
                onClick={() => advance(i)}
                style={{
                  padding: '8px 14px',
                  borderRadius: 999,
                  background: isActive ? rc.bg : 'none',
                  color: isActive ? rc.text : 'rgba(251,249,244,0.45)',
                  border: `1px solid ${isActive ? rc.border : 'rgba(251,249,244,0.18)'}`,
                  fontSize: 11, fontWeight: 500,
                  whiteSpace: 'nowrap',
                  transition: 'all 220ms ease',
                  fontFamily: 'var(--mf-sans)',
                  cursor: 'pointer',
                  marginBottom: isLast ? 0 : 28,
                }}
              >
                <span style={{
                  display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
                  background: isActive ? rc.dot : 'rgba(251,249,244,0.15)',
                  marginRight: 8, verticalAlign: 1,
                  transition: 'background 220ms ease',
                }} />
                {s.label}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, {
  AnimatedPhone, StatusBar,
  ScrGuestBrowse, ScrDishDetail, ScrAdmin, ScrKitchen, ScrQR,
  MF_SCREENS: SCREENS,
});
