// ============================================
// KDS V6 — Kanban por platillo + identificacion de cocinero
// ============================================
// Cada card = un platillo individual (no una orden completa).
// Para mover de "Nuevos" a "Preparando", el cocinero teclea su ID
// numerico en un keypad. El ID esta registrado en sistema con su nombre.
// Ordenamiento: descendente por tiempo (mas antiguo arriba = mayor prioridad).
// ============================================

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

// ─── Brand & Color tokens ───
const KDS_BRAND = {
  green: '#2f5a1f',
  greenDark: '#264a18',
  greenSoft: '#eef5e6',
  cream: '#f7f5ef',
  ink: '#1c1e1a',
  inkSoft: '#5a5d54',
  mute: '#9aa094',
  border: '#e6e3db',
  orange: '#d97706',
  orangeSoft: '#fdf0e0',
};

const KDS_URGENCY = {
  ok:       { fg: '#3a6b1f', bg: '#eef5e6', border: '#cfe2ba' },
  warn:     { fg: '#b75a07', bg: '#fdf0e0', border: '#f3d2a3' },
  critical: { fg: '#a8170c', bg: '#fde6e3', border: '#f1bdb7' },
};

function kdsUrgencyOf(min) {
  if (min >= 12) return 'critical';
  if (min >= 7) return 'warn';
  return 'ok';
}

// ─── SVG Icons (inline, no external deps) ───

const KDSChefIcon = ({ size = 18, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M6 13.87A4 4 0 0 1 7.41 6a5.11 5.11 0 0 1 1.05-1.54 5 5 0 0 1 7.08 0A5.11 5.11 0 0 1 16.59 6 4 4 0 0 1 18 13.87V21H6Z" />
    <line x1="6" y1="17" x2="18" y2="17" />
  </svg>
);

const KDSCoffeeIcon = ({ size = 18, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M18 8h1a4 4 0 0 1 0 8h-1" />
    <path d="M2 8h16v9a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4Z" />
    <line x1="6" y1="2" x2="6" y2="5" />
    <line x1="10" y1="2" x2="10" y2="5" />
    <line x1="14" y1="2" x2="14" y2="5" />
  </svg>
);

const KDSCheckIcon = ({ size = 16, color = 'currentColor', stroke = 2.5 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">
    <polyline points="20 6 9 17 4 12" />
  </svg>
);

const KDSClockIcon = ({ size = 14, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="9" />
    <polyline points="12 7 12 12 15 14" />
  </svg>
);

const KDSPlayIcon = ({ size = 14, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color} stroke="none">
    <polygon points="6 4 20 12 6 20 6 4" />
  </svg>
);

const KDSOrderTypeIcon = ({ type, size = 14, color = 'currentColor' }) => {
  if (type === 'delivery') return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="1" y="3" width="15" height="13" />
      <polygon points="16 8 20 8 23 11 23 16 16 16 16 8" />
      <circle cx="5.5" cy="18.5" r="2.5" />
      <circle cx="18.5" cy="18.5" r="2.5" />
    </svg>
  );
  if (type === 'llevar') return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 2h12l-1 4H7Z" />
      <path d="M5 6h14l-1 14H6Z" />
    </svg>
  );
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 10h18l-2 4H5Z" />
      <line x1="7" y1="14" x2="7" y2="20" />
      <line x1="17" y1="14" x2="17" y2="20" />
    </svg>
  );
};

const KDSBackspaceIcon = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 4H8l-7 8 7 8h13Z" />
    <line x1="18" y1="9" x2="12" y2="15" />
    <line x1="12" y1="9" x2="18" y2="15" />
  </svg>
);

// ============================================
// KDSView — Componente principal
// ============================================

