// Admin Panel component
const { useState: uS_a, useEffect: uE_a } = React;

function AdminPanel() {
  const { setRoute } = useRoute();
  const [products, setProducts] = uS_a([]);
  const [emails, setEmails] = uS_a([]);
  const [selectedEmails, setSelectedEmails] = uS_a([]);
  const [pendingOrders, setPendingOrders] = uS_a([]);
  const [guidesInput, setGuidesInput] = uS_a({});
  const [guideStatus, setGuideStatus] = uS_a({});
  const [debugInfo, setDebugInfo] = uS_a(null);
  const [loading, setLoading] = uS_a(true);
  const [msg, setMsg] = uS_a('');
  const [selectedNews, setSelectedNews] = uS_a([]);
  const [sendingEmail, setSendingEmail] = uS_a(false);
  const [newsStatus, setNewsStatus] = uS_a('');

  const ADMIN_SECRET = '1998Amarillo+-+-';

  const loadData = async () => {
    setLoading(true);
    try {
      const pRes = await fetch('/api/products');
      const pData = await pRes.json();
      setProducts(pData);

      const eRes = await fetch('/api/admin/emails', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ secret: ADMIN_SECRET })
      });
      if (eRes.ok) {
        const eData = await eRes.json();
        if (eData.emails) {
          setEmails(eData.emails);
          setSelectedEmails(eData.emails.map(x => x.email));
        }
        if (eData.debug) setDebugInfo(eData.debug);
      }

      const gRes = await fetch('/api/admin/pending-guides', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ secret: ADMIN_SECRET })
      });
      if (gRes.ok) {
        const gData = await gRes.json();
        if (gData.pending) setPendingOrders(gData.pending);
      }
    } catch (e) {
      console.error('Error cargando data admin', e);
    } finally {
      setLoading(false);
    }
  };

  uE_a(() => {
    loadData();
  }, []);

  const updateStock = async (slug, newStock) => {
    try {
      setMsg('Actualizando...');
      const r = await fetch('/api/admin/product-stock', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ secret: ADMIN_SECRET, slug, stock: parseInt(newStock) })
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Error actualizando stock');
      setMsg('¡Stock actualizado con éxito!');
      setTimeout(() => setMsg(''), 2000);
      loadData();
    } catch (e) {
      setMsg(e.message);
    }
  };

  const toggleSelection = (slug) => {
    setSelectedNews(prev => 
      prev.includes(slug) ? prev.filter(s => s !== slug) : [...prev, slug]
    );
  };

  const handleSendNewsletter = async () => {
    if (selectedNews.length === 0 || selectedEmails.length === 0) return;
    if (!confirm(`¿Estás seguro que deseas enviar un correo sobre estos ${selectedNews.length} productos a los ${selectedEmails.length} destinatarios seleccionados?`)) return;
    
    setSendingEmail(true);
    setNewsStatus('Enviando correos, por favor espera...');
    try {
      const itemsPayload = selectedNews.map(slug => products.find(p => p.slug === slug)).filter(Boolean);
      
      const r = await fetch('/newsletter/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ secret: ADMIN_SECRET, productos: itemsPayload, emails: selectedEmails })
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Error al enviar');
      setNewsStatus(`¡Éxito! El correo fue enviado a ${d.sent} coleccionistas.`);
      setSelectedNews([]); // reset
    } catch (e) {
      setNewsStatus(`Error: ${e.message}`);
    } finally {
      setSendingEmail(false);
    }
  };

  const handleSendGuide = async (folio) => {
    const guia = guidesInput[folio]?.trim();
    if (!guia) return;
    
    setGuideStatus(prev => ({ ...prev, [folio]: 'Enviando...' }));
    try {
      const r = await fetch('/api/admin/send-guide', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ secret: ADMIN_SECRET, folio, guia })
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error || 'Error enviando guía');
      
      setGuideStatus(prev => ({ ...prev, [folio]: '¡Guía enviada!' }));
      setTimeout(() => {
        setPendingOrders(prev => prev.filter(order => order.folio !== folio));
      }, 2000);
    } catch (e) {
      setGuideStatus(prev => ({ ...prev, [folio]: `Error: ${e.message}` }));
    }
  };

  if (loading) return (
    <div style={{ padding: 40, fontFamily: 'Special Elite,monospace', color: 'var(--paper)', minHeight: '80vh', background: 'var(--kraft)' }}>
      Cargando panel de administración...
    </div>
  );

  return (
    <section style={{ padding: '60px 20px', minHeight: '80vh', background: 'var(--kraft)' }}>
      <div style={{ maxWidth: 1000, margin: '0 auto', background: 'var(--paper)', border: '4px solid var(--ink)', boxShadow: '8px 8px 0 var(--ink)', padding: '40px 36px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 30, borderBottom: '3px solid var(--ink)', paddingBottom: 16 }}>
          <div>
            <h1 style={{ fontFamily: 'Bungee,sans-serif', fontSize: 32, color: 'var(--red)', margin: 0 }}>PANEL DE ADMIN</h1>
            <p style={{ fontFamily: 'Special Elite,monospace', margin: '4px 0 0', color: 'var(--ink-soft)' }}>Gestión de Inventario y Envíos de Correo</p>
          </div>
          <button onClick={() => setRoute({ page: 'home' })} style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '8px 16px', fontFamily: 'Special Elite,monospace', cursor: 'pointer', border: 'none' }}>
            ← Salir al Inicio
          </button>
        </div>

        {msg && <div style={{ background: '#f7c90a', color: '#1a1611', padding: 12, fontFamily: 'Special Elite,monospace', fontWeight: 'bold', marginBottom: 20, textAlign: 'center', border: '2px solid #1a1611' }}>{msg}</div>}

        {/* NEWSLETTER SECTION */}
        <div style={{ marginBottom: 40 }}>
          <h2 style={{ fontFamily: 'Oswald,sans-serif', fontSize: 24, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 16 }}>
            📢 Avisar a clientes (Múltiples Productos)
          </h2>
          <div style={{ background: '#fff', border: '2px solid var(--ink)', padding: 24 }}>
            <p style={{ fontFamily: 'Special Elite,monospace', fontSize: 14, marginBottom: 16 }}>
              Selecciona todos los productos que quieras anunciar. El correo agrupará a todos con su foto, título y botón a la tienda.
            </p>
            
            <div style={{ maxHeight: 200, overflowY: 'auto', border: '1px solid #ccc', padding: 10, marginBottom: 16 }}>
              {products.filter(p => p.stock > 0).map(p => (
                <label key={p.slug} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 0', fontFamily: 'Special Elite,monospace', cursor: 'pointer' }}>
                  <input 
                    type="checkbox" 
                    checked={selectedNews.includes(p.slug)}
                    onChange={() => toggleSelection(p.slug)}
                  />
                  <span>{p.nombre}</span>
                </label>
              ))}
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontFamily: 'Special Elite,monospace', fontWeight: 'bold' }}>
                {selectedNews.length} producto(s) y {selectedEmails.length} destinatario(s) seleccionados
              </div>
              <button 
                onClick={handleSendNewsletter} 
                disabled={selectedNews.length === 0 || selectedEmails.length === 0 || sendingEmail}
                style={{ background: 'var(--red)', color: '#fff', padding: '12px 24px', fontFamily: 'Bungee,sans-serif', fontSize: 14, border: '3px solid var(--ink)', cursor: (selectedNews.length === 0 || selectedEmails.length === 0 || sendingEmail) ? 'not-allowed' : 'pointer', opacity: (selectedNews.length === 0 || selectedEmails.length === 0 || sendingEmail) ? 0.6 : 1, boxShadow: '3px 3px 0 var(--ink)' }}
              >
                {sendingEmail ? 'Enviando...' : `✉ ENVIAR AVISO A SELECCIONADOS (${selectedEmails.length})`}
              </button>
            </div>
            {newsStatus && <p style={{ fontFamily: 'Special Elite,monospace', color: newsStatus.includes('Error') ? 'var(--red)' : '#2a7a3a', marginTop: 12, fontWeight: 'bold' }}>{newsStatus}</p>}
          </div>
        </div>

        {/* INVENTORY SECTION */}
        <div style={{ marginBottom: 40 }}>
          <h2 style={{ fontFamily: 'Oswald,sans-serif', fontSize: 24, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 16 }}>
            📦 Gestión de Inventario
          </h2>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'Special Elite,monospace', fontSize: 14, border: '2px solid var(--ink)' }}>
            <thead>
              <tr style={{ background: 'var(--ink)', color: 'var(--paper)' }}>
                <th style={{ padding: 12, textAlign: 'left' }}>Img</th>
                <th style={{ padding: 12, textAlign: 'left' }}>Producto</th>
                <th style={{ padding: 12, textAlign: 'left' }}>Estado</th>
                <th style={{ padding: 12, textAlign: 'center' }}>Stock</th>
                <th style={{ padding: 12, textAlign: 'center' }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {products.map(p => (
                <tr key={p.id} style={{ borderBottom: '1px solid #ccc', background: p.stock <= 0 ? '#eee' : '#fff' }}>
                  <td style={{ padding: 8 }}>
                    <img src={p.img} alt={p.nombre} style={{ width: 40, height: 40, objectFit: 'cover', border: '1px solid var(--ink)' }} />
                  </td>
                  <td style={{ padding: 8 }}>
                    <strong>{p.nombre}</strong><br/>
                    <small style={{ color: '#666' }}>{p.marca} · {p.categoria}</small>
                  </td>
                  <td style={{ padding: 8 }}>
                    {p.stock > 0 ? <span style={{ color: '#2a7a3a', fontWeight: 'bold' }}>Público</span> : <span style={{ color: 'var(--red)', fontWeight: 'bold' }}>Oculto / Agotado</span>}
                  </td>
                  <td style={{ padding: 8, textAlign: 'center' }}>
                    <input 
                      type="number" 
                      defaultValue={p.stock} 
                      min="0"
                      style={{ width: 60, padding: 4, fontFamily: 'Special Elite,monospace', textAlign: 'center', border: '2px solid var(--ink)' }}
                      onBlur={(e) => {
                        const val = parseInt(e.target.value);
                        if (!isNaN(val) && val !== p.stock) updateStock(p.slug, val);
                      }}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          const val = parseInt(e.target.value);
                          if (!isNaN(val) && val !== p.stock) updateStock(p.slug, val);
                          e.target.blur();
                        }
                      }}
                    />
                  </td>
                  <td style={{ padding: 8, textAlign: 'center' }}>
                    <button 
                      onClick={() => {
                        const newStock = p.stock > 0 ? 0 : 1;
                        updateStock(p.slug, newStock);
                      }}
                      style={{ background: p.stock > 0 ? 'var(--red)' : '#2a7a3a', color: '#fff', border: '2px solid var(--ink)', padding: '6px 10px', cursor: 'pointer', fontFamily: 'Special Elite,monospace' }}
                    >
                      {p.stock > 0 ? 'Ocultar' : 'Activar (Stock=1)'}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* GUÍAS DE ENVÍO SECTION */}
        <div style={{ marginBottom: 40 }}>
          <h2 style={{ fontFamily: 'Oswald,sans-serif', fontSize: 24, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 16 }}>
            🚚 Guías de Envío (Pedidos Pendientes)
          </h2>
          <div style={{ background: '#fff', border: '2px solid var(--ink)', padding: 24 }}>
            <p style={{ fontFamily: 'Special Elite,monospace', fontSize: 14, marginBottom: 16 }}>
              Aquí aparecen los pedidos registrados en Google Sheets cuya columna de Guía contiene "No" o está vacía. Escribe el número de guía de Correos de México y haz clic en "Enviar" para guardar la guía en el Sheets y enviarle un correo automatizado de rastreo al cliente.
            </p>
            
            {pendingOrders.length === 0 ? (
              <p style={{ fontFamily: 'Special Elite,monospace', margin: 0, color: '#2a7a3a', fontWeight: 'bold', fontSize: 15 }}>
                🎉 ¡No hay pedidos pendientes de guía! Todos los envíos están al día.
              </p>
            ) : (
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'Special Elite,monospace', fontSize: 13, border: '2px solid var(--ink)' }}>
                  <thead>
                    <tr style={{ background: 'var(--ink)', color: 'var(--paper)' }}>
                      <th style={{ padding: 10, textAlign: 'left' }}>Pedido</th>
                      <th style={{ padding: 10, textAlign: 'left' }}>Cliente / Email</th>
                      <th style={{ padding: 10, textAlign: 'left' }}>Productos / Total</th>
                      <th style={{ padding: 10, textAlign: 'left' }}>Dirección</th>
                      <th style={{ padding: 10, textAlign: 'center', width: 220 }}>Número de Guía</th>
                      <th style={{ padding: 10, textAlign: 'center', width: 100 }}>Acción</th>
                    </tr>
                  </thead>
                  <tbody>
                    {pendingOrders.map(order => (
                      <tr key={order.folio} style={{ borderBottom: '1px solid #ccc', background: '#fff' }}>
                        <td style={{ padding: 10 }}>
                          <strong>#{order.folio}</strong><br/>
                          <small style={{ color: '#666' }}>{order.fecha.split(',')[0]}</small>
                        </td>
                        <td style={{ padding: 10 }}>
                          <strong>{order.cliente}</strong><br/>
                          <small style={{ color: '#666', fontSize: 11 }}>{order.email}</small>
                        </td>
                        <td style={{ padding: 10 }}>
                          <span style={{ fontSize: 12 }}>{order.productos}</span><br/>
                          <strong>Total: ${order.total} MXN</strong>
                        </td>
                        <td style={{ padding: 10, fontSize: 11, maxWidth: 200, wordBreak: 'break-word' }}>
                          {order.direccion}
                        </td>
                        <td style={{ padding: 10, textAlign: 'center' }}>
                          <input 
                            type="text"
                            placeholder="Ej: EE123456789MX"
                            value={guidesInput[order.folio] || ''}
                            onChange={(e) => setGuidesInput(prev => ({ ...prev, [order.folio]: e.target.value.toUpperCase() }))}
                            style={{ width: '90%', padding: 6, fontFamily: 'monospace', fontSize: 13, border: '2px solid var(--ink)', textAlign: 'center', fontWeight: 'bold' }}
                          />
                          {guideStatus[order.folio] && (
                            <div style={{ fontSize: 11, marginTop: 4, fontWeight: 'bold', color: guideStatus[order.folio].includes('Error') ? 'var(--red)' : '#2a7a3a' }}>
                              {guideStatus[order.folio]}
                            </div>
                          )}
                        </td>
                        <td style={{ padding: 10, textAlign: 'center' }}>
                          <button
                            onClick={() => handleSendGuide(order.folio)}
                            disabled={!guidesInput[order.folio]?.trim() || guideStatus[order.folio] === 'Enviando...'}
                            style={{ background: '#2a7a3a', color: '#fff', border: '2px solid var(--ink)', padding: '6px 12px', cursor: (!guidesInput[order.folio]?.trim() || guideStatus[order.folio] === 'Enviando...') ? 'not-allowed' : 'pointer', fontFamily: 'Special Elite,monospace', fontSize: 12, opacity: (!guidesInput[order.folio]?.trim() || guideStatus[order.folio] === 'Enviando...') ? 0.6 : 1 }}
                          >
                            Enviar
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        {/* EMAILS LIST SECTION */}
        <div>
          <h2 style={{ fontFamily: 'Oswald,sans-serif', fontSize: 24, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 16 }}>
            📧 Base de Correos ({emails.length} activos)
          </h2>
          
          {debugInfo && (
            <div style={{ background: '#1a1611', color: '#f2e7cf', padding: 12, fontFamily: 'Special Elite,monospace', fontSize: 13, marginBottom: 16 }}>
              <strong>DIAGNÓSTICO DEL SERVIDOR:</strong><br/>
              • ¿ID de Google Sheets configurado?: {debugInfo.sheetsId ? '✅ SÍ' : '❌ NO'}<br/>
              • Correos leídos de Base de Datos (Sitio Web): {debugInfo.postgres}<br/>
              • Filas leídas en pestaña Pedidos: {debugInfo.pedidosRows}<br/>
              • Filas leídas en pestaña Sugerencias: {debugInfo.sugerenciasRows}<br/>
              {debugInfo.errors?.length > 0 && <span style={{ color: '#c5281c' }}>• Errores en Sheets: {debugInfo.errors.join(' | ')}</span>}
            </div>
          )}

          <div style={{ maxHeight: 300, overflowY: 'auto', border: '2px solid var(--ink)', background: '#fff' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'Special Elite,monospace', fontSize: 13 }}>
              <thead>
                <tr style={{ background: '#f7c90a', color: 'var(--ink)' }}>
                  <th style={{ padding: 10, width: 40, borderBottom: '2px solid var(--ink)', textAlign: 'center' }}>
                    <input 
                      type="checkbox"
                      checked={selectedEmails.length === emails.length && emails.length > 0}
                      onChange={(event) => {
                        if (event.target.checked) {
                          setSelectedEmails(emails.map(x => x.email));
                        } else {
                          setSelectedEmails([]);
                        }
                      }}
                      style={{ cursor: 'pointer' }}
                    />
                  </th>
                  <th style={{ padding: 10, textAlign: 'left', borderBottom: '2px solid var(--ink)' }}>Email</th>
                  <th style={{ padding: 10, textAlign: 'left', borderBottom: '2px solid var(--ink)' }}>Nombre</th>
                  <th style={{ padding: 10, textAlign: 'left', borderBottom: '2px solid var(--ink)' }}>Origen</th>
                  <th style={{ padding: 10, textAlign: 'left', borderBottom: '2px solid var(--ink)' }}>Fecha de registro</th>
                </tr>
              </thead>
              <tbody>
                {emails.map((e, idx) => (
                  <tr key={idx} style={{ borderBottom: '1px solid #eee', background: selectedEmails.includes(e.email) ? '#fff' : '#fafafa' }}>
                    <td style={{ padding: 10, textAlign: 'center' }}>
                      <input 
                        type="checkbox"
                        checked={selectedEmails.includes(e.email)}
                        onChange={() => {
                          setSelectedEmails(prev => 
                            prev.includes(e.email) ? prev.filter(x => x !== e.email) : [...prev, e.email]
                          );
                        }}
                        style={{ cursor: 'pointer' }}
                      />
                    </td>
                    <td style={{ padding: 10 }}>{e.email}</td>
                    <td style={{ padding: 10 }}>{e.nombre || 'N/A'}</td>
                    <td style={{ padding: 10, color: '#666', fontSize: 11 }}>{e.origen}</td>
                    <td style={{ padding: 10 }}>{e.fecha ? new Date(e.fecha).toLocaleDateString('es-MX') : 'N/A'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

      </div>
    </section>
  );
}

Object.assign(window, { AdminPanel });
