// ===== RIVAMAR Group — Módulos del panel admin (v1.1) =====
const { useState, useMemo } = React;

// ---------- Iconos ----------
const AdminIcons = {
  grid: <g><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></g>,
  list: <g><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></g>,
  calendar: <g><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></g>,
  image: <g><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></g>,
  edit: <g><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></g>,
  users: <g><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></g>,
  chart: <g><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></g>,
  briefcase: <g><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></g>,
  home: <g><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></g>,
  trash: <g><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></g>,
  star: <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>,
  plus: <g><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></g>,
  reset: <g><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></g>,
  mail: <g><path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><polyline points="22,6 12,13 2,6"/></g>,
  globe: <g><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></g>,
  book: <g><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></g>,
};
function AdIcon({ name, size = 18 }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">{AdminIcons[name]}</svg>;
}

// ---------- Vista calendario ----------
function CalendarView({ reservas, onSelect }) {
  const [month, setMonth] = useState(new Date(2026, 5, 1)); // junio 2026 (local)
  const y = month.getFullYear(), m = month.getMonth();
  const first = new Date(y, m, 1);
  const startDow = (first.getDay() + 6) % 7; // lunes=0
  const days = new Date(y, m + 1, 0).getDate();
  const monthName = month.toLocaleDateString('es-CL', { month: 'long', year: 'numeric' });

  const byDate = {};
  reservas.forEach((r) => { (byDate[r.fecha] = byDate[r.fecha] || []).push(r); });

  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= days; d++) cells.push(d);

  const dateStr = (d) => `${y}-${String(m + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;

  return (
    <div className="p-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-display font-bold text-gray-50 capitalize">{monthName}</h3>
        <div className="flex gap-1">
          <button onClick={() => setMonth(new Date(y, m - 1, 1))} className="w-9 h-9 grid place-items-center rounded-md bg-carbon border border-white/10 text-gray-300 hover:border-gold">‹</button>
          <button onClick={() => setMonth(new Date(y, m + 1, 1))} className="w-9 h-9 grid place-items-center rounded-md bg-carbon border border-white/10 text-gray-300 hover:border-gold">›</button>
        </div>
      </div>
      <div className="grid grid-cols-7 gap-1.5 text-center text-[11px] uppercase tracking-wider text-gray-500 mb-1.5">
        {['Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá', 'Do'].map((d) => <div key={d}>{d}</div>)}
      </div>
      <div className="grid grid-cols-7 gap-1.5">
        {cells.map((d, i) => {
          if (!d) return <div key={i}></div>;
          const items = byDate[dateStr(d)] || [];
          return (
            <div key={i} className="min-h-[68px] rounded-md bg-carbon border border-white/5 p-1.5 text-left">
              <div className="text-[11px] text-gray-500 mb-1">{d}</div>
              <div className="space-y-1">
                {items.slice(0, 2).map((r) => (
                  <button key={r.id} onClick={() => onSelect(r)}
                    className={`w-full text-left text-[10px] truncate px-1 py-0.5 rounded ${
                      r.estado === 'confirmada' ? 'bg-emerald-500/20 text-emerald-300' : r.estado === 'cancelada' ? 'bg-red-500/15 text-red-300 line-through' : 'bg-orange-500/20 text-orange-300'
                    }`}>
                    {r.hora} {LOCAL_MAP[r.local].nombre.split(' ').pop()}
                  </button>
                ))}
                {items.length > 2 && <div className="text-[9px] text-gray-500 px-1">+{items.length - 2} más</div>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---------- Modal editar reserva ----------
function EditModal({ reserva, onSave, onClose }) {
  const [r, setR] = useState(reserva);
  if (!reserva) return null;
  const set = (k) => (e) => setR({ ...r, [k]: e.target.value });
  return (
    <div className="fixed inset-0 z-[60] bg-carbon/80 backdrop-blur-sm grid place-items-center p-4" onClick={onClose}>
      <div className="bg-iron border border-white/10 rounded-xl w-full max-w-md p-6" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-5">
          <h3 className="font-display font-bold text-gray-50">Editar reserva <span className="font-mono text-gold text-sm">{r.id}</span></h3>
          <button onClick={onClose} className="text-gray-500 hover:text-gray-200">✕</button>
        </div>
        <div className="space-y-3 text-sm">
          <Field label="Nombre"><input className={inputCls} value={r.nombre || ''} onChange={set('nombre')} /></Field>
          <Field label="Empresa"><input className={inputCls} value={r.empresa || ''} onChange={set('empresa')} /></Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Correo"><input type="email" className={inputCls} value={r.correo || ''} onChange={set('correo')} /></Field>
            <Field label="Teléfono"><input className={inputCls} value={r.telefono || ''} onChange={set('telefono')} /></Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Fecha"><input type="date" className={inputCls} value={r.fecha || ''} onChange={set('fecha')} /></Field>
            <Field label="Hora">
              <select className={inputCls} value={r.hora || ''} onChange={set('hora')}>
                <option value="">—</option>
                {HORARIOS.map((h) => <option key={h} value={h}>{h} hrs</option>)}
              </select>
            </Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Local">
              <select className={inputCls} value={r.local} onChange={set('local')}>
                {LOCALES.map((l) => <option key={l.id} value={l.id}>{l.nombre}</option>)}
              </select>
            </Field>
            <Field label="N° de personas"><input type="number" min="1" className={inputCls} value={r.pax || ''} onChange={(e) => setR({ ...r, pax: parseInt(e.target.value) || 0 })} /></Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Estado">
              <select className={inputCls} value={r.estado} onChange={set('estado')}>
                <option value="pendiente">Pendiente</option>
                <option value="confirmada">Confirmada</option>
                <option value="cancelada">Cancelada</option>
                <option value="eliminada">Eliminada</option>
              </select>
            </Field>
            <Field label="Beneficio EXPONOR">
              <select className={inputCls} value={r.exponor ? 'si' : 'no'} onChange={(e) => setR({ ...r, exponor: e.target.value === 'si' })}>
                <option value="no">Sin descuento</option>
                <option value="si">EXPONOR 15%</option>
              </select>
            </Field>
          </div>
          <Field label="Credencial EXPONOR"><input className={inputCls} value={r.credencial || ''} onChange={set('credencial')} placeholder="N° de credencial (opcional)" /></Field>
          <Field label="Comentarios"><textarea className={inputCls + ' !h-16 py-2 resize-none'} value={r.comentarios || ''} onChange={set('comentarios')} /></Field>
        </div>
        <div className="flex gap-3 mt-6">
          <Btn variant="ghost" onClick={onClose} className="flex-1">Cancelar</Btn>
          <Btn variant="primary" onClick={() => onSave(r)} className="flex-1">Guardar cambios</Btn>
        </div>
      </div>
    </div>
  );
}

// ---------- Reportes ----------
function Reportes({ reservas }) {
  const porLocal = LOCALES.map((l) => ({
    local: l.nombre,
    total: reservas.filter((r) => r.local === l.id).length,
    exponor: reservas.filter((r) => r.local === l.id && r.exponor).length,
    tono: l.tono,
  }));
  const maxTotal = Math.max(1, ...porLocal.map((p) => p.total));
  const pax = reservas.reduce((s, r) => s + (r.estado !== 'cancelada' ? r.pax : 0), 0);
  const exponorPax = reservas.filter((r) => r.exponor).reduce((s, r) => s + r.pax, 0);
  const confirmadas = reservas.filter((r) => r.estado === 'confirmada').length;
  const tasa = Math.round(100 * confirmadas / Math.max(1, reservas.length));

  const exportPDF = () => {
    const fecha = new Date().toLocaleDateString('es-CL', { day: '2-digit', month: 'long', year: 'numeric' });
    const filas = porLocal.map((p) => `<tr><td>${p.local}</td><td style="text-align:center">${p.total}</td><td style="text-align:center;color:#B45309">${p.exponor}</td></tr>`).join('');
    const html = `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>Reporte RIVAMAR</title>
      <style>
        @media print { @page { margin: 18mm; } }
        body{font-family:Arial,Helvetica,sans-serif;color:#111827;margin:0;padding:32px;}
        .brand{display:flex;align-items:center;gap:10px;border-bottom:3px solid #C8A000;padding-bottom:14px;margin-bottom:8px}
        .logo{width:36px;height:36px;background:#C8A000;color:#111827;font-weight:800;display:grid;place-items:center;border-radius:4px;font-size:20px}
        h1{font-size:20px;margin:0} .sub{color:#6B7280;font-size:12px;margin:2px 0 0}
        .meta{color:#6B7280;font-size:12px;margin:18px 0}
        .kpis{display:flex;gap:12px;margin:20px 0}
        .kpi{flex:1;border:1px solid #E5E7EB;border-radius:8px;padding:14px}
        .kpi .n{font-size:26px;font-weight:800;color:#B45309} .kpi .l{font-size:11px;color:#6B7280;margin-top:4px}
        table{width:100%;border-collapse:collapse;margin-top:8px;font-size:13px}
        th,td{border:1px solid #E5E7EB;padding:8px 10px;text-align:left} th{background:#1A2A3A;color:#fff;font-size:12px}
        h2{font-size:14px;color:#B45309;margin:26px 0 6px} .foot{margin-top:30px;border-top:1px solid #E5E7EB;padding-top:10px;color:#9CA3AF;font-size:11px}
      </style></head><body>
      <div class="brand"><div class="logo">R</div><div><h1>RIVAMAR Group — Reporte de Reservas</h1><p class="sub">Antofagasta, Chile · MAEDY GROUP</p></div></div>
      <p class="meta">Generado el ${fecha} · Periodo: histórico acumulado</p>
      <div class="kpis">
        <div class="kpi"><div class="n">${reservas.length}</div><div class="l">Total reservas</div></div>
        <div class="kpi"><div class="n">${confirmadas}</div><div class="l">Confirmadas</div></div>
        <div class="kpi"><div class="n">${pax}</div><div class="l">Comensales activos</div></div>
        <div class="kpi"><div class="n">${tasa}%</div><div class="l">Tasa confirmación</div></div>
      </div>
      <h2>Reservas por local</h2>
      <table><thead><tr><th>Local</th><th style="text-align:center">Total reservas</th><th style="text-align:center">Con EXPONOR</th></tr></thead><tbody>${filas}</tbody></table>
      <h2>Beneficio EXPONOR 2026</h2>
      <table><tbody>
        <tr><td>Reservas con descuento EXPONOR</td><td style="text-align:right">${reservas.filter(r=>r.exponor).length}</td></tr>
        <tr><td>Comensales bajo beneficio EXPONOR</td><td style="text-align:right">${exponorPax}</td></tr>
      </tbody></table>
      <p class="foot">Documento generado automáticamente desde el Panel de Administración · RIVAMAR Group © 2026</p>
      <script>window.onload=function(){setTimeout(function(){window.print()},300)}<\/script>
      </body></html>`;
    const w = window.open('', '_blank');
    if (w) { w.document.write(html); w.document.close(); }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-end">
        <Btn variant="outline" onClick={exportPDF} className="!min-h-[38px] !px-3 !text-xs"><AdIcon name="image" size={14} /> Exportar PDF</Btn>
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <MiniStat label="Comensales (activos)" value={pax} accent="#C8A000" />
        <MiniStat label="Comensales EXPONOR" value={exponorPax} accent="#F5A623" />
        <MiniStat label="Ticket promedio pax" value={Math.round(pax / Math.max(1, reservas.filter(r=>r.estado!=='cancelada').length))} accent="#B87333" />
        <MiniStat label="Tasa confirmación" value={tasa + '%'} accent="#10B981" />
      </div>
      <div className="bg-iron border border-white/10 rounded-xl p-6">
        <h3 className="font-display font-bold text-gray-50 mb-5">Reservas por local</h3>
        <div className="space-y-4">
          {porLocal.map((p) => (
            <div key={p.local}>
              <div className="flex justify-between text-sm mb-1.5">
                <span className="text-gray-300">{p.local}</span>
                <span className="text-gray-400">{p.total} reservas · <span className="text-exponor">{p.exponor} EXPONOR</span></span>
              </div>
              <div className="h-3 rounded-full bg-carbon overflow-hidden">
                <div className="h-full rounded-full transition-all" style={{ width: `${(p.total / maxTotal) * 100}%`, background: p.tono }}></div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <p className="text-xs text-gray-500 font-mono">Métricas calculadas sobre las reservas del periodo actual · exportables a CSV (Gestión de Reservas) y PDF.</p>
    </div>
  );
}
function MiniStat({ label, value, accent }) {
  return (
    <div className="bg-iron border border-white/10 rounded-xl p-5 relative overflow-hidden">
      <div className="absolute top-0 left-0 w-full h-0.5" style={{ background: accent }}></div>
      <div className="font-display text-2xl font-bold text-gray-50">{value}</div>
      <div className="text-xs text-gray-400 mt-1">{label}</div>
    </div>
  );
}

// ---------- Galería admin ----------
const GAL_VACIA = { local: '', cat: '', titulo: '', orden: 0, desc: '', img: '', destacada: false };

function GaleriaForm({ initial, onSave, onCancel }) {
  const [f, setF] = useState(initial || GAL_VACIA);
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const selCls = inputCls;
  const valid = f.local && f.cat && f.img;
  return (
    <div className="bg-iron border border-white/10 rounded-xl p-6">
      <div className="flex items-center justify-between mb-5">
        <h3 className="font-display font-bold text-gray-50 text-lg">{initial ? 'Editar foto' : 'Nueva foto'}</h3>
        <button onClick={onCancel} className="text-gray-500 hover:text-gray-200 w-8 h-8 grid place-items-center">✕</button>
      </div>
      <div className="grid sm:grid-cols-2 gap-5">
        <Field label="Local" required>
          <select className={selCls} value={f.local} onChange={set('local')}>
            <option value="">Seleccionar…</option>
            {LOCALES.map((l) => <option key={l.id} value={l.id}>{l.nombre}</option>)}
          </select>
        </Field>
        <Field label="Categoría" required>
          <select className={selCls} value={f.cat} onChange={set('cat')}>
            <option value="">Seleccionar…</option>
            {Object.entries(CAT_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
        </Field>
        <Field label="Título del plato">
          <input className={inputCls} value={f.titulo} onChange={set('titulo')} placeholder="Ej: Ceviche Clásico" />
        </Field>
        <Field label="Orden (0 = primero)">
          <input type="number" className={inputCls} value={f.orden} onChange={set('orden')} placeholder="0" />
        </Field>
      </div>
      <div className="mt-5">
        <Field label="Descripción">
          <textarea className={inputCls + ' !h-20 py-2.5 resize-none'} value={f.desc} onChange={set('desc')} placeholder="Descripción del plato…" />
        </Field>
      </div>
      <div className="mt-5">
        <span className="block text-sm font-medium text-gray-300 mb-1.5">Imagen <span className="text-copper">*</span></span>
        <ImagePicker value={f.img} onChange={(v) => setF({ ...f, img: v })} ratio="1/1" />
      </div>
      <label className="flex items-center gap-2.5 mt-5 cursor-pointer select-none">
        <input type="checkbox" checked={f.destacada} onChange={(e) => setF({ ...f, destacada: e.target.checked })} className="w-5 h-5 rounded border-white/20 bg-carbon accent-[#C8A000]" />
        <span className="text-sm font-medium text-gray-200">Foto destacada</span>
      </label>
      <div className="flex gap-3 mt-6">
        <Btn variant="primary" onClick={() => onSave(f)} disabled={!valid} className="!px-5"><AdIcon name="plus" size={15} /> Guardar foto</Btn>
        <Btn variant="ghost" onClick={onCancel}>Cancelar</Btn>
      </div>
      {!valid && <p className="text-[11px] text-gray-500 mt-2">Local, categoría e imagen son obligatorios.</p>}
    </div>
  );
}

function GaleriaAdmin({ galeria, setGaleria }) {
  const [filtro, setFiltro] = useState('todos');
  const [toast, setToast] = useState('');
  const [form, setForm] = useState(null); // null | {} (nueva) | item (editar)
  const flash = (m) => { setToast(m); setTimeout(() => setToast(''), 2200); };
  const items = (filtro === 'todos' ? galeria : galeria.filter((g) => g.local === filtro))
    .slice().sort((a, b) => (b.destacada ? 1 : 0) - (a.destacada ? 1 : 0) || (a.orden || 0) - (b.orden || 0));

  const toggleDest = (id) => setGaleria((p) => p.map((g) => g.id === id ? { ...g, destacada: !g.destacada } : g));
  const remove = (id) => { if (confirm('¿Eliminar esta foto de la galería?')) setGaleria((p) => p.filter((g) => g.id !== id)); };

  const save = (f) => {
    const data = { ...f, label: f.titulo || f.label || 'Foto', orden: Number(f.orden) || 0 };
    if (f.id) {
      setGaleria((p) => p.map((g) => g.id === f.id ? data : g));
      flash('Foto actualizada');
    } else {
      const id = Math.max(0, ...galeria.map((g) => g.id)) + 1;
      setGaleria((p) => [{ ...data, id }, ...p]);
      flash('Foto agregada a la galería');
    }
    setForm(null);
  };

  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap gap-2">
          {[{ id: 'todos', label: 'Todos' }, ...LOCALES.map((l) => ({ id: l.id, label: l.nombre }))].map((p) => (
            <button key={p.id} onClick={() => setFiltro(p.id)}
              className={`px-3 py-1.5 rounded-md text-xs font-medium ${filtro === p.id ? 'bg-gold text-carbon' : 'bg-carbon border border-white/10 text-gray-400 hover:text-gray-100'}`}>{p.label}</button>
          ))}
        </div>
        {!form && <Btn variant="primary" onClick={() => setForm(GAL_VACIA)} className="!min-h-[38px] !px-3 !text-xs"><AdIcon name="plus" size={14} /> Agregar foto</Btn>}
      </div>

      {form && <GaleriaForm initial={form.id ? form : null} onSave={save} onCancel={() => setForm(null)} />}

      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
        {items.map((g) => (
          <div key={g.id} className="bg-iron border border-white/10 rounded-xl overflow-hidden group">
            <div className="relative">
              <ImgSlot label={g.label} src={g.img} tone={LOCAL_MAP[g.local].tono} ratio="1/1" className="w-full" />
              {g.destacada && <span className="absolute top-2 left-2 text-[9px] font-mono uppercase px-1.5 py-0.5 rounded bg-gold text-carbon font-bold">★</span>}
            </div>
            <div className="p-3">
              <p className="text-xs font-medium text-gray-200 truncate">{g.label}</p>
              <p className="text-[10px] text-gray-500 mb-2">{LOCAL_MAP[g.local].nombre} · {CAT_LABEL[g.cat]}</p>
              <div className="flex gap-1.5">
                <button onClick={() => toggleDest(g.id)} className={`flex-1 text-[10px] font-semibold py-1.5 rounded ${g.destacada ? 'bg-gold/20 text-gold' : 'bg-white/5 text-gray-400 hover:text-gray-100'}`}>★ Destacar</button>
                <button onClick={() => setForm(g)} className="w-8 grid place-items-center rounded bg-white/5 text-gray-400 hover:text-gold"><AdIcon name="edit" size={13} /></button>
                <button onClick={() => remove(g.id)} className="w-8 grid place-items-center rounded bg-red-500/10 text-red-400 hover:bg-red-500/20"><AdIcon name="trash" size={13} /></button>
              </div>
            </div>
          </div>
        ))}
      </div>
      {toast && <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-emerald-600 text-white text-sm px-5 py-3 rounded-lg shadow-xl">{toast}</div>}
    </div>
  );
}

// ---------- CMS Lite movido a admin-cms.jsx (editor de contenido completo) ----------

// ---------- Usuarios ----------
function Usuarios({ users, setUsers }) {
  const [query, setQuery] = useState('');
  const [nuevo, setNuevo] = useState({ nombre: '', correo: '', pass: '', rol: 'Usuario básico' });
  const [editId, setEditId] = useState(null);
  const [passId, setPassId] = useState(null);
  const [passVal, setPassVal] = useState('');
  const [toast, setToast] = useState('');
  const flash = (m) => { setToast(m); setTimeout(() => setToast(''), 3000); };
  const setN = (k) => (e) => setNuevo({ ...nuevo, [k]: e.target.value });

  const filtered = users.filter((u) => `${u.nombre} ${u.correo}`.toLowerCase().includes(query.toLowerCase()));

  // Crea y guarda el usuario en el store SIEMPRE. Si es invitación, intenta enviar correo.
  const crearUsuario = (invitar) => {
    if (!nuevo.correo.includes('@')) { flash('Ingresa un correo válido'); return; }
    if (users.some((u) => u.correo.toLowerCase() === nuevo.correo.toLowerCase())) { flash('Ese correo ya existe'); return; }
    const id = Math.max(0, ...users.map((u) => u.id)) + 1;
    const registro = {
      id, nombre: nuevo.nombre.trim() || nuevo.correo.split('@')[0], correo: nuevo.correo.trim(),
      pass: nuevo.pass.trim(), rol: nuevo.rol, ultima: '—', estado: invitar ? 'pendiente' : 'activo',
      modulos: ROLES[nuevo.rol].modulos.slice(),
      creado: new Date().toLocaleString('es-CL'),
    };
    // Guardado persistente primero (no depende del envío)
    setUsers((p) => [...p, registro]);
    if (invitar) {
      const site = (typeof window !== 'undefined' && window.SITE) || {};
      let enviado = false;
      try {
        if (window.emailjs && site.emailjs_public && site.emailjs_service && site.emailjs_template) {
          emailjs.init({ publicKey: site.emailjs_public });
          emailjs.send(site.emailjs_service, site.emailjs_template, {
            reserva_id: 'INVITACION', nombre: registro.nombre, correo: registro.correo,
            local: 'Panel Admin', comentarios: 'Invitación de acceso como ' + registro.rol,
            email_destino: registro.correo,
          });
          enviado = true;
        }
      } catch (e) { enviado = false; }
      flash(enviado ? 'Usuario creado e invitación enviada a ' + registro.correo
                    : 'Usuario creado y guardado. Envío de correo no disponible — comparte el acceso manualmente.');
    } else {
      flash('Usuario creado y guardado: ' + registro.correo);
    }
    setNuevo({ nombre: '', correo: '', pass: '', rol: 'Usuario básico' });
  };

  const cambiarPass = (id) => {
    if (!passVal.trim()) { flash('Ingresa una contraseña'); return; }
    setUsers((p) => p.map((u) => u.id === id ? { ...u, pass: passVal.trim() } : u));
    flash('Contraseña actualizada');
    setPassId(null); setPassVal('');
  };

  const remove = (id) => setUsers((p) => p.filter((u) => u.id !== id));
  const setRol = (id, rol) => setUsers((p) => p.map((u) => u.id === id ? { ...u, rol, modulos: ROLES[rol].modulos.slice() } : u));
  const setEstadoU = (id, estado) => setUsers((p) => p.map((u) => u.id === id ? { ...u, estado } : u));
  const toggleModulo = (id, mod) => setUsers((p) => p.map((u) => {
    if (u.id !== id) return u;
    const has = (u.modulos || []).includes(mod);
    return { ...u, modulos: has ? u.modulos.filter((m) => m !== mod) : [...(u.modulos || []), mod] };
  }));

  const rolBadge = (rol) => {
    const map = { 'Administrador': 'bg-gold/15 text-gold', 'Encargado Local': 'bg-sky-500/15 text-sky-300', 'Usuario básico': 'bg-white/5 text-gray-300' };
    return map[rol] || 'bg-white/5 text-gray-300';
  };

  const inp = "w-full min-h-[42px] px-3 rounded-md bg-carbon border border-white/10 text-gray-100 text-sm placeholder-gray-600 focus:border-gold outline-none";

  return (
    <div className="space-y-5">
      {/* Leyenda de roles */}
      <div className="grid sm:grid-cols-3 gap-3">
        {Object.entries(ROLES).map(([rol, info]) => (
          <div key={rol} className="bg-iron border border-white/10 rounded-xl p-4">
            <span className={`inline-block text-xs font-semibold px-2.5 py-1 rounded-full ${rolBadge(rol)}`}>{rol}</span>
            <p className="text-xs text-gray-400 mt-2 leading-snug">{info.desc}</p>
            <p className="text-[11px] text-gray-600 mt-1.5">{info.modulos.length} de {ADMIN_MODULOS.length} módulos</p>
          </div>
        ))}
      </div>

      {/* Crear / invitar usuario */}
      <div className="bg-iron border border-white/10 rounded-xl p-5">
        <h3 className="font-display font-bold text-gray-50 text-sm mb-3 flex items-center gap-2"><AdIcon name="users" size={16} /> Crear usuario</h3>
        <div className="grid sm:grid-cols-2 gap-3">
          <input className={inp} value={nuevo.nombre} onChange={setN('nombre')} placeholder="Nombre completo" />
          <input className={inp} value={nuevo.correo} onChange={setN('correo')} placeholder="correo@rivamar.cl" />
          <input className={inp} value={nuevo.pass} onChange={setN('pass')} placeholder="Contraseña" type="text" />
          <select className={inp} value={nuevo.rol} onChange={setN('rol')}>
            {Object.keys(ROLES).map((r) => <option key={r} value={r}>{r}</option>)}
          </select>
        </div>
        <div className="flex flex-wrap gap-2 mt-3">
          <Btn variant="primary" onClick={() => crearUsuario(false)} className="!min-h-[40px] !px-4 !text-xs"><AdIcon name="users" size={14} /> Crear usuario (activo)</Btn>
          <Btn variant="ghost" onClick={() => crearUsuario(true)} className="!min-h-[40px] !px-4 !text-xs"><AdIcon name="mail" size={14} /> Crear e invitar por correo</Btn>
        </div>
        <p className="text-[11px] text-gray-500 mt-2.5 leading-relaxed">El usuario se <strong className="text-gray-400">guarda siempre</strong>, aunque el envío del correo falle o no esté configurado. La invitación queda en estado «Pendiente» hasta que el usuario active su acceso.</p>
      </div>

      <div className="relative max-w-xs">
        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500"><AdIcon name="users" size={15} /></span>
        <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar usuario…" className="w-full min-h-[40px] pl-9 pr-3 rounded-md bg-carbon border border-white/10 text-gray-100 text-sm placeholder-gray-600 focus:border-gold outline-none" />
      </div>

      <div className="bg-iron border border-white/10 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="text-left text-xs uppercase tracking-wider text-gray-500 border-b border-white/10">
              <th className="px-4 py-3 font-semibold">Usuario</th>
              <th className="px-4 py-3 font-semibold">Rol</th>
              <th className="px-4 py-3 font-semibold">Módulos</th>
              <th className="px-4 py-3 font-semibold">Estado</th>
              <th className="px-4 py-3 font-semibold text-right">Acciones</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((u) => (
              <React.Fragment key={u.id}>
              <tr className="border-b border-white/5 hover:bg-white/[0.02]">
                <td className="px-4 py-3">
                  <div className="font-medium text-gray-100">{u.nombre}</div>
                  <div className="text-xs text-gray-500">{u.correo}</div>
                </td>
                <td className="px-4 py-3">
                  <select value={u.rol} onChange={(e) => setRol(u.id, e.target.value)}
                    className={`text-xs font-semibold px-2.5 py-1.5 rounded-md bg-carbon border border-white/10 outline-none ${rolBadge(u.rol).split(' ')[1]}`}>
                    {Object.keys(ROLES).map((r) => <option key={r} value={r}>{r}</option>)}
                  </select>
                </td>
                <td className="px-4 py-3">
                  <button onClick={() => setEditId(editId === u.id ? null : u.id)} className="text-xs font-medium text-sky-300 hover:text-sky-200 inline-flex items-center gap-1">
                    {(u.modulos || []).length} módulos <AdIcon name="edit" size={12} />
                  </button>
                </td>
                <td className="px-4 py-3">
                  {u.estado === 'pendiente'
                    ? <button onClick={() => setEstadoU(u.id, 'activo')} title="Activar acceso" className="inline-flex items-center gap-1.5 text-xs font-semibold text-orange-400 hover:text-emerald-400"><span className="w-1.5 h-1.5 rounded-full bg-orange-400"></span>Pendiente · activar</button>
                    : <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-emerald-400"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>Activo</span>}
                </td>
                <td className="px-4 py-3 text-right">
                  <div className="flex items-center justify-end gap-1.5">
                    <button onClick={() => { setPassId(passId === u.id ? null : u.id); setPassVal(''); }} title="Cambiar contraseña" className="text-xs font-semibold px-2.5 py-1.5 rounded-md bg-white/5 text-gray-300 hover:text-gold">🔑 Contraseña</button>
                    <button onClick={() => remove(u.id)} className="text-xs font-semibold px-2.5 py-1.5 rounded-md bg-red-500/10 text-red-400 hover:bg-red-500/20">Revocar</button>
                  </div>
                </td>
              </tr>
              {passId === u.id && (
                <tr className="bg-carbon/40 border-b border-white/5">
                  <td colSpan="5" className="px-4 py-4">
                    <p className="text-xs font-semibold text-gray-300 mb-2.5">Nueva contraseña para <span className="text-gold">{u.nombre}</span>:</p>
                    <div className="flex flex-wrap gap-2 items-center">
                      <input className={inp + ' max-w-xs'} value={passVal} onChange={(e) => setPassVal(e.target.value)} placeholder="Nueva contraseña" type="text" />
                      <Btn variant="primary" onClick={() => cambiarPass(u.id)} className="!min-h-[42px] !px-4 !text-xs">Guardar contraseña</Btn>
                      <button onClick={() => { setPassId(null); setPassVal(''); }} className="text-xs text-gray-400 hover:text-gray-200 px-2">Cancelar</button>
                    </div>
                    <p className="text-[11px] text-gray-600 mt-2">{u.pass ? 'Este usuario ya tiene contraseña asignada.' : 'Este usuario aún no tiene contraseña.'}</p>
                  </td>
                </tr>
              )}
              {editId === u.id && (
                <tr className="bg-carbon/40 border-b border-white/5">
                  <td colSpan="5" className="px-4 py-4">
                    <p className="text-xs font-semibold text-gray-300 mb-2.5">Módulos asignados a <span className="text-gold">{u.nombre}</span> — el rol define los predeterminados, ajústalos a la medida:</p>
                    <div className="flex flex-wrap gap-2">
                      {ADMIN_MODULOS.map(([mid, mlabel]) => {
                        const on = (u.modulos || []).includes(mid);
                        const lock = u.rol === 'Administrador';
                        return (
                          <button key={mid} disabled={lock} onClick={() => toggleModulo(u.id, mid)}
                            className={`text-xs font-medium px-3 py-1.5 rounded-full border transition-colors ${on ? 'bg-gold/15 text-gold border-gold/40' : 'bg-carbon text-gray-500 border-white/10 hover:text-gray-300'} ${lock ? 'opacity-70 cursor-not-allowed' : ''}`}>
                            {on ? '✓ ' : ''}{mlabel}
                          </button>
                        );
                      })}
                    </div>
                    {u.rol === 'Administrador' && <p className="text-[11px] text-gray-500 mt-2">El Administrador siempre tiene acceso a todos los módulos.</p>}
                    {u.creado && <p className="text-[11px] text-gray-600 mt-2">Creado: {u.creado}</p>}
                  </td>
                </tr>
              )}
              </React.Fragment>
            ))}
          </tbody>
        </table>
        </div>
      </div>
      <p className="text-xs text-gray-500">{users.length} usuarios · {users.filter((u) => u.rol === 'Administrador').length} administradores · {users.filter((u) => u.rol === 'Encargado Local').length} encargados · {users.filter((u) => u.estado === 'pendiente').length} pendientes</p>
      {toast && <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-emerald-600 text-white text-sm px-5 py-3 rounded-lg shadow-xl max-w-md text-center">{toast}</div>}
    </div>
  );
}

Object.assign(window, { AdIcon, CalendarView, EditModal, Reportes, GaleriaAdmin, Usuarios, Correos, Visitas, Cotizaciones });

// ---------- Cotizaciones B2B (solicitudes de convenio) ----------
function Cotizaciones({ cotizaciones, setCotizaciones }) {
  const [filtro, setFiltro] = useState('todas');
  const [query, setQuery] = useState('');
  const [toast, setToast] = useState('');
  const flash = (m) => { setToast(m); setTimeout(() => setToast(''), 2400); };
  const lista = (cotizaciones || []).filter((c) => {
    if (filtro === 'todas') { if (c.estado === 'archivada') return false; }
    else if (c.estado !== filtro) return false;
    const q = query.trim().toLowerCase();
    if (q && !(`${c.empresa} ${c.contacto} ${c.correo} ${c.telefono} ${c.id} ${c.rut || ''}`.toLowerCase().includes(q))) return false;
    return true;
  });

  const setEstado = (id, estado) => setCotizaciones((p) => p.map((c) => c.id === id ? { ...c, estado } : c));
  const eliminar = (id) => { if (confirm('¿Archivar esta cotización? Se conserva el registro y puede restaurarse desde el filtro «Archivadas».')) setEstado(id, 'archivada'); };

  const waLink = (c) => {
    const t = `Hola ${c.contacto}, gracias por su interés en RIVAMAR Group. Sobre su cotización ${c.id} para ${c.empresa} (${c.pax} pax):`;
    return 'https://wa.me/' + (c.telefono || '').replace(/[^0-9]/g, '') + '?text=' + encodeURIComponent(t);
  };
  const estadoBadge = (e) => {
    const m = { nueva: 'bg-gold/15 text-gold', contactada: 'bg-sky-500/15 text-sky-300', cerrada: 'bg-emerald-500/15 text-emerald-400', archivada: 'bg-gray-500/15 text-gray-400' };
    return m[e] || m.nueva;
  };

  const site = (typeof window !== 'undefined' && window.SITE) || {};
  const exportCSV = () => {
    const headers = ['id', 'empresa', 'rut', 'contacto', 'correo', 'telefono', 'local', 'num_personas', 'colaboradores', 'fecha_evento', 'estado', 'mensaje'];
    const rows = lista.map((c) => [c.id, c.empresa, c.rut || '', c.contacto, c.correo, c.telefono, c.local || 'Indistinto', c.pax, c.colaboradores || '', c.fecha || '', c.estado, c.mensaje || '']);
    const csv = [headers.join(','), ...rows.map((r) => r.map((x) => `"${String(x ?? '').replace(/"/g, '""')}"`).join(','))].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = `cotizaciones_rivamar_${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
    flash(`CSV exportado · ${lista.length} cotizaciones`);
  };
  const generarPDF = (c) => {
    const localNom = c.local ? (LOCAL_MAP[c.local] ? LOCAL_MAP[c.local].nombre : c.local) : 'Indistinto';
    const fila = (k, v) => `<tr><td class="k">${k}</td><td class="v">${v}</td></tr>`;
    const html = `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>Cotización ${c.id}</title>
      <style>@media print{@page{margin:16mm}}body{font-family:Arial,Helvetica,sans-serif;color:#1C1611;margin:0;padding:34px}
      .brand{display:flex;align-items:center;gap:12px;border-bottom:3px solid #B5552E;padding-bottom:16px}
      .logo{width:40px;height:40px;background:#B5552E;color:#fff;font-weight:800;display:grid;place-items:center;border-radius:5px;font-size:22px;font-family:Georgia,serif}
      h1{font-size:20px;margin:0}.sub{color:#8A7558;font-size:12px;margin:2px 0 0}
      .tag{display:inline-block;margin:18px 0 8px;padding:6px 14px;border-radius:99px;font-size:13px;font-weight:700;background:#FEF3C7;color:#B45309}
      table{width:100%;border-collapse:collapse;margin-top:8px;font-size:14px}td{border-bottom:1px solid #EADFce;padding:10px 4px}.k{color:#8A7558;width:38%}.v{color:#1C1611;font-weight:600}
      .foot{margin-top:28px;border-top:1px solid #EADFce;padding-top:12px;color:#A08D72;font-size:11px;text-align:center}</style></head><body>
      <div class="brand"><div class="logo">R</div><div><h1>${(site.brand_nombre || 'RIVAMAR')} ${(site.brand_sub || 'GROUP')}</h1><p class="sub">Cotización Convenios B2B · Antofagasta, Chile</p></div></div>
      <div class="tag">Cotización ${c.estado}</div>
      <table>${fila('Código', c.id)}${fila('Empresa', c.empresa)}${c.rut ? fila('RUT', c.rut) : ''}${fila('Contacto', c.contacto)}${fila('Correo', c.correo)}${fila('Teléfono', c.telefono)}${fila('Local', localNom)}${fila('N° de personas', c.pax + (c.colaboradores ? ' (' + c.colaboradores + ')' : ''))}${fila('Fecha del evento', c.fecha || 'Por definir')}${c.mensaje ? fila('Detalles', c.mensaje) : ''}</table>
      <p class="foot">${site.footer_copy || '© 2026 RIVAMAR Group — Antofagasta, Chile · MAEDY GROUP'}<br/>Documento generado desde el panel de administración.</p>
      <script>window.onload=function(){setTimeout(function(){window.print()},350)}<\/script></body></html>`;
    const w = window.open('', '_blank'); if (w) { w.document.write(html); w.document.close(); }
    flash('PDF generado · ' + c.id);
  };

  const total = (cotizaciones || []).filter((c) => c.estado !== 'archivada').length;
  const pillCls = (active) => `px-3 py-1.5 rounded-md text-xs font-medium transition-colors min-h-[36px] ${active ? 'bg-gold text-carbon' : 'bg-carbon border border-white/10 text-gray-400 hover:text-gray-100'}`;

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <MiniStat label="Total cotizaciones" value={total} accent="#C8A000" />
        <MiniStat label="Nuevas" value={(cotizaciones || []).filter((c) => c.estado === 'nueva').length} accent="#F5A623" />
        <MiniStat label="Contactadas" value={(cotizaciones || []).filter((c) => c.estado === 'contactada').length} accent="#3B82C4" />
        <MiniStat label="Cerradas" value={(cotizaciones || []).filter((c) => c.estado === 'cerrada').length} accent="#10B981" />
      </div>

      {/* Barra de herramientas (igual que Gestión de Reservas) */}
      <div className="bg-iron border border-white/10 rounded-xl p-4 flex flex-col lg:flex-row gap-3 lg:items-center justify-between">
        <div className="relative flex-1 max-w-sm">
          <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500"><AdIcon name="users" size={15} /></span>
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar por empresa, contacto, correo, ID…"
            className="w-full min-h-[40px] pl-9 pr-3 rounded-md bg-carbon border border-white/10 text-gray-100 text-sm placeholder-gray-600 focus:border-gold outline-none" />
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {[['todas', 'Activas'], ['nueva', 'Nuevas'], ['contactada', 'Contactadas'], ['cerrada', 'Cerradas'], ['archivada', 'Archivadas']].map(([id, l]) => (
            <button key={id} onClick={() => setFiltro(id)} className={pillCls(filtro === id)}>{l}</button>
          ))}
          <span className="w-px h-5 bg-white/10 mx-1"></span>
          <Btn variant="outline" onClick={exportCSV} className="!min-h-[36px] !px-3 !text-xs"><AdIcon name="chart" size={14} /> Exportar CSV</Btn>
        </div>
      </div>

      {lista.length === 0 ? (
        <div className="bg-iron border border-white/10 rounded-xl p-12 text-center text-gray-500 text-sm">
          No hay cotizaciones {filtro !== 'todas' ? 'en este estado' : 'todavía'}. Las solicitudes del formulario «Convenios B2B» aparecerán aquí.
        </div>
      ) : (
        <div className="space-y-3">
          {lista.map((c) => (
            <div key={c.id} className="bg-iron border border-white/10 rounded-xl p-5">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <div className="flex items-center gap-2.5 flex-wrap">
                    <span className="font-mono text-xs text-gray-500">{c.id}</span>
                    <h3 className="font-display font-bold text-gray-50">{c.empresa}</h3>
                    <span className={`text-[11px] font-semibold px-2 py-0.5 rounded-full ${estadoBadge(c.estado)}`}>{c.estado}</span>
                  </div>
                  <p className="text-sm text-gray-400 mt-1">{c.contacto} · {c.correo} · {c.telefono}</p>
                </div>
                <div className="flex gap-1.5">
                  <a href={waLink(c)} target="_blank" rel="noopener" title="Responder por WhatsApp" className="w-9 h-9 grid place-items-center rounded-md bg-[#25D366]/15 text-[#25D366] hover:bg-[#25D366]/25">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.6.2-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.2-1.2-.5-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.5-.8-2-.2-.5-.4-.5-.6-.5h-.5c-.2 0-.5.1-.7.3-.2.3-.9.9-.9 2.2s.9 2.5 1.1 2.7c.1.2 1.8 2.7 4.3 3.8.6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.7-.7 1.9-1.3.2-.7.2-1.2.2-1.3-.1-.2-.3-.2-.6-.4M12 2a10 10 0 0 0-8.6 15l-1.4 5.1 5.2-1.4A10 10 0 1 0 12 2"/></svg>
                  </a>
                  <a href={`mailto:${c.correo}?subject=${encodeURIComponent('Cotización ' + c.id + ' — RIVAMAR Group')}`} title="Responder por correo" className="w-9 h-9 grid place-items-center rounded-md bg-white/5 text-gray-400 hover:text-gold">
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                  </a>
                  <button onClick={() => generarPDF(c)} title="Descargar PDF" className="w-9 h-9 grid place-items-center rounded-md bg-white/5 text-gray-400 hover:text-gold">
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="12" y1="18" x2="12" y2="12"/><polyline points="9 15 12 18 15 15"/></svg>
                  </button>
                  {c.estado === 'archivada'
                    ? <button onClick={() => setEstado(c.id, 'nueva')} title="Restaurar" className="w-9 h-9 grid place-items-center rounded-md bg-emerald-500/15 text-emerald-400 hover:bg-emerald-500/25">↺</button>
                    : <button onClick={() => eliminar(c.id)} title="Archivar" className="w-9 h-9 grid place-items-center rounded-md bg-red-500/10 text-red-400 hover:bg-red-500/20"><AdIcon name="trash" size={14} /></button>}
                </div>
              </div>
              <div className="grid sm:grid-cols-4 gap-3 mt-4 text-sm">
                <div><span className="block text-[11px] text-gray-500 uppercase tracking-wider">N° personas</span><span className="text-gray-200">{c.pax} {c.colaboradores ? `(${c.colaboradores})` : ''}</span></div>
                <div><span className="block text-[11px] text-gray-500 uppercase tracking-wider">Local</span><span className="text-gray-200">{c.local ? (LOCAL_MAP[c.local] ? LOCAL_MAP[c.local].nombre : c.local) : 'Indistinto'}</span></div>
                <div><span className="block text-[11px] text-gray-500 uppercase tracking-wider">Fecha evento</span><span className="text-gray-200">{c.fecha || 'Por definir'}</span></div>
                <div><span className="block text-[11px] text-gray-500 uppercase tracking-wider">RUT</span><span className="text-gray-200">{c.rut || '—'}</span></div>
              </div>
              {c.mensaje && <p className="mt-3 text-sm text-gray-400 bg-carbon/50 rounded-lg p-3">{c.mensaje}</p>}
              <div className="flex flex-wrap gap-2 mt-4 pt-3 border-t border-white/5">
                <span className="text-[11px] text-gray-500 self-center mr-1">Marcar como:</span>
                {[['nueva', 'Nueva'], ['contactada', 'Contactada'], ['cerrada', 'Cerrada']].map(([e, l]) => (
                  <button key={e} onClick={() => { setEstado(c.id, e); flash('Cotización marcada como ' + l); }} className={`text-xs font-semibold px-2.5 py-1.5 rounded-md ${c.estado === e ? estadoBadge(e) : 'bg-white/5 text-gray-400 hover:text-gray-100'}`}>{l}</button>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
      {toast && <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-emerald-600 text-white text-sm px-5 py-3 rounded-lg shadow-xl">{toast}</div>}
    </div>
  );
}

// ---------- Visitas (analítica de tráfico con IP) ----------
function uaBrowser(ua) {
  ua = ua || '';
  if (/Edg/.test(ua)) return 'Edge';
  if (/Chrome/.test(ua)) return 'Chrome';
  if (/Firefox/.test(ua)) return 'Firefox';
  if (/Safari/.test(ua)) return 'Safari';
  return 'Otro';
}
function uaDevice(ua) {
  ua = ua || '';
  if (/iPhone|Android.*Mobile|Mobile/.test(ua)) return 'Móvil';
  if (/iPad|Tablet/.test(ua)) return 'Tablet';
  return 'Escritorio';
}
function refLabel(ref) {
  if (!ref) return 'Directo';
  try { return new URL(ref).hostname.replace('www.', ''); } catch (e) { return 'Directo'; }
}

function Visitas() {
  const [visits, setVisits] = useState(() => getVisits());
  const [toast, setToast] = useState('');
  const refresh = () => setVisits(getVisits());
  const flash = (m) => { setToast(m); setTimeout(() => setToast(''), 2200); };

  const todayStr = new Date().toISOString().slice(0, 10);
  const total = visits.length;
  const hoy = visits.filter((v) => v.ts.slice(0, 10) === todayStr).length;
  const ipsUnicas = new Set(visits.map((v) => v.ip).filter(Boolean)).size;
  const ultima = visits.length ? new Date(visits[visits.length - 1].ts) : null;

  // Serie últimos 7 días
  const dias = [];
  for (let i = 6; i >= 0; i--) {
    const d = new Date(Date.now() - i * 86400000);
    const key = d.toISOString().slice(0, 10);
    dias.push({ key, label: d.toLocaleDateString('es-CL', { weekday: 'short' }), n: visits.filter((v) => v.ts.slice(0, 10) === key).length });
  }
  const maxDia = Math.max(1, ...dias.map((d) => d.n));

  // Distribución por dispositivo
  const dispositivos = ['Móvil', 'Escritorio', 'Tablet'].map((dv) => ({ dv, n: visits.filter((v) => uaDevice(v.ua) === dv).length }));

  const recientes = visits.slice().reverse().slice(0, 25);

  const exportCSV = () => {
    const headers = ['fecha_hora', 'ip', 'dispositivo', 'navegador', 'origen'];
    const rows = visits.slice().reverse().map((v) => [v.ts, v.ip || '', uaDevice(v.ua), uaBrowser(v.ua), refLabel(v.ref)]);
    const csv = [headers.join(','), ...rows.map((r) => r.map((c) => `"${String(c ?? '').replace(/"/g, '""')}"`).join(','))].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = `visitas_rivamar_${todayStr}.csv`;
    document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
    flash(`CSV exportado · ${visits.length} visitas`);
  };

  const limpiar = () => {
    if (confirm('¿Borrar todo el registro de visitas? Esta acción no se puede deshacer.')) {
      clearVisits(); refresh(); flash('Registro de visitas borrado');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <p className="text-sm text-gray-400 max-w-xl">Registro de tráfico del sitio público. La IP se captura automáticamente al ingresar cada visitante.</p>
        <div className="flex gap-2">
          <Btn variant="ghost" onClick={refresh} className="!min-h-[38px] !px-3 !text-xs">↻ Actualizar</Btn>
          <Btn variant="outline" onClick={exportCSV} className="!min-h-[38px] !px-3 !text-xs"><AdIcon name="image" size={14} /> Exportar CSV</Btn>
          <Btn variant="ghost" onClick={limpiar} className="!min-h-[38px] !px-3 !text-xs !text-red-400"><AdIcon name="trash" size={13} /> Limpiar</Btn>
        </div>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <MiniStat label="Visitas totales" value={total} accent="#C8A000" />
        <MiniStat label="Visitas hoy" value={hoy} accent="#3B82C4" />
        <MiniStat label="IPs únicas" value={ipsUnicas} accent="#10B981" />
        <MiniStat label="Última visita" value={ultima ? ultima.toLocaleDateString('es-CL', { day: '2-digit', month: 'short' }) : '—'} accent="#B87333" />
      </div>

      <div className="grid lg:grid-cols-3 gap-4">
        <div className="lg:col-span-2 bg-iron border border-white/10 rounded-xl p-6">
          <h3 className="font-display font-bold text-gray-50 mb-5">Visitas — últimos 7 días</h3>
          <div className="flex items-end justify-between gap-3 h-44">
            {dias.map((d) => (
              <div key={d.key} className="flex-1 flex flex-col items-center gap-2">
                <span className="text-xs font-semibold text-gray-300">{d.n}</span>
                <div className="w-full rounded-t-md bg-gold/80 hover:bg-gold transition-colors" style={{ height: `${Math.max(4, (d.n / maxDia) * 140)}px` }}></div>
                <span className="text-[10px] uppercase text-gray-500">{d.label}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="bg-iron border border-white/10 rounded-xl p-6">
          <h3 className="font-display font-bold text-gray-50 mb-5">Por dispositivo</h3>
          <div className="space-y-4">
            {dispositivos.map((d) => (
              <div key={d.dv}>
                <div className="flex justify-between text-sm mb-1.5"><span className="text-gray-300">{d.dv}</span><span className="text-gray-400">{d.n}</span></div>
                <div className="h-2.5 rounded-full bg-carbon overflow-hidden"><div className="h-full rounded-full bg-copper" style={{ width: `${(d.n / Math.max(1, total)) * 100}%` }}></div></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="bg-iron border border-white/10 rounded-xl overflow-hidden">
        <div className="p-4 border-b border-white/10"><h3 className="font-display font-bold text-gray-50">Visitas recientes</h3></div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-gray-500 border-b border-white/10">
                <th className="px-4 py-3 font-semibold">Fecha y hora</th>
                <th className="px-4 py-3 font-semibold">Dirección IP</th>
                <th className="px-4 py-3 font-semibold">Dispositivo</th>
                <th className="px-4 py-3 font-semibold">Navegador</th>
                <th className="px-4 py-3 font-semibold">Origen</th>
              </tr>
            </thead>
            <tbody>
              {recientes.map((v, i) => (
                <tr key={v.id || i} className="border-b border-white/5 hover:bg-white/[0.02]">
                  <td className="px-4 py-3 text-gray-300 whitespace-nowrap">{new Date(v.ts).toLocaleString('es-CL', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}</td>
                  <td className="px-4 py-3 font-mono text-xs text-gold">{v.ip || <span className="text-gray-600">capturando…</span>}</td>
                  <td className="px-4 py-3 text-gray-400">{uaDevice(v.ua)}</td>
                  <td className="px-4 py-3 text-gray-400">{uaBrowser(v.ua)}</td>
                  <td className="px-4 py-3 text-gray-400">{refLabel(v.ref)}</td>
                </tr>
              ))}
              {recientes.length === 0 && <tr><td colSpan="5" className="px-4 py-12 text-center text-gray-500">Aún no hay visitas registradas.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
      <p className="text-xs text-gray-500 font-mono">Nota: en el sitio publicado, la IP se obtiene automáticamente. En la vista previa local puede aparecer “capturando…” si el navegador bloquea la consulta.</p>
      {toast && <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-emerald-600 text-white text-sm px-5 py-3 rounded-lg shadow-xl">{toast}</div>}
    </div>
  );
}

// ---------- Correos branded (Sec. 6.6) ----------
function EmailFrame({ children }) {
  return (
    <div className="rounded-xl overflow-hidden border border-white/10 shadow-2xl" style={{ background: '#111827' }}>
      {children}
    </div>
  );
}

function Correos({ reservas = [], cotizaciones = [], setReservas }) {
  const [tab, setTab] = useState('pendientes');
  const demo = SEED_RESERVAS[0];
  const localNom = LOCAL_MAP[demo.local].nombre;
  const site = (typeof window !== 'undefined' && window.SITE) || {};
  const pendientes = (reservas || []).filter((r) => r.estado === 'pendiente');
  const cotPend = (cotizaciones || []).filter((c) => c.estado === 'nueva');

  const tabBtn = (id, label, badge) => (
    <button onClick={() => setTab(id)}
      className={`relative px-4 py-2 rounded-lg text-sm font-medium ${tab === id ? 'bg-gold text-carbon' : 'bg-iron border border-white/10 text-gray-300 hover:text-gray-50'}`}>{label}
      {badge > 0 && <span className="ml-1.5 inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-red-500 text-white text-[10px] font-bold align-middle">{badge}</span>}
    </button>
  );
  const confirmar = (r) => { setReservas && setReservas((p) => p.map((x) => x.id === r.id ? { ...x, estado: 'confirmada' } : x)); };
  const waConfirm = (r) => {
    const nom = LOCAL_MAP[r.local] ? LOCAL_MAP[r.local].nombre : r.local;
    const msg = `¡Hola ${r.nombre}! Tu reserva ${r.id} en ${(site.brand_nombre || 'RIVAMAR')} — ${nom} para el ${r.fecha} a las ${r.hora} hrs (${r.pax} pax) está CONFIRMADA ✅. ¡Te esperamos!`;
    const tel = (r.telefono || '').replace(/[^0-9]/g, ''); const num = tel.startsWith('56') ? tel : ('56' + tel);
    window.open(`https://wa.me/${num}?text=${encodeURIComponent(msg)}`, '_blank');
  };

  // Estilos inline (como en un correo real)
  const wrap = { maxWidth: 560, margin: '0 auto', fontFamily: 'Inter, Arial, sans-serif' };
  const head = { background: '#1A2A3A', padding: '24px', textAlign: 'center', borderBottom: '3px solid #C8A000' };
  const body = { padding: '28px 28px 8px', color: '#E5E7EB' };
  const card = { background: '#1F2937', borderRadius: 10, padding: 18, margin: '18px 0', border: '1px solid rgba(255,255,255,0.08)' };
  const row = { display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 14, borderBottom: '1px solid rgba(255,255,255,0.05)' };
  const cta = { display: 'inline-block', background: '#C8A000', color: '#111827', fontWeight: 700, padding: '12px 26px', borderRadius: 8, textDecoration: 'none', fontSize: 14 };
  const foot = { padding: '18px 28px', color: '#6B7280', fontSize: 11, textAlign: 'center', borderTop: '1px solid rgba(255,255,255,0.06)' };
  const logo = { width: 40, height: 40, background: '#C8A000', color: '#111827', fontWeight: 800, display: 'inline-grid', placeItems: 'center', borderRadius: 5, fontSize: 22, fontFamily: 'Georgia, serif' };

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div className="flex gap-2 flex-wrap">{tabBtn('pendientes', 'Pendientes de confirmación', pendientes.length + cotPend.length)}{tabBtn('cliente', '✉ Confirmación al cliente')}{tabBtn('admin', '🔔 Aviso al administrador')}</div>
        <span className="text-xs text-gray-500 font-mono">Notificaciones · identidad RIVAMAR</span>
      </div>

      {tab === 'pendientes' && (
        <div className="space-y-4">
          <p className="text-sm text-gray-400">Solicitudes recibidas (desde cualquier dispositivo) que esperan tu confirmación.</p>
          <div className="bg-iron border border-white/10 rounded-xl overflow-hidden">
            <div className="px-4 py-3 border-b border-white/10 flex items-center justify-between">
              <h3 className="font-display font-bold text-gray-50 text-sm">Reservas pendientes</h3>
              <span className="text-xs text-gray-500">{pendientes.length} pendiente(s)</span>
            </div>
            {pendientes.length === 0 ? (
              <p className="px-4 py-8 text-center text-sm text-gray-500">No hay reservas pendientes. ✓</p>
            ) : (
              <div className="divide-y divide-white/5">
                {pendientes.map((r) => (
                  <div key={r.id} className="px-4 py-3 flex flex-wrap items-center gap-3 justify-between">
                    <div className="min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="font-mono text-xs text-gray-500">{r.id}</span>
                        <span className="font-medium text-gray-100">{r.nombre}</span>
                        {r.exponor && <span className="text-exponor text-xs font-bold">★ −15%</span>}
                      </div>
                      <p className="text-xs text-gray-500">{LOCAL_MAP[r.local] ? LOCAL_MAP[r.local].nombre : r.local} · {r.fecha} {r.hora} · {r.pax} pax · {r.telefono}</p>
                    </div>
                    <div className="flex gap-2 shrink-0">
                      <button onClick={() => waConfirm(r)} title="Confirmar por WhatsApp" className="inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1.5 rounded-md bg-[#25D366]/15 text-[#25D366] hover:bg-[#25D366]/25">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.6.2-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.2-1.2-.5-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.5-.8-2-.2-.5-.4-.5-.6-.5h-.5c-.2 0-.5.1-.7.3-.2.3-.9.9-.9 2.2s.9 2.5 1.1 2.7c.1.2 1.8 2.7 4.3 3.8.6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.7-.7 1.9-1.3.2-.7.2-1.2.2-1.3-.1-.2-.3-.2-.6-.4M12 2a10 10 0 0 0-8.6 15l-1.4 5.1 5.2-1.4A10 10 0 1 0 12 2"/></svg>
                        WhatsApp
                      </button>
                      <button onClick={() => confirmar(r)} className="text-xs font-semibold px-2.5 py-1.5 rounded-md bg-emerald-500/15 text-emerald-400 hover:bg-emerald-500/25">✓ Confirmar</button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
          {cotPend.length > 0 && (
            <div className="bg-iron border border-white/10 rounded-xl overflow-hidden">
              <div className="px-4 py-3 border-b border-white/10"><h3 className="font-display font-bold text-gray-50 text-sm">Cotizaciones B2B nuevas ({cotPend.length})</h3></div>
              <div className="divide-y divide-white/5">
                {cotPend.map((c) => (
                  <div key={c.id} className="px-4 py-3 flex items-center justify-between gap-3">
                    <div><span className="font-medium text-gray-100">{c.empresa}</span> <span className="text-xs text-gray-500">· {c.contacto} · {c.pax} pax</span></div>
                    <span className="text-xs text-gold font-mono">{c.id}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      <p className="text-sm text-gray-400 max-w-2xl" style={{ display: tab === 'pendientes' ? 'none' : 'block' }}>
        Plantillas HTML branded que se envían automáticamente al confirmar una reserva (Sec. 6.6). Vista previa con datos de ejemplo
        de la reserva <span className="font-mono text-gold">{demo.id}</span>.
      </p>

      {tab === 'cliente' && (
        <EmailFrame>
          <div style={wrap}>
            <div style={head}><span style={logo}>R</span><div style={{ color: '#fff', fontWeight: 700, marginTop: 10, fontSize: 18 }}>RIVAMAR Group</div></div>
            <div style={body}>
              <h2 style={{ color: '#fff', fontSize: 20, margin: '4px 0 6px' }}>¡Reserva recibida, {demo.nombre.split(' ')[0]}!</h2>
              <p style={{ color: '#9CA3AF', fontSize: 14, lineHeight: 1.6 }}>
                Gracias por reservar en {localNom}. Tu solicitud quedó registrada en estado
                <span style={{ color: '#F97316', fontWeight: 600 }}> Pendiente</span> y será confirmada dentro de las próximas 24 horas.
              </p>
              <div style={card}>
                <div style={row}><span style={{ color: '#6B7280' }}>Código</span><span style={{ color: '#C8A000', fontWeight: 700 }}>{demo.id}</span></div>
                <div style={row}><span style={{ color: '#6B7280' }}>Local</span><span style={{ color: '#E5E7EB' }}>{localNom}</span></div>
                <div style={row}><span style={{ color: '#6B7280' }}>Fecha y hora</span><span style={{ color: '#E5E7EB' }}>{demo.fecha} · {demo.hora} hrs</span></div>
                <div style={{ ...row, borderBottom: 'none' }}><span style={{ color: '#6B7280' }}>Personas</span><span style={{ color: '#E5E7EB' }}>{demo.pax} pax</span></div>
              </div>
              {demo.exponor && (
                <div style={{ background: 'rgba(245,166,35,0.12)', border: '1px solid rgba(245,166,35,0.4)', borderRadius: 8, padding: 12, fontSize: 13, color: '#F5A623', fontWeight: 600 }}>
                  ★ Beneficio EXPONOR 2026 aplicado — 15% de descuento. Recuerda presentar tu credencial al pedir la cuenta.
                </div>
              )}
              <div style={{ textAlign: 'center', margin: '22px 0' }}><a href="#" style={cta}>Ver mi reserva</a></div>
            </div>
            <div style={foot}>RIVAMAR Group — Antofagasta, Chile · MAEDY GROUP<br/>Recibiste este correo porque realizaste una reserva en rivamar.cl</div>
          </div>
        </EmailFrame>
      )}

      {tab === 'admin' && (
        <EmailFrame>
          <div style={wrap}>
            <div style={{ ...head, borderBottom: '3px solid #F5A623' }}><span style={logo}>R</span><div style={{ color: '#fff', fontWeight: 700, marginTop: 10, fontSize: 18 }}>Panel RIVAMAR · Nueva reserva</div></div>
            <div style={body}>
              <div style={{ display: 'inline-block', background: 'rgba(249,115,22,0.15)', color: '#F97316', fontSize: 12, fontWeight: 700, padding: '5px 12px', borderRadius: 99 }}>● Acción requerida — Pendiente</div>
              <h2 style={{ color: '#fff', fontSize: 19, margin: '14px 0 6px' }}>Nueva reserva de {demo.nombre}</h2>
              <p style={{ color: '#9CA3AF', fontSize: 14, lineHeight: 1.6 }}>Ingresó una nueva solicitud que requiere validación en el panel de administración.</p>
              <div style={card}>
                <div style={row}><span style={{ color: '#6B7280' }}>Cliente</span><span style={{ color: '#E5E7EB' }}>{demo.nombre}</span></div>
                <div style={row}><span style={{ color: '#6B7280' }}>Empresa</span><span style={{ color: '#E5E7EB' }}>{demo.empresa || 'Particular'}</span></div>
                <div style={row}><span style={{ color: '#6B7280' }}>Contacto</span><span style={{ color: '#E5E7EB' }}>{demo.correo}</span></div>
                <div style={row}><span style={{ color: '#6B7280' }}>Local</span><span style={{ color: '#E5E7EB' }}>{localNom}</span></div>
                <div style={row}><span style={{ color: '#6B7280' }}>Fecha</span><span style={{ color: '#E5E7EB' }}>{demo.fecha} · {demo.hora} · {demo.pax} pax</span></div>
                <div style={{ ...row, borderBottom: 'none' }}><span style={{ color: '#6B7280' }}>EXPONOR</span><span style={{ color: demo.exponor ? '#F5A623' : '#6B7280', fontWeight: 600 }}>{demo.exponor ? '★ Sí (−15%)' : 'No'}</span></div>
              </div>
              <div style={{ textAlign: 'center', margin: '22px 0' }}><a href="#" style={cta}>Abrir en el panel</a></div>
            </div>
            <div style={foot}>Notificación automática del sistema de reservas · RIVAMAR Group</div>
          </div>
        </EmailFrame>
      )}
    </div>
  );
}