const KDSView = ({ user, showToast }) => {
  const canSwitchArea = true; // Todos los roles pueden cambiar entre cocina y bebidas
  const [activeStation, setActiveStation] = useState("cocina");
  const [items, setItems] = useState([]);
  const [cooks, setCooks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [claimingItem, setClaimingItem] = useState(null);

  const areaParam = activeStation;

  // ─── Fetch items (kanban data) ───
  const fetchItems = useCallback(async () => {
    try {
      const res = await fetchWithAuth(`${API_BASE}/kds/items?area=${areaParam}`);
      if (!res.ok) { setLoading(false); return; }
      const data = await res.json();
      setItems(data.items || []);
      setLoading(false);
    } catch { setLoading(false); }
  }, [areaParam]);

  // ─── Fetch cooks (solo los del área activa; los de "ambos" aparecen en las dos) ───
  const fetchCooks = useCallback(async () => {
    try {
      const res = await fetchWithAuth(`${API_BASE}/kds/cooks?area=${areaParam}`);
      if (!res.ok) return;
      const data = await res.json();
      setCooks(data.cooks || []);
    } catch {}
  }, [areaParam]);

  // ─── SSE: refresca inmediatamente ───
  useSSE(useCallback((eventType) => {
    if (eventType === "kds:area_update" || eventType.startsWith("order:")) {
      fetchItems();
    }
  }, [fetchItems]));

  // ─── Init + polling fallback ───
  useEffect(() => {
    setLoading(true);
    fetchItems();
    fetchCooks();
    const t = setInterval(fetchItems, 10000);
    return () => clearInterval(t);
  }, [fetchItems, fetchCooks]);

  // ─── Buckets (sort: mas antiguo primero) ───
  const nuevos = useMemo(() =>
    items.filter(t => t.status === 'nuevo').sort((a, b) => b.minutes - a.minutes),
    [items]
  );
  const preparando = useMemo(() =>
    items.filter(t => t.status === 'preparando').sort((a, b) => b.minutes - a.minutes),
    [items]
  );
  const listos = useMemo(() =>
    items.filter(t => t.status === 'listo').sort((a, b) => b.minutes - a.minutes),
    [items]
  );

  // ─── Workload strip ───
  const workload = useMemo(() => {
    const m = new Map();
    preparando.forEach(t => {
      if (!t.cook) return;
      const k = t.cook.id;
      if (!m.has(k)) m.set(k, { cook: t.cook, count: 0 });
      m.get(k).count += 1;
    });
    return Array.from(m.values()).sort((a, b) => b.count - a.count);
  }, [preparando]);

  // ─── Claim (cocinero toma platillo) ───
  const handleClaim = useCallback(async (orderId, itemIndex, cookCode) => {
    try {
      const res = await fetchWithAuth(`${API_BASE}/kds/items/${orderId}/${itemIndex}/claim`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cookCode }),
      });
      if (res.ok) {
        showToast("Platillo tomado");
        fetchItems();
      } else {
        const err = await res.json().catch(() => ({}));
        showToast(err.error || "Error al tomar platillo", "error");
      }
    } catch { showToast("Error de conexion", "error"); }
  }, [fetchItems, showToast]);

  // ─── Finish (marcar listo) ───
  const handleFinish = useCallback(async (orderId, itemIndex) => {
    try {
      const res = await fetchWithAuth(`${API_BASE}/kds/items/${orderId}/${itemIndex}/ready`, {
        method: 'POST',
      });
      if (res.ok) {
        const data = await res.json();
        showToast(data.message || "Platillo listo");
        fetchItems();
      }
    } catch { showToast("Error de conexion", "error"); }
  }, [fetchItems, showToast]);

  // ─── Columnas ───
  const cols = [
    { id: 'nuevo', label: 'Nuevos', count: nuevos.length, tickets: nuevos,
      tint: '#fdf0e0', fg: '#b75a07', ring: '#f3d2a3' },
    { id: 'preparando', label: 'Preparando', count: preparando.length, tickets: preparando,
      tint: '#eef5e6', fg: KDS_BRAND.green, ring: '#cfe2ba' },
    { id: 'listo', label: 'Listos para entregar', count: listos.length, tickets: listos,
      tint: '#e8efff', fg: '#2a4fb8', ring: '#bfd0ed' },
  ];

  const areaLabel = areaParam === 'bebidas' ? 'BEBIDAS' : 'COCINA';
  const StationIcon = areaParam === 'bebidas' ? KDSCoffeeIcon : KDSChefIcon;

  return (
    <div className="kds-v6-root" style={{
      background: KDS_BRAND.cream,
      fontFamily: 'Inter, -apple-system, sans-serif',
      color: KDS_BRAND.ink,
    }}>
      {/* Top Bar */}
      <KDSTopBar
        areaLabel={areaLabel}
        StationIcon={StationIcon}
        activeStation={areaParam}
        onSwitch={canSwitchArea ? setActiveStation : null}
        count={nuevos.length + preparando.length}
      />

      {/* Loading */}
      {loading ? (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ textAlign: 'center', color: KDS_BRAND.mute }}>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Cargando platillos...</div>
          </div>
        </div>
      ) : (
        /* Columns — using position:absolute to guarantee scroll */
        <div className="kds-v6-columns-area">
          <div className="kds-v6-columns-inner">
            {cols.map(c => (
              <KDSColumn
                key={c.id}
                col={c}
                onClaim={(t) => setClaimingItem(t)}
                onFinish={(t) => handleFinish(t.orderId, t.itemIndex)}
              />
            ))}
          </div>
        </div>
      )}

      {/* Workload strip */}
      <KDSWorkloadStrip workload={workload} areaLabel={areaLabel} />

      {/* Claim Modal */}
      {claimingItem && (
        <KDSClaimModal
          item={claimingItem}
          cooks={cooks}
          onCancel={() => setClaimingItem(null)}
          onConfirm={(cook) => {
            handleClaim(claimingItem.orderId, claimingItem.itemIndex, cook.id);
            setClaimingItem(null);
          }}
        />
      )}
    </div>
  );
};

