
// Budgets Module

function Budgets() {
  const [view, setView] = React.useState('list');
  const [selected, setSelected] = React.useState(null);
  const [budgets, setBudgets] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [toast, setToast] = React.useState(null);
  const [filter, setFilter]           = React.useState('all');
  const [periodType, setPeriodType]   = React.useState('todos');
  const [periodOffset, setPeriodOffset] = React.useState(0);
  const [addModal, setAddModal] = React.useState(false);
  const [editModal, setEditModal] = React.useState(false);
  const [delConfirm, setDelConfirm] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const emptyForm = { client_name: '', event_name: '', value: '', status: 'Em elaboração', issued_date: '' };
  const [form, setForm] = React.useState(emptyForm);
  const [editForm, setEditForm] = React.useState(emptyForm);
  const [items, setItems] = React.useState([{ description: '', qty: 1, unit_price: '', total: 0 }]);

  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };

  const updateItem = (i, field, val) => {
    setItems(prev => prev.map((item, idx) => {
      if (idx !== i) return item;
      const updated = { ...item, [field]: val };
      if (field === 'qty' || field === 'unit_price') {
        const qty = field === 'qty' ? parseFloat(val) || 0 : parseFloat(item.qty) || 0;
        const unit = field === 'unit_price' ? parseFloat(val) || 0 : parseFloat(item.unit_price) || 0;
        updated.total = qty * unit;
      }
      return updated;
    }));
  };

  const addItem = () => setItems(prev => [...prev, { description: '', qty: 1, unit_price: '', total: 0 }]);
  const removeItem = (i) => setItems(prev => prev.filter((_, idx) => idx !== i));

  const calcTotal = () => items.reduce((s, it) => s + (it.total || 0), 0);

  const nextCode = () => {
    if (budgets.length === 0) return '#001';
    const nums = budgets.map(b => parseInt((b.code || '#000').replace('#', '')) || 0);
    return '#' + String(Math.max(...nums) + 1).padStart(3, '0');
  };

  const handleCreate = async () => {
    if (!form.client_name.trim() || !form.event_name.trim()) {
      showToast('Preencha cliente e evento.', 'danger'); return;
    }
    setSaving(true);
    const code = nextCode();
    const today = new Date();
    const issued_date = form.issued_date || `${today.getDate().toString().padStart(2,'0')} ${['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'][today.getMonth()]} ${today.getFullYear()}`;
    const value = parseFloat(form.value) || calcTotal();

    const { data: budget, error } = await sb.from('budgets').insert({
      code,
      client_name: form.client_name,
      event_name: form.event_name,
      issued_date,
      value,
      status: form.status,
      items_count: items.filter(it => it.description.trim()).length,
    }).select().single();

    if (error) { showToast('Erro ao criar orçamento.', 'danger'); setSaving(false); return; }

    const validItems = items.filter(it => it.description.trim());
    if (validItems.length > 0) {
      await sb.from('budget_items').insert(validItems.map(it => ({
        budget_id: budget.id,
        description: it.description,
        qty: parseFloat(it.qty) || 1,
        unit_price: parseFloat(it.unit_price) || 0,
        total: it.total || 0,
      })));
    }

    setBudgets(prev => [budget, ...prev]);
    setAddModal(false);
    setForm(emptyForm);
    setItems([{ description: '', qty: 1, unit_price: '', total: 0 }]);
    setSaving(false);
    showToast(`Orçamento ${code} criado com sucesso!`);
  };

  React.useEffect(() => {
    sb.from('budgets').select('*').order('created_at', { ascending: false }).then(({ data }) => {
      if (data) setBudgets(data);
      setLoading(false);
    });
  }, []);

  const statusVariant = { 'Enviado': 'primary', 'Aprovado': 'success', 'Em elaboração': 'warning', 'Recusado': 'danger' };

  // ── Período ──────────────────────────────────────────────
  const getRange = (type, offset) => {
    const now = new Date();
    if (type === 'todos') return { start: new Date(2000,0,1), end: new Date(2099,11,31), label: 'Todo o período' };
    let start, end, label;
    if (type === 'diario') {
      const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() + offset);
      start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0,0,0);
      end   = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23,59,59);
      label = d.toLocaleDateString('pt-BR', { weekday:'long', day:'numeric', month:'long', year:'numeric' });
      label = label.charAt(0).toUpperCase() + label.slice(1);
    } else if (type === 'semanal') {
      const d = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      d.setDate(d.getDate() - d.getDay() + offset * 7);
      start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0,0,0);
      end   = new Date(d.getFullYear(), d.getMonth(), d.getDate()+6, 23,59,59);
      const fmt = { day:'numeric', month:'short' };
      label = `${start.toLocaleDateString('pt-BR', fmt)} – ${end.toLocaleDateString('pt-BR', { ...fmt, year:'numeric' })}`;
    } else {
      const d = new Date(now.getFullYear(), now.getMonth() + offset, 1);
      start = new Date(d.getFullYear(), d.getMonth(), 1, 0,0,0);
      end   = new Date(d.getFullYear(), d.getMonth()+1, 0, 23,59,59);
      label = d.toLocaleDateString('pt-BR', { month:'long', year:'numeric' });
      label = label.charAt(0).toUpperCase() + label.slice(1);
    }
    return { start, end, label };
  };
  const { start: rangeStart, end: rangeEnd, label: rangeLabel } = getRange(periodType, periodOffset);
  const inRange = (d) => d && d >= rangeStart && d <= rangeEnd;

  const byStatus   = filter === 'all' ? budgets : budgets.filter(b => b.status === filter);
  const filtered   = byStatus.filter(b => {
    if (periodType === 'todos') return true;
    const d = b.created_at ? new Date(b.created_at) : null;
    return inRange(d);
  });

  const fmtCurrency = v => 'R$ ' + (v || 0).toLocaleString('pt-BR');

  const total     = filtered.reduce((s, b) => s + (b.value || 0), 0);
  const aprovados = filtered.filter(b => b.status === 'Aprovado').reduce((s, b) => s + (b.value || 0), 0);
  const pendentes = filtered.filter(b => b.status !== 'Aprovado' && b.status !== 'Recusado').reduce((s, b) => s + (b.value || 0), 0);
  const recusados = filtered.filter(b => b.status === 'Recusado').reduce((s, b) => s + (b.value || 0), 0);

  const [budgetItems, setBudgetItems] = React.useState([]);
  const [loadingItems, setLoadingItems] = React.useState(false);

  React.useEffect(() => {
    if (!selected) return;
    setLoadingItems(true);
    setBudgetItems([]);
    sb.from('budget_items').select('*').eq('budget_id', selected.id).then(({ data }) => {
      setBudgetItems(data || []);
      setLoadingItems(false);
    });
  }, [selected?.id]);

  const openEdit = () => {
    setEditForm({ client_name: selected.client_name || '', event_name: selected.event_name || '', status: selected.status || 'Em elaboração', issued_date: selected.issued_date || '' });
    setEditModal(true);
  };

  const handleEditSave = async () => {
    if (!editForm.client_name.trim() || !editForm.event_name.trim()) { showToast('Preencha cliente e evento.', 'danger'); return; }
    setSaving(true);
    const { data, error } = await sb.from('budgets').update({
      client_name: editForm.client_name, event_name: editForm.event_name,
      status: editForm.status, issued_date: editForm.issued_date,
    }).eq('id', selected.id).select().single();
    setSaving(false);
    if (error) { showToast('Erro ao salvar.', 'danger'); return; }
    setBudgets(prev => prev.map(b => b.id === data.id ? data : b));
    setSelected(data);
    setEditModal(false);
    showToast('Orçamento atualizado!');
  };

  const handleDelete = async () => {
    const id = selected.id;
    const code = selected.code;
    await sb.from('budget_items').delete().eq('budget_id', id);
    await sb.from('budgets').delete().eq('id', id);
    setBudgets(prev => prev.filter(b => b.id !== id));
    setDelConfirm(false);
    setSelected(null);
    setView('list');
    showToast(`Orçamento ${code} excluído.`);
  };

  const exportPDF = () => {
    const b = selected;
    const total = budgetItems.reduce((s, i) => s + (parseFloat(i.total) || 0), 0);
    const fmt = v => 'R$ ' + (parseFloat(v) || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    const OG = '#C8621A'; // laranja Promoup

    const itemRows = budgetItems.length === 0
      ? `<tr><td colspan="5" style="padding:20px;text-align:center;color:#94A3B8;font-style:italic">Nenhum item cadastrado</td></tr>`
      : budgetItems.map((it, i) => `
          <tr style="background:${i % 2 === 0 ? '#fff' : '#FBF7F4'}">
            <td style="padding:10px 12px;font-size:12px;color:#1E293B;border-bottom:1px solid #E2E8F0;vertical-align:top"><strong>${it.description}</strong></td>
            <td style="padding:10px 12px;font-size:12px;color:#64748B;text-align:center;border-bottom:1px solid #E2E8F0">un.</td>
            <td style="padding:10px 12px;font-size:12px;color:#64748B;text-align:right;border-bottom:1px solid #E2E8F0">${fmt(it.unit_price)}</td>
            <td style="padding:10px 12px;font-size:12px;color:#64748B;text-align:center;border-bottom:1px solid #E2E8F0">${it.qty}</td>
            <td style="padding:10px 12px;font-size:12px;font-weight:700;color:#1E293B;text-align:right;border-bottom:1px solid #E2E8F0">${fmt(it.total)}</td>
          </tr>`).join('');

    const html = `<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8"/>
  <title>Proposta ${b.code} — ${b.client_name}</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>
  <style>
    *{box-sizing:border-box;margin:0;padding:0}
    body{font-family:'Inter',sans-serif;background:#fff;color:#1E293B;-webkit-print-color-adjust:exact;print-color-adjust:exact;font-size:12px}
    @page{size:A4;margin:14mm 16mm}
    @media print{body{padding:0}}
    .sec-title{font-size:14px;font-weight:700;color:${OG};border-bottom:2px solid ${OG};padding-bottom:6px;margin:24px 0 14px}
    table{border-collapse:collapse;width:100%}
    th{background:#F1F5F9;font-size:10px;font-weight:700;color:#64748B;text-transform:uppercase;letter-spacing:0.06em;padding:8px 12px}
  </style>
</head>
<body style="padding:28px 36px;max-width:820px;margin:0 auto">

  <!-- ═══ CABEÇALHO ═══ -->
  <table style="margin-bottom:6px"><tr>
    <td style="vertical-align:top;width:55%">
      <div style="font-size:20px;font-weight:800;color:${OG};letter-spacing:-0.02em">Promoup Marketing E Eventos</div>
      <div style="font-size:10px;color:#64748B;margin-top:2px">PROMOUP MARKETING E EVENTOS LTDA</div>
      <div style="font-size:10px;color:#64748B">CNPJ: 61.643.567/0001-70</div>
      <div style="font-size:10px;color:#64748B">Rua Antonieta Clotilde, 615 — Jardim Iracema, Fortaleza-CE</div>
      <div style="font-size:10px;color:#64748B">CEP 60330-605</div>
    </td>
    <td style="vertical-align:top;text-align:right;font-size:10px;color:#64748B;line-height:1.8">
      <div>✉ silvana@promoupmarketing.com.br</div>
      <div>☎ +55 (85) 9998-0363</div>
      <div>📷 @promouoeventos &nbsp;|&nbsp; 🌐 promoup360.net</div>
      <div style="font-size:13px;font-weight:700;color:#1E293B;margin-top:6px">${b.issued_date || new Date().toLocaleDateString('pt-BR')}</div>
    </td>
  </tr></table>
  <div style="font-size:10px;color:#94A3B8;font-style:italic;margin-bottom:12px">"Experiências que conectam. Resultados que permanecem."</div>
  <div style="font-size:9px;color:#94A3B8;margin-bottom:16px;padding-bottom:12px;border-bottom:1px solid #E2E8F0">
    📷 @promouoeventos &nbsp;&nbsp; 🌐 promoup360.net
  </div>

  <!-- ═══ TÍTULO DA PROPOSTA ═══ -->
  <div style="background:${OG};color:#fff;padding:12px 20px;border-radius:6px;margin-bottom:20px">
    <div style="font-size:18px;font-weight:800">Proposta comercial ${b.code}</div>
  </div>

  <!-- ═══ CLIENTE ═══ -->
  <table style="margin-bottom:4px"><tr>
    <td style="vertical-align:top;width:55%;padding-right:24px">
      <div style="font-size:13px;font-weight:700;color:#1E293B;margin-bottom:4px">Cliente: ${b.client_name}</div>
    </td>
    <td style="vertical-align:top;font-size:10px;color:#64748B;line-height:1.8"></td>
  </tr></table>

  <!-- ═══ INFORMAÇÕES BÁSICAS ═══ -->
  <div class="sec-title">Informações básicas</div>
  <table style="margin-bottom:4px">
    <tr>
      <td style="padding:6px 0;width:25%;vertical-align:top">
        <div style="font-size:10px;font-weight:700;color:#1E293B">Prazo de entrega</div>
        <div style="font-size:11px;color:#64748B">Imediato</div>
      </td>
      <td style="padding:6px 0;width:25%;vertical-align:top">
        <div style="font-size:10px;font-weight:700;color:#1E293B">Tipo de evento</div>
        <div style="font-size:11px;color:#64748B">${b.event_name}</div>
      </td>
      <td style="padding:6px 0;width:25%;vertical-align:top">
        <div style="font-size:10px;font-weight:700;color:#1E293B">Local do evento</div>
        <div style="font-size:11px;color:#64748B">A confirmar</div>
      </td>
      <td style="padding:6px 0;width:25%;vertical-align:top">
        <div style="font-size:10px;font-weight:700;color:#1E293B">Status</div>
        <div style="font-size:11px;color:#64748B">${b.status}</div>
      </td>
    </tr>
  </table>

  <!-- ═══ SERVIÇOS ═══ -->
  <div class="sec-title">Serviços</div>
  <table>
    <thead>
      <tr>
        <th style="text-align:left">Descrição</th>
        <th>Unidade</th>
        <th style="text-align:right">Preço unitário</th>
        <th style="text-align:center">Qtd.</th>
        <th style="text-align:right">Preço</th>
      </tr>
    </thead>
    <tbody>${itemRows}</tbody>
    <tfoot>
      <tr style="background:${OG}">
        <td colspan="4" style="padding:10px 12px;font-size:12px;font-weight:700;color:#fff">Total</td>
        <td style="padding:10px 12px;font-size:13px;font-weight:800;color:#fff;text-align:right">${fmt(total)}</td>
      </tr>
    </tfoot>
  </table>

  <!-- ═══ PAGAMENTO ═══ -->
  <div class="sec-title">Pagamento</div>
  <table><tr>
    <td style="vertical-align:top;width:50%;padding-right:24px">
      <div style="font-size:10px;font-weight:700;color:#1E293B;margin-bottom:4px">Meios de pagamento</div>
      <div style="font-size:11px;color:#64748B">Boleto, transferência bancária ou pix.</div>
    </td>
    <td style="vertical-align:top">
      <div style="font-size:10px;font-weight:700;color:#1E293B;margin-bottom:4px">PIX</div>
      <div style="font-size:11px;color:#64748B">financeiro@promoupmarketing.com.br</div>
    </td>
  </tr></table>

  <!-- Dados bancários -->
  <div style="margin-top:16px;display:grid;grid-template-columns:1fr 1fr;gap:16px">
    <div>
      <div style="font-size:10px;font-weight:700;color:#1E293B;margin-bottom:6px">Dados bancários</div>
      <div style="font-size:11px;color:#64748B;line-height:1.8">
        Banco: Itaú<br/>Agência: 8144<br/>Conta: 98839-4<br/>Tipo de conta: Corrente<br/>Titular (CNPJ): 61.643.567/0001-70
      </div>
    </div>
    <div>
      <div style="font-size:10px;font-weight:700;color:#1E293B;margin-bottom:6px">Condições de pagamento</div>
      <div style="font-size:11px;color:#64748B">À vista.</div>
    </div>
  </div>

  <!-- ═══ CLÁUSULAS CONTRATUAIS ═══ -->
  <div class="sec-title">Cláusulas contratuais</div>
  <div style="font-size:10px;color:#1E293B;font-weight:600;margin-bottom:6px">Obrigações do Cliente</div>
  <div style="font-size:10px;color:#64748B;line-height:1.7;margin-bottom:10px">
    1.1. Fornecer todas as informações necessárias sobre o evento com pelo menos 30 dias de antecedência.<br/>
    1.2. Garantir o acesso ao local do evento para preparação, realização e desmontagem.<br/>
    1.3. Obter todas as autorizações e licenças necessárias para o local escolhido.<br/>
    1.4. Informar sobre restrições ou regulamentos específicos do local.<br/>
    1.5. Cooperar durante todas as fases de planejamento e execução.
  </div>
  <div style="font-size:10px;color:#1E293B;font-weight:600;margin-bottom:6px">Obrigações do Contratado</div>
  <div style="font-size:10px;color:#64748B;line-height:1.7;margin-bottom:10px">
    2.1. Planejar, organizar e executar o evento conforme especificações acordadas.<br/>
    2.2. Fornecer todos os materiais, equipamentos e pessoal necessários.<br/>
    2.3. Garantir que fornecedores cumpram padrões de qualidade e prazos.<br/>
    2.4. Manter o cliente informado sobre o progresso e quaisquer alterações.<br/>
    2.5. Assegurar que o local seja deixado em condições satisfatórias após o evento.
  </div>
  <div style="font-size:10px;color:#1E293B;font-weight:600;margin-bottom:6px">Regras de Rescisão</div>
  <div style="font-size:10px;color:#64748B;line-height:1.7;margin-bottom:10px">
    3.1. O cliente pode rescindir mediante notificação por escrito com 15 dias de antecedência.<br/>
    3.2. O Contratado pode rescindir se o cliente não cumprir suas obrigações (prazo de 7 dias para correção).<br/>
    3.3. Todas as despesas incorridas até a rescisão são de responsabilidade do cliente.<br/>
    3.4. A rescisão não afetará direitos ou obrigações acumulados até a data de rescisão.
  </div>
  <div style="font-size:10px;color:#1E293B;font-weight:600;margin-bottom:6px">Regras Gerais</div>
  <div style="font-size:10px;color:#64748B;line-height:1.7">
    4.1. Qualquer alteração deve ser feita por escrito e assinada por ambas as partes.<br/>
    4.2. Este contrato constitui o acordo completo entre as partes.<br/>
    4.3. Disposições inválidas não afetam as demais cláusulas.<br/>
    4.4. As partes concordam em cumprir todas as leis e regulamentos aplicáveis.
  </div>

  <!-- ═══ RODAPÉ COMPANY ═══ -->
  <div style="margin-top:24px;padding-top:12px;border-top:1px solid #E2E8F0;display:flex;justify-content:space-between;font-size:9px;color:#94A3B8">
    <div>PROMOUP MARKETING E EVENTOS LTDA — CNPJ: 61.643.567/0001-70<br/>Rua Antonieta Clotilde, 615 — Jardim Iracema, Fortaleza-CE — CEP 60330-605<br/>📷 @promouoeventos &nbsp; 🌐 promoup360.net</div>
    <div style="text-align:right">✉ silvana@promoupmarketing.com.br<br/>☎ +55 (85) 9998-0363<br/>📱 85999980363</div>
  </div>

  <!-- ═══ ASSINATURA ═══ -->
  <div style="margin-top:32px;text-align:center;font-size:11px;color:#64748B">
    <div style="font-style:italic;margin-bottom:20px">Agradecemos pela parceria e confiança na Promoup.</div>
    <div>Fortaleza, ${b.issued_date || new Date().toLocaleDateString('pt-BR')}</div>
    <div style="margin:24px auto;width:220px;border-top:1px solid #1E293B;padding-top:6px">
      <div style="font-weight:700;color:#1E293B">Promoup Marketing E Eventos</div>
      <div>Silvana Rocha</div>
    </div>
  </div>

  <script>window.onload=()=>{ window.print(); }<\/script>
</body>
</html>`;

    const win = window.open('', '_blank');
    win.document.write(html);
    win.document.close();
  };

  const updateStatus = async (newStatus) => {
    const { error } = await sb.from('budgets').update({ status: newStatus }).eq('id', selected.id);
    if (!error) {
      setBudgets(prev => prev.map(b => b.id === selected.id ? { ...b, status: newStatus } : b));
      setSelected(prev => ({ ...prev, status: newStatus }));
      showToast(`Orçamento marcado como ${newStatus}!`);
    }
  };

  if (view === 'detail' && selected) {
    const b = selected;
    const subtotal = budgetItems.reduce((s, i) => s + (i.total || 0), 0);
    const discount = subtotal * 0.05;
    const totalVal = subtotal - discount;

    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28 }}>
          <Btn variant="ghost" size="sm" icon="arrow" onClick={() => setView('list')} style={{ transform: 'rotate(180deg)' }}></Btn>
          <div>
            <h1 style={{ fontSize: 22, fontWeight: 700, color: DS.colors.text, margin: 0 }}>Orçamento {b.code}</h1>
            <p style={{ fontSize: 13, color: DS.colors.textSec, margin: 0 }}>{b.event_name} · {b.client_name}</p>
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <Btn variant="secondary" size="sm" icon="download" onClick={exportPDF} disabled={loadingItems}>Exportar PDF</Btn>
            <Btn variant="secondary" size="sm" icon="edit" onClick={openEdit}>Editar</Btn>
            <Btn variant="danger" size="sm" icon="x" onClick={() => setDelConfirm(true)}>Excluir</Btn>
            <Btn size="sm" icon="mail" onClick={() => showToast('Orçamento enviado por e-mail!')}>Enviar</Btn>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20 }}>
          <Card style={{ padding: 40 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 32 }}>
              <div>
                <div style={{ fontSize: 28, fontWeight: 800, color: DS.colors.primary, letterSpacing: '-0.03em' }}>EventFlow</div>
                <div style={{ fontSize: 12, color: DS.colors.textSec, marginTop: 2 }}>Gestão de Eventos Premium</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 22, fontWeight: 700, color: DS.colors.text }}>{b.code}</div>
                <div style={{ fontSize: 12, color: DS.colors.textSec }}>Emitido em {b.issued_date}</div>
                <div style={{ marginTop: 8 }}><Badge variant={statusVariant[b.status]}>{b.status}</Badge></div>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 32, padding: '20px 24px', background: '#F8FAFC', borderRadius: DS.radius.md }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>Cliente</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>{b.client_name}</div>
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>Evento</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>{b.event_name}</div>
              </div>
            </div>

            {loadingItems ? <Spinner size={24} /> : (
              <>
                <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 24 }}>
                  <thead>
                    <tr style={{ background: DS.colors.text }}>
                      {['Descrição', 'Qtd', 'Valor Unit.', 'Total'].map((h, i) => (
                        <th key={h} style={{ padding: '10px 16px', textAlign: i === 0 ? 'left' : 'right', fontSize: 11, fontWeight: 700, color: '#fff', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {budgetItems.length === 0 ? (
                      <tr><td colSpan={4} style={{ padding: '20px 16px', textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Nenhum item cadastrado</td></tr>
                    ) : budgetItems.map((item, i) => (
                      <tr key={item.id} style={{ background: i % 2 === 0 ? '#fff' : '#F8FAFC' }}>
                        <td style={{ padding: '12px 16px', fontSize: 13, color: DS.colors.text }}>{item.description}</td>
                        <td style={{ padding: '12px 16px', fontSize: 13, color: DS.colors.textSec, textAlign: 'right' }}>{item.qty}</td>
                        <td style={{ padding: '12px 16px', fontSize: 13, color: DS.colors.textSec, textAlign: 'right' }}>{fmtCurrency(item.unit_price)}</td>
                        <td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 600, color: DS.colors.text, textAlign: 'right' }}>{fmtCurrency(item.total)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {budgetItems.length > 0 && (
                  <div style={{ marginLeft: 'auto', width: 260 }}>
                    {[['Subtotal', subtotal], ['Desconto (5%)', -discount]].map(([label, val]) => (
                      <div key={label} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 13, color: DS.colors.textSec, borderBottom: `1px solid ${DS.colors.border}` }}>
                        <span>{label}</span><span style={{ color: val < 0 ? DS.colors.success : DS.colors.text }}>{val < 0 ? '-' : ''}{fmtCurrency(Math.abs(val))}</span>
                      </div>
                    ))}
                    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '14px 0 6px', fontSize: 18, fontWeight: 800, color: DS.colors.text }}>
                      <span>Total</span><span style={{ color: DS.colors.primary }}>{fmtCurrency(totalVal)}</span>
                    </div>
                  </div>
                )}
              </>
            )}

            <div style={{ marginTop: 32, padding: '16px 20px', background: DS.colors.primaryLight, borderRadius: DS.radius.sm, fontSize: 12, color: DS.colors.textSec, lineHeight: 1.6 }}>
              <strong style={{ color: DS.colors.primary }}>Validade:</strong> Este orçamento é válido por 15 dias a partir da data de emissão.
            </div>
          </Card>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Card style={{ padding: 20 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: DS.colors.textSec, marginBottom: 12, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Status</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {['Em elaboração', 'Enviado', 'Aprovado'].map((s, i) => {
                  const done = ['Em elaboração', 'Enviado', 'Aprovado', 'Recusado'].indexOf(b.status) >= i;
                  return (
                    <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{ width: 20, height: 20, borderRadius: '50%', background: done ? DS.colors.primary : '#E2E8F0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        {done && <Icon name="check" size={11} color="#fff" />}
                      </div>
                      <span style={{ fontSize: 13, color: done ? DS.colors.text : DS.colors.textMuted, fontWeight: done ? 600 : 400 }}>{s}</span>
                    </div>
                  );
                })}
              </div>
            </Card>
            <Card style={{ padding: 20 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: DS.colors.textSec, marginBottom: 12, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Ações</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <Btn style={{ justifyContent: 'center' }} icon="check" onClick={() => updateStatus('Aprovado')}>Marcar como aprovado</Btn>
                <Btn variant="secondary" style={{ justifyContent: 'center' }} icon="mail" onClick={() => updateStatus('Enviado')}>Marcar como enviado</Btn>
                <Btn variant="danger" style={{ justifyContent: 'center' }} icon="x" onClick={() => updateStatus('Recusado')}>Recusar</Btn>
              </div>
            </Card>
          </div>
        </div>
        {/* Modal editar orçamento */}
        <Modal open={editModal} onClose={() => setEditModal(false)} title={`Editar Orçamento ${selected?.code}`} width={500}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Input label="Cliente" value={editForm.client_name} onChange={v => setEditForm(f => ({ ...f, client_name: v }))} />
              <Input label="Evento" value={editForm.event_name} onChange={v => setEditForm(f => ({ ...f, event_name: v }))} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Select label="Status" value={editForm.status} onChange={v => setEditForm(f => ({ ...f, status: v }))} options={[
                { value: 'Em elaboração', label: 'Em elaboração' },
                { value: 'Enviado', label: 'Enviado' },
                { value: 'Aprovado', label: 'Aprovado' },
                { value: 'Recusado', label: 'Recusado' },
              ]} />
              <Input label="Data de emissão" value={editForm.issued_date} onChange={v => setEditForm(f => ({ ...f, issued_date: v }))} placeholder="Ex: 22 Abr 2026" />
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
              <Btn variant="secondary" onClick={() => setEditModal(false)}>Cancelar</Btn>
              <Btn onClick={handleEditSave} disabled={saving} icon="check">{saving ? 'Salvando…' : 'Salvar alterações'}</Btn>
            </div>
          </div>
        </Modal>

        {/* Confirmação exclusão */}
        <Modal open={delConfirm} onClose={() => setDelConfirm(false)} title="Excluir orçamento" width={400}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p style={{ fontSize: 14, color: DS.colors.textSec, lineHeight: 1.6 }}>Tem certeza que deseja excluir o orçamento <strong style={{ color: DS.colors.text }}>{selected?.code}</strong>? Todos os itens serão removidos permanentemente.</p>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <Btn variant="secondary" onClick={() => setDelConfirm(false)}>Cancelar</Btn>
              <Btn variant="danger" icon="x" onClick={handleDelete}>Excluir</Btn>
            </div>
          </div>
        </Modal>

        {toast && <Toast message={toast.msg} type={toast.type} onClose={() => setToast(null)} />}
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Orçamentos</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Gerencie propostas comerciais e acompanhe aprovações</p>
        </div>
        <Btn icon="plus" onClick={() => setAddModal(true)}>Novo orçamento</Btn>
      </div>

      {/* Seletor de período */}
      <Card style={{ padding: '12px 18px', marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 4, background: '#F1F5F9', borderRadius: DS.radius.sm, padding: 3 }}>
            {[{ id:'diario', label:'Diário' }, { id:'semanal', label:'Semanal' }, { id:'mensal', label:'Mensal' }, { id:'todos', label:'Todos' }].map(t => (
              <button key={t.id} onClick={() => { setPeriodType(t.id); setPeriodOffset(0); }}
                style={{ padding:'6px 14px', borderRadius: DS.radius.sm, border:'none', background: periodType===t.id ? DS.colors.primary : 'transparent', color: periodType===t.id ? '#fff' : DS.colors.textSec, fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit', transition:'all 0.15s' }}>
                {t.label}
              </button>
            ))}
          </div>

          {periodType !== 'todos' && (
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <button onClick={() => setPeriodOffset(o => o-1)}
                style={{ width:28, height:28, borderRadius: DS.radius.sm, border:`1px solid ${DS.colors.border}`, background:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="arrow" size={13} color={DS.colors.textSec} style={{ transform:'rotate(180deg)' }} />
              </button>
              <span style={{ fontSize:13, fontWeight:700, color:DS.colors.text, minWidth:210, textAlign:'center' }}>{rangeLabel}</span>
              <button onClick={() => setPeriodOffset(o => o+1)}
                style={{ width:28, height:28, borderRadius: DS.radius.sm, border:`1px solid ${DS.colors.border}`, background:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="arrow" size={13} color={DS.colors.textSec} />
              </button>
              {periodOffset !== 0 && (
                <button onClick={() => setPeriodOffset(0)}
                  style={{ padding:'4px 12px', borderRadius: DS.radius.sm, border:`1px solid ${DS.colors.border}`, background:'#fff', fontSize:11, fontWeight:700, color:DS.colors.textSec, cursor:'pointer', fontFamily:'inherit' }}>
                  Hoje
                </button>
              )}
            </div>
          )}

          <div style={{ marginLeft:'auto', fontSize:12, color:DS.colors.textMuted }}>
            <strong style={{ color:DS.colors.text }}>{filtered.length}</strong> orçamento{filtered.length!==1?'s':''}
          </div>
        </div>
      </Card>

      {/* Filtro por status */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 16, background: '#F1F5F9', padding: 4, borderRadius: DS.radius.sm, width: 'fit-content' }}>
        {[['all', 'Todos'], ['Em elaboração', 'Em elaboração'], ['Enviado', 'Enviados'], ['Aprovado', 'Aprovados'], ['Recusado', 'Recusados']].map(([val, label]) => (
          <button key={val} onClick={() => setFilter(val)} style={{
            padding: '6px 14px', borderRadius: '6px', border: 'none', fontSize: 12, fontWeight: 600, cursor: 'pointer', transition: 'all 0.15s',
            background: filter === val ? '#fff' : 'transparent',
            color: filter === val ? DS.colors.text : DS.colors.textSec,
            boxShadow: filter === val ? DS.shadow.sm : 'none',
          }}>{label}</button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
        {[
          { label: 'Total', value: fmtCurrency(total), color: DS.colors.primary },
          { label: 'Aprovados', value: fmtCurrency(aprovados), color: DS.colors.success },
          { label: 'Pendentes', value: fmtCurrency(pendentes), color: DS.colors.warning },
          { label: 'Recusados', value: fmtCurrency(recusados), color: DS.colors.danger },
        ].map(s => (
          <Card key={s.label} style={{ padding: '14px 18px' }}>
            <div style={{ fontSize: 11, color: DS.colors.textMuted, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.label}</div>
            <div style={{ fontSize: 20, fontWeight: 700, color: s.color, marginTop: 4 }}>{s.value}</div>
          </Card>
        ))}
      </div>

      <Card>
        {loading ? <Spinner /> : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '0.6fr 2fr 1.5fr 0.8fr 1fr 1fr 0.8fr', padding: '10px 24px', borderBottom: `1px solid ${DS.colors.border}`, fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
              <span>Nº</span><span>Evento</span><span>Cliente</span><span>Itens</span><span>Data</span><span>Status</span><span style={{ textAlign: 'right' }}>Valor</span>
            </div>
            {filtered.length === 0 ? <EmptyState icon="budget" title="Nenhum orçamento encontrado" /> : filtered.map((b, i) => (
              <div key={b.id}
                onClick={() => { setSelected(b); setView('detail'); }}
                style={{ display: 'grid', gridTemplateColumns: '0.6fr 2fr 1.5fr 0.8fr 1fr 1fr 0.8fr', padding: '14px 24px', borderBottom: i < filtered.length - 1 ? `1px solid ${DS.colors.border}` : 'none', alignItems: 'center', cursor: 'pointer', transition: 'background 0.1s' }}
                onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
              >
                <span style={{ fontSize: 13, fontWeight: 700, color: DS.colors.primary }}>{b.code}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{b.event_name}</span>
                <span style={{ fontSize: 13, color: DS.colors.textSec }}>{b.client_name}</span>
                <span style={{ fontSize: 13, color: DS.colors.textSec }}>{b.items_count} itens</span>
                <span style={{ fontSize: 13, color: DS.colors.textSec }}>{b.issued_date}</span>
                <span><Badge variant={statusVariant[b.status]}>{b.status}</Badge></span>
                <span style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, textAlign: 'right' }}>{fmtCurrency(b.value)}</span>
              </div>
            ))}
          </>
        )}
      </Card>
      {/* Modal novo orçamento */}
      <Modal open={addModal} onClose={() => { setAddModal(false); setForm(emptyForm); setItems([{ description: '', qty: 1, unit_price: '', total: 0 }]); }} title="Novo Orçamento" width={680}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* Dados principais */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Cliente" value={form.client_name} onChange={v => setForm(f => ({ ...f, client_name: v }))} placeholder="Ex: TechCorp Brasil" />
            <Input label="Evento" value={form.event_name} onChange={v => setForm(f => ({ ...f, event_name: v }))} placeholder="Ex: Congresso Tech 2027" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Status inicial" value={form.status} onChange={v => setForm(f => ({ ...f, status: v }))} options={[
              { value: 'Em elaboração', label: 'Em elaboração' },
              { value: 'Enviado',       label: 'Enviado' },
              { value: 'Aprovado',      label: 'Aprovado' },
            ]} />
            <Input label="Data de emissão (opcional)" value={form.issued_date} onChange={v => setForm(f => ({ ...f, issued_date: v }))} placeholder="Ex: 22 Abr 2026" />
          </div>

          <Divider style={{ margin: '4px 0' }} />

          {/* Itens do orçamento */}
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 10 }}>Itens do orçamento</div>

            {/* Header da tabela */}
            <div style={{ display: 'grid', gridTemplateColumns: '2.5fr 0.6fr 1fr 1fr 32px', gap: 8, marginBottom: 6 }}>
              {['Descrição', 'Qtd', 'Valor unit.', 'Total', ''].map((h, i) => (
                <div key={i} style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{h}</div>
              ))}
            </div>

            {/* Linhas */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {items.map((it, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '2.5fr 0.6fr 1fr 1fr 32px', gap: 8, alignItems: 'center' }}>
                  <input value={it.description} onChange={e => updateItem(i, 'description', e.target.value)} placeholder="Ex: Locação de espaço"
                    style={{ border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, padding: '8px 10px', fontSize: 13, outline: 'none', fontFamily: 'inherit', color: DS.colors.text }}
                    onFocus={e => e.target.style.borderColor = DS.colors.primary} onBlur={e => e.target.style.borderColor = DS.colors.border} />
                  <input type="number" value={it.qty} onChange={e => updateItem(i, 'qty', e.target.value)} min="1"
                    style={{ border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, padding: '8px 10px', fontSize: 13, outline: 'none', fontFamily: 'inherit', color: DS.colors.text, textAlign: 'center' }}
                    onFocus={e => e.target.style.borderColor = DS.colors.primary} onBlur={e => e.target.style.borderColor = DS.colors.border} />
                  <input type="number" value={it.unit_price} onChange={e => updateItem(i, 'unit_price', e.target.value)} placeholder="0"
                    style={{ border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, padding: '8px 10px', fontSize: 13, outline: 'none', fontFamily: 'inherit', color: DS.colors.text }}
                    onFocus={e => e.target.style.borderColor = DS.colors.primary} onBlur={e => e.target.style.borderColor = DS.colors.border} />
                  <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text, padding: '8px 10px', background: '#F8FAFC', borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}` }}>
                    {fmtCurrency(it.total)}
                  </div>
                  <button onClick={() => removeItem(i)} disabled={items.length === 1}
                    style={{ width: 28, height: 28, borderRadius: 6, border: 'none', background: items.length === 1 ? 'transparent' : '#FEF2F2', cursor: items.length === 1 ? 'default' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name="x" size={12} color={items.length === 1 ? DS.colors.border : DS.colors.danger} />
                  </button>
                </div>
              ))}
            </div>

            <button onClick={addItem} style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: `1px dashed ${DS.colors.border}`, borderRadius: DS.radius.sm, padding: '7px 14px', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: DS.colors.textSec, width: '100%', justifyContent: 'center' }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = DS.colors.primary; e.currentTarget.style.color = DS.colors.primary; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = DS.colors.border; e.currentTarget.style.color = DS.colors.textSec; }}>
              <Icon name="plus" size={13} color="currentColor" /> Adicionar item
            </button>
          </div>

          {/* Totalizador */}
          {calcTotal() > 0 && (
            <div style={{ background: '#F8FAFC', borderRadius: DS.radius.sm, padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 13, color: DS.colors.textSec, fontWeight: 600 }}>Total do orçamento</span>
              <span style={{ fontSize: 18, fontWeight: 800, color: DS.colors.primary }}>{fmtCurrency(calcTotal())}</span>
            </div>
          )}

          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <Btn variant="secondary" onClick={() => { setAddModal(false); setForm(emptyForm); setItems([{ description: '', qty: 1, unit_price: '', total: 0 }]); }}>Cancelar</Btn>
            <Btn onClick={handleCreate} disabled={saving} icon="budget">
              {saving ? 'Salvando…' : 'Criar orçamento'}
            </Btn>
          </div>
        </div>
      </Modal>

      {toast && <Toast message={toast.msg} type={toast.type} onClose={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { Budgets });
