// ─────────────────────────────────────────────────────────────────────────────
// Expense Entry Module — Formulario para cargar gastos manualmente
// Los gastos son el único dato que no se genera solo. El founder los ingresa aquí.
// Cuando haya Supabase: POST a tabla `expenses`
// ─────────────────────────────────────────────────────────────────────────────

const { useState: useS } = React;

const EXPENSE_CATS = [
  { id: 'infra',     label: 'Infraestructura',  color: DT.cyan },
  { id: 'pagos',     label: 'Pagos & finanzas', color: DT.accent },
  { id: 'legal',     label: 'Tiendas & legal',  color: DT.indigo },
  { id: 'equipo',    label: 'Equipo',           color: DT.amber },
  { id: 'marketing', label: 'Marketing',        color: DT.red },
];

const EXPENSE_TYPES = [
  { id: 'fijo', label: 'Fijo' },
  { id: 'uso',  label: 'Por uso' },
  { id: 'var',  label: 'Variable' },
];

const inputS = {
  background: DT.bg, border: `1px solid ${DT.border2}`, borderRadius: 9,
  padding: '11px 13px', color: '#fff', fontSize: 13, outline: 'none',
  width: '100%', boxSizing: 'border-box', fontFamily: 'Inter, sans-serif',
};
const labelS = { fontSize: 10, fontWeight: 600, color: DT.muted, marginBottom: 5, display: 'block', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em', textTransform: 'uppercase' };

const ExpenseEntryModal = ({ onClose, onSave }) => {
  const [form, setForm] = useS({ name: '', vendor: '', cat: 'infra', type: 'fijo', cost: '', note: '' });
  const [err, setErr] = useS('');
  const set = (k, v) => { setForm(p => ({ ...p, [k]: v })); setErr(''); };

  const save = () => {
    if (!form.name.trim()) return setErr('Ingresa el nombre del gasto');
    if (!form.cost || Number(form.cost) <= 0) return setErr('Ingresa un monto válido');
    onSave({ ...form, cost: Number(form.cost) });
    onClose();
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 460, background: DT.card, border: `1px solid ${DT.border2}`, borderRadius: 18, padding: 28, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 17, fontWeight: 800 }}>Nuevo gasto</div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: DT.muted, fontSize: 20, cursor: 'pointer' }}>✕</button>
        </div>

        <div>
          <label style={labelS}>Nombre del gasto *</label>
          <input value={form.name} onChange={e => set('name', e.target.value)} placeholder="Ej: Hosting & compute" style={inputS}/>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={labelS}>Proveedor</label>
            <input value={form.vendor} onChange={e => set('vendor', e.target.value)} placeholder="Ej: Supabase" style={inputS}/>
          </div>
          <div>
            <label style={labelS}>Monto mensual (CLP) *</label>
            <input value={form.cost} onChange={e => set('cost', e.target.value.replace(/\D/g, ''))} placeholder="38000" inputMode="numeric" style={{ ...inputS, fontFamily: 'JetBrains Mono, monospace' }}/>
          </div>
        </div>

        <div>
          <label style={labelS}>Categoría</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {EXPENSE_CATS.map(c => (
              <button key={c.id} onClick={() => set('cat', c.id)} style={{
                padding: '7px 12px', borderRadius: 8, fontSize: 11, fontWeight: 600,
                background: form.cat === c.id ? `${c.color}20` : 'transparent',
                color: form.cat === c.id ? c.color : DT.textSec,
                border: `1px solid ${form.cat === c.id ? `${c.color}50` : DT.border}`, cursor: 'pointer',
              }}>{c.label}</button>
            ))}
          </div>
        </div>

        <div>
          <label style={labelS}>Tipo</label>
          <div style={{ display: 'flex', gap: 6 }}>
            {EXPENSE_TYPES.map(t => (
              <button key={t.id} onClick={() => set('type', t.id)} style={{
                flex: 1, padding: '9px 0', borderRadius: 8, fontSize: 11, fontWeight: 600,
                background: form.type === t.id ? DT.accent : 'transparent',
                color: form.type === t.id ? '#000' : DT.textSec,
                border: `1px solid ${form.type === t.id ? DT.accent : DT.border}`, cursor: 'pointer',
              }}>{t.label}</button>
            ))}
          </div>
        </div>

        <div>
          <label style={labelS}>Nota</label>
          <input value={form.note} onChange={e => set('note', e.target.value)} placeholder="Ej: 8GB + backups + auth" style={inputS}/>
        </div>

        {err && <div style={{ fontSize: 12, color: DT.red, fontWeight: 500 }}>⚠ {err}</div>}

        <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
          <button onClick={onClose} style={{ flex: 1, padding: '12px 0', background: 'transparent', border: `1px solid ${DT.border2}`, borderRadius: 10, color: DT.textSec, fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Cancelar</button>
          <button onClick={save} style={{ flex: 2, padding: '12px 0', background: DT.accent, border: 'none', borderRadius: 10, color: '#000', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>Guardar gasto</button>
        </div>
      </div>
    </div>
  );
};

// Botón que se monta en PageGastos para abrir el modal
const AddExpenseButton = () => {
  const [open, setOpen] = useS(false);
  const [saved, setSaved] = useS([]);

  const handleSave = async (exp) => {
    setSaved(p => [...p, exp]);
    // Insert via cliente Supabase (respeta RLS — el admin debe estar autenticado).
    // Antes hacíamos fetch directo con anon key Bearer, lo que expone el token
    // y NO usa la sesión actual del admin → RLS no podía verificar identidad.
    if (!sb) return;
    try {
      const { error } = await sb.from('expenses').insert({
        nombre:    exp.name,
        proveedor: exp.vendor || null,
        categoria: exp.cat,
        tipo:      exp.type,
        monto_clp: exp.cost,
        nota:      exp.note || null,
      });
      if (error) console.warn('[expenses] insert falló:', error.message);
    } catch (e) {
      console.warn('[expenses] excepción:', e);
    }
  };

  return (
    <>
      {open && <ExpenseEntryModal onClose={() => setOpen(false)} onSave={handleSave}/>}
      <button onClick={() => setOpen(true)} style={{
        display: 'flex', alignItems: 'center', gap: 8,
        background: DT.accent, border: 'none', borderRadius: 9,
        padding: '9px 16px', fontSize: 12, fontWeight: 700, color: '#000', cursor: 'pointer',
      }}>
        <span style={{ fontSize: 15 }}>＋</span> Agregar gasto
        {saved.length > 0 && <span style={{ fontSize: 10, background: '#000', color: DT.accent, padding: '1px 6px', borderRadius: 10 }}>{saved.length}</span>}
      </button>
    </>
  );
};

Object.assign(window, { ExpenseEntryModal, AddExpenseButton });