// ============================================
// KDSTopBar
// ============================================

function KDSTopBar({ areaLabel, StationIcon, activeStation, onSwitch, count }) {
  return (
    <div style={{
      height: 64, flex: '0 0 64px',
      borderBottom: `1px solid ${KDS_BRAND.border}`,
      display: 'flex', alignItems: 'center',
      padding: '0 24px',
      gap: 24,
      background: '#fff',
    }}>
      {/* Left: area title */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 180 }}>
        <StationIcon size={20} color={KDS_BRAND.green} />
        <div style={{ fontWeight: 700, fontSize: 16, letterSpacing: '0.08em', color: KDS_BRAND.ink }}>
          {areaLabel}
        </div>
        <div style={{ fontSize: 12, color: KDS_BRAND.inkSoft, fontWeight: 500 }}>
          Por platillo
        </div>
      </div>

      {/* Center: station tabs */}
      {onSwitch && (
        <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
          <div style={{
            display: 'flex', gap: 4,
            background: '#f0ede4',
            padding: 4, borderRadius: 10,
          }}>
            <KDSStationTab
              icon={KDSChefIcon} label="Cocina"
              active={activeStation === 'cocina'}
              onClick={() => onSwitch('cocina')}
            />
            <KDSStationTab
              icon={KDSCoffeeIcon} label="Bebidas"
              active={activeStation === 'bebidas'}
              onClick={() => onSwitch('bebidas')}
            />
          </div>
        </div>
      )}

      {/* Right: count + refresh */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginLeft: 'auto' }}>
        <span style={{ fontSize: 14, fontWeight: 600, color: KDS_BRAND.ink }}>
          {count} {count === 1 ? 'platillo' : 'platillos'}
        </span>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
          background: '#f0ede4',
          padding: '6px 10px', borderRadius: 20, fontSize: 12,
        }}>
          <span style={{
            width: 8, height: 8, borderRadius: '50%',
            background: KDS_BRAND.green, display: 'inline-block',
            animation: 'kds-pulse 2s infinite',
          }} />
          <span style={{ fontFamily: 'monospace', fontWeight: 600, color: KDS_BRAND.ink }}>10s</span>
        </div>
      </div>
    </div>
  );
}

function KDSStationTab({ icon: Icon, label, active, onClick }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '8px 16px',
      borderRadius: 7,
      background: active ? KDS_BRAND.green : 'transparent',
      color: active ? '#fff' : KDS_BRAND.inkSoft,
      fontWeight: 600, fontSize: 14,
      cursor: 'pointer',
      transition: 'all .15s',
    }}>
      <Icon size={14} color={active ? '#fff' : 'currentColor'} />
      {label}
    </div>
  );
}

// ============================================
// KDSColumn
// ============================================

function KDSColumn({ col, onClaim, onFinish }) {
  return (
    <div className="kds-v6-column">
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '4px 6px 12px',
        flexShrink: 0,
      }}>
        <div style={{ width: 8, height: 8, borderRadius: '50%', background: col.fg }} />
        <div style={{
          fontSize: 12, fontWeight: 700, letterSpacing: '0.08em',
          textTransform: 'uppercase', color: KDS_BRAND.ink,
        }}>{col.label}</div>
        <div style={{
          marginLeft: 'auto',
          fontSize: 12, fontWeight: 700,
          background: col.tint, color: col.fg,
          padding: '3px 9px', borderRadius: 10,
          fontFamily: 'monospace',
        }}>{col.count}</div>
      </div>

      {/* Cards — scrollable */}
      <div className="kds-v6-cards">
        {col.tickets.length === 0 && (
          <div style={{
            padding: '32px 0', textAlign: 'center', fontSize: 11.5, color: KDS_BRAND.mute,
          }}>&mdash;</div>
        )}
        {col.tickets.map(t => (
          <KDSTicketCard
            key={t.key}
            ticket={t}
            phase={col.id}
            onClaim={() => onClaim(t)}
            onFinish={() => onFinish(t)}
          />
        ))}
      </div>
    </div>
  );
}

// ============================================
// KDSTicketCard — cada platillo
// ============================================

function KDSTicketCard({ ticket, phase, onClaim, onFinish }) {
  const urg = kdsUrgencyOf(ticket.minutes);
  const c = KDS_URGENCY[urg];

  return (
    <div style={{
      background: '#fff',
      borderRadius: 10,
      border: `1px solid ${phase === 'nuevo' ? c.border : KDS_BRAND.border}`,
      overflow: 'hidden',
      boxShadow: '0 1px 2px rgba(0,0,0,0.03)',
    }}>
      {/* Order context strip */}
      <div style={{
        padding: '7px 10px',
        background: '#faf8f2',
        borderBottom: `1px solid ${KDS_BRAND.border}`,
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 11, color: KDS_BRAND.inkSoft, fontWeight: 600,
      }}>
        <KDSOrderTypeIcon type={ticket.type} size={11} color={KDS_BRAND.inkSoft} />
        <span style={{ color: KDS_BRAND.ink, fontWeight: 700 }}>{ticket.source} {ticket.ref}</span>
        <div style={{
          marginLeft: 'auto',
          display: 'flex', alignItems: 'center', gap: 4,
          color: c.fg, fontWeight: 700,
          fontFamily: 'monospace',
        }}>
          <KDSClockIcon size={10} color={c.fg} />
          {ticket.minutes}m
        </div>
      </div>

      {/* Dish content */}
      <div style={{ padding: '12px 12px 10px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
          {/* Qty */}
          <div style={{
            fontSize: 26, fontWeight: 800,
            fontFamily: 'monospace',
            color: phase === 'listo' ? KDS_BRAND.mute : KDS_BRAND.green,
            lineHeight: 1,
            minWidth: 38,
          }}>
            {ticket.qty}<span style={{ fontSize: 16 }}>x</span>
          </div>
          {/* Name + mods */}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontSize: 15, fontWeight: 700, lineHeight: 1.25,
              color: phase === 'listo' ? KDS_BRAND.mute : KDS_BRAND.ink,
              textTransform: 'uppercase',
              letterSpacing: '0.01em',
              textDecoration: phase === 'listo' ? 'line-through' : 'none',
            }}>{ticket.name}</div>
            {ticket.mods && ticket.mods.length > 0 && (
              <div style={{ display: 'flex', gap: 4, marginTop: 6, flexWrap: 'wrap' }}>
                {ticket.mods.map((m, idx) => (
                  <span key={idx} style={{
                    fontSize: 10.5, fontWeight: 600,
                    color: KDS_BRAND.orange, background: KDS_BRAND.orangeSoft,
                    padding: '2px 6px', borderRadius: 4,
                  }}>{m}</span>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Order note */}
        {ticket.orderNote && (
          <div style={{
            marginTop: 10,
            padding: '6px 8px',
            background: KDS_BRAND.orangeSoft,
            borderRadius: 6,
            fontSize: 11, color: '#7a4a08', fontWeight: 500, lineHeight: 1.4,
          }}>{ticket.orderNote}</div>
        )}

        {/* Cook chip */}
        {ticket.cook && phase !== 'nuevo' && (
          <div style={{
            marginTop: 10,
            display: 'flex', alignItems: 'center', gap: 7,
            padding: '5px 8px 5px 5px',
            background: '#f4f2ec',
            borderRadius: 20,
            width: 'fit-content',
            border: `1px solid ${KDS_BRAND.border}`,
          }}>
            <KDSCookAvatar cook={ticket.cook} size={22} />
            <div style={{ fontSize: 11.5, fontWeight: 600, color: KDS_BRAND.ink }}>
              {ticket.cook.name}
            </div>
            <div style={{
              fontSize: 10, fontFamily: 'monospace',
              color: KDS_BRAND.inkSoft, paddingLeft: 4,
              borderLeft: `1px solid ${KDS_BRAND.border}`,
            }}>#{ticket.cook.id}</div>
          </div>
        )}
      </div>

      {/* Action buttons */}
      {phase === 'nuevo' && (
        <button onClick={onClaim} style={{
          width: '100%', background: '#fff', color: KDS_BRAND.green,
          border: `1.5px solid ${KDS_BRAND.green}`,
          padding: '10px 0',
          fontSize: 12.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
          cursor: 'pointer', fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
          borderBottomLeftRadius: 9, borderBottomRightRadius: 9,
          marginTop: -1,
        }}>
          <KDSPlayIcon size={11} color={KDS_BRAND.green} />
          COMENZAR
        </button>
      )}
      {phase === 'preparando' && (
        <button onClick={onFinish} style={{
          width: '100%', background: KDS_BRAND.green, color: '#fff',
          border: 'none', padding: '11px 0',
          fontSize: 12.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
          cursor: 'pointer', fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
        }}>
          <KDSCheckIcon size={13} color="#fff" />
          MARCAR LISTO
        </button>
      )}
      {phase === 'listo' && (
        <div style={{
          padding: '10px 12px',
          fontSize: 11, color: '#2a4fb8', fontWeight: 600,
          background: '#e8efff',
          textAlign: 'center', letterSpacing: '0.06em', textTransform: 'uppercase',
        }}>
          Entregar al pase
        </div>
      )}
    </div>
  );
}

// ============================================
// KDSCookAvatar
// ============================================

function KDSCookAvatar({ cook, size = 32 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: cook.color || '#2a4fb8',
      color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 700, fontSize: size * 0.36,
      letterSpacing: '0.02em',
      flex: '0 0 auto',
    }}>{cook.initials || '??'}</div>
  );
}

// ============================================
// KDSWorkloadStrip — footer con carga por cocinero
// ============================================

function KDSWorkloadStrip({ workload, areaLabel }) {
  return (
    <div style={{
      borderTop: `1px solid ${KDS_BRAND.border}`,
      padding: '10px 18px',
      display: 'flex', alignItems: 'center', gap: 12,
      background: '#fbfaf6',
      minHeight: 50,
    }}>
      <div style={{
        fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em',
        textTransform: 'uppercase', color: KDS_BRAND.inkSoft,
      }}>En {areaLabel.toLowerCase()} ahora</div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', flex: 1 }}>
        {workload.length === 0 ? (
          <div style={{ fontSize: 12, color: KDS_BRAND.mute }}>&mdash;</div>
        ) : workload.map(({ cook, count }) => (
          <div key={cook.id} style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '3px 9px 3px 3px',
            background: '#fff',
            border: `1px solid ${KDS_BRAND.border}`,
            borderRadius: 20,
          }}>
            <KDSCookAvatar cook={cook} size={22} />
            <div style={{ fontSize: 12, fontWeight: 600, color: KDS_BRAND.ink }}>{cook.name}</div>
            <div style={{
              fontSize: 11, fontWeight: 700, fontFamily: 'monospace',
              color: KDS_BRAND.green, background: KDS_BRAND.greenSoft,
              padding: '1px 6px', borderRadius: 8,
            }}>{count}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================
// KDSClaimModal — Keypad para ingresar ID de cocinero
// ============================================

function KDSClaimModal({ item, cooks, onCancel, onConfirm }) {
  const [pin, setPin] = useState('');
  const [error, setError] = useState(false);
  const matched = cooks.find(c => c.id === pin);

  const press = (d) => {
    setError(false);
    setPin(p => (p.length >= 2 ? p : (p + d)));
  };
  const back = () => { setError(false); setPin(p => p.slice(0, -1)); };
  const clear = () => { setError(false); setPin(''); };
  const submit = () => {
    if (matched) onConfirm(matched);
    else { setError(true); setPin(''); }
  };

  // ─── Soporte de teclado físico ───
  // Números 0-9 ingresan dígitos; Backspace borra; Enter confirma; Escape cancela.
  useEffect(() => {
    const onKey = (e) => {
      if (e.key >= '0' && e.key <= '9') {
        e.preventDefault();
        press(e.key);
      } else if (e.key === 'Backspace') {
        e.preventDefault();
        back();
      } else if (e.key === 'Enter') {
        e.preventDefault();
        submit();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        onCancel();
      } else if (e.key === 'Delete') {
        e.preventDefault();
        clear();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [matched]); // matched cambia con pin; submit usa matched actualizado

  // Auto-feedback: si 2 digitos y no hay match, mostrar error
  useEffect(() => {
    if (pin.length === 2 && !cooks.find(c => c.id === pin)) {
      const t = setTimeout(() => { setError(true); setPin(''); }, 350);
      return () => clearTimeout(t);
    }
  }, [pin, cooks]);

  // Auto-confirm: si match detectado
  useEffect(() => {
    if (matched && pin.length === 2) {
      const t = setTimeout(() => onConfirm(matched), 400);
      return () => clearTimeout(t);
    }
  }, [matched, pin]);

  return (
    <div
      onClick={onCancel}
      style={{
        position: 'absolute', inset: 0,
        background: 'rgba(20,22,18,0.55)',
        backdropFilter: 'blur(2px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 50,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: 400, maxWidth: '90vw',
          background: '#fff',
          borderRadius: 18,
          boxShadow: '0 24px 60px rgba(0,0,0,0.25)',
          overflow: 'hidden',
          fontFamily: 'Inter, -apple-system, sans-serif',
        }}
      >
        {/* Header */}
        <div style={{ padding: '20px 24px 0' }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: '0.1em',
            textTransform: 'uppercase', color: KDS_BRAND.inkSoft,
          }}>Tomar platillo</div>
          <div style={{
            marginTop: 4,
            fontSize: 18, fontWeight: 700, color: KDS_BRAND.ink, lineHeight: 1.25,
          }}>{item.name}</div>
          <div style={{
            marginTop: 18,
            fontSize: 13, color: KDS_BRAND.inkSoft, fontWeight: 500,
          }}>Ingresa tu ID de cocinero</div>
        </div>

        {/* PIN display */}
        <div style={{
          margin: '12px 24px 0',
          padding: '18px 16px',
          background: error ? '#fde6e3' : matched ? KDS_BRAND.greenSoft : '#f7f5ef',
          border: `1.5px solid ${error ? '#f1bdb7' : matched ? '#cfe2ba' : KDS_BRAND.border}`,
          borderRadius: 12,
          display: 'flex', alignItems: 'center', gap: 14,
          minHeight: 64,
          transition: 'background .15s, border-color .15s',
        }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {[0, 1].map(i => (
              <div key={i} style={{
                width: 38, height: 46, borderRadius: 8,
                background: '#fff',
                border: `1.5px solid ${error ? '#f1bdb7' : matched ? '#cfe2ba' : KDS_BRAND.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 24, fontWeight: 700,
                fontFamily: 'monospace',
                color: error ? '#a8170c' : matched ? KDS_BRAND.green : KDS_BRAND.ink,
              }}>{pin[i] || ''}</div>
            ))}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            {error ? (
              <div style={{ fontSize: 13, fontWeight: 700, color: '#a8170c' }}>
                ID no reconocido
              </div>
            ) : matched ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <KDSCookAvatar cook={matched} size={36} />
                <div>
                  <div style={{ fontSize: 14, fontWeight: 700, color: KDS_BRAND.ink }}>{matched.name}</div>
                  <div style={{ fontSize: 11, color: KDS_BRAND.green, fontWeight: 600 }}>Confirmado</div>
                </div>
              </div>
            ) : (
              <div style={{ fontSize: 12, color: KDS_BRAND.mute }}>2 digitos</div>
            )}
          </div>
        </div>

        {/* Keypad */}
        <div style={{
          padding: '18px 24px 12px',
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 10,
        }}>
          {[1, 2, 3, 4, 5, 6, 7, 8, 9].map(d => (
            <KDSKeypadButton key={d} onClick={() => press(String(d))}>{d}</KDSKeypadButton>
          ))}
          <KDSKeypadButton onClick={clear} variant="soft">C</KDSKeypadButton>
          <KDSKeypadButton onClick={() => press('0')}>0</KDSKeypadButton>
          <KDSKeypadButton onClick={back} variant="soft"><KDSBackspaceIcon /></KDSKeypadButton>
        </div>

        {/* Action buttons */}
        <div style={{
          padding: '4px 24px 22px', display: 'flex', gap: 10,
        }}>
          <button onClick={onCancel} style={{
            flex: 1,
            background: 'transparent',
            border: `1.5px solid ${KDS_BRAND.border}`,
            color: KDS_BRAND.inkSoft,
            padding: '12px 0', borderRadius: 10,
            fontSize: 13, fontWeight: 600,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>Cancelar</button>
          <button
            onClick={submit}
            disabled={!matched}
            style={{
              flex: 1.4,
              background: matched ? KDS_BRAND.green : '#cdd0c5',
              color: '#fff',
              border: 'none',
              padding: '12px 0', borderRadius: 10,
              fontSize: 13, fontWeight: 700, letterSpacing: '0.06em',
              cursor: matched ? 'pointer' : 'not-allowed',
              fontFamily: 'inherit',
              transition: 'background .15s',
            }}
          >Confirmar</button>
        </div>

        {/* Quick-access cook chips */}
        {cooks.length > 0 && (
          <div style={{
            padding: '0 24px 22px',
            display: 'flex', gap: 6, flexWrap: 'wrap',
            fontSize: 11, color: KDS_BRAND.inkSoft,
          }}>
            <span style={{ alignSelf: 'center', fontWeight: 600 }}>Acceso rapido:</span>
            {cooks.slice(0, 4).map(c => (
              <button
                key={c.id}
                onClick={() => { setPin(c.id); setError(false); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 5,
                  padding: '4px 8px 4px 4px',
                  background: '#f7f5ef',
                  border: `1px solid ${KDS_BRAND.border}`,
                  borderRadius: 14,
                  cursor: 'pointer', fontFamily: 'inherit',
                  fontSize: 11, fontWeight: 600, color: KDS_BRAND.ink,
                }}
              >
                <KDSCookAvatar cook={c} size={18} />
                {c.name.split(' ')[0]}
                <span style={{ fontFamily: 'monospace', color: KDS_BRAND.mute }}>#{c.id}</span>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================
// KDSKeypadButton
// ============================================

function KDSKeypadButton({ children, onClick, variant }) {
  const soft = variant === 'soft';
  return (
    <button
      onClick={onClick}
      style={{
        height: 56,
        border: `1.5px solid ${KDS_BRAND.border}`,
        background: soft ? '#f7f5ef' : '#fff',
        color: KDS_BRAND.ink,
        fontSize: 22, fontWeight: 600,
        fontFamily: 'monospace',
        borderRadius: 12,
        cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'background .1s, transform .05s',
      }}
      onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.97)'}
      onMouseUp={(e) => e.currentTarget.style.transform = ''}
      onMouseLeave={(e) => e.currentTarget.style.transform = ''}
    >{children}</button>
  );
}

// Export global
Object.assign(window, { KDSView });
