/* ===========================================================
   Forja 3D — Gastos & Vendas
   =========================================================== */
const EXP_CATS = ['Filamento', 'Energia', 'Embalagem', 'Manutenção', 'Marketing', 'Equipamento', 'Impostos', 'Outro'];
const CHANNELS = ['Shopee', 'Mercado Livre', 'Elo7', 'Instagram', 'Encomenda', 'Venda direta', 'Outro'];

/* ---------------- GASTOS ---------------- */
function ExpenseForm({ onClose }) {
  const [e, setE] = useState({ date: today(), description: '', category: 'Filamento', amount: '' });
  const set = (k, v) => setE((p) => ({ ...p, [k]: v }));
  return (
    <>
      <Field label="Descrição"><Text value={e.description} onChange={(v) => set('description', v)} placeholder="Ex: Filamento PLA+ 1kg" /></Field>
      <div className="grid2">
        <Field label="Categoria"><Select value={e.category} onChange={(v) => set('category', v)} options={EXP_CATS.map((c) => ({ value: c, label: c }))} /></Field>
        <Field label="Valor"><Num value={e.amount} onChange={(v) => set('amount', v)} prefix="R$" /></Field>
      </div>
      <Field label="Data"><input type="date" className="inp" value={e.date} onChange={(ev) => set('date', ev.target.value)} /></Field>
      <div className="modal-f" style={{ margin: '8px -22px -22px', borderTop: '1px solid var(--line)' }}>
        <Button variant="ghost" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" icon="check" onClick={() => { if (e.description && e.amount) { store.addExpense({ ...e, amount: Number(e.amount) }); onClose(); } }}>Salvar gasto</Button>
      </div>
    </>
  );
}

function Expenses() {
  const s = useStore();
  const [modal, setModal] = useState(false);
  const [cat, setCat] = useState('Todas');
  const list = s.expenses.filter((e) => cat === 'Todas' || e.category === cat).sort((a, b) => (b.date > a.date ? 1 : -1));
  const total = list.reduce((a, e) => a + e.amount, 0);
  const totalMes = s.expenses.filter((e) => isThisMonth(e.date)).reduce((a, e) => a + e.amount, 0);

  return (
    <div className="page">
      <PageHead title="Gastos & Despesas" sub="Tudo que sai do caixa: filamento, energia, embalagem, manutenção, marketing…"
        action={<Button variant="primary" icon="plus" onClick={() => setModal(true)}>Novo gasto</Button>} />

      <div className="kpis" style={{ gridTemplateColumns: 'repeat(3,1fr)', marginBottom: 18 }}>
        <Kpi label="Gasto no mês" dot="r" value={fmt.brl0(totalMes)} />
        <Kpi label="Lançamentos" value={s.expenses.length} />
        <Kpi label="Total filtrado" value={fmt.brl0(total)} />
      </div>

      <div className="toolbar">
        <div className="seg" style={{ flexWrap: 'wrap' }}>
          {['Todas', ...EXP_CATS].map((c) => <button key={c} className={cat === c ? 'on' : ''} onClick={() => setCat(c)}>{c}</button>)}
        </div>
      </div>

      <div className="panel">
        {list.length === 0 ? <Empty icon="money" title="Nenhum gasto aqui" action={<Button variant="primary" icon="plus" onClick={() => setModal(true)}>Lançar gasto</Button>}>Registre suas despesas para acompanhar o caixa.</Empty> : (
          <table className="tbl">
            <thead><tr><th>Descrição</th><th className="hide-sm">Categoria</th><th className="hide-sm">Data</th><th className="r">Valor</th><th></th></tr></thead>
            <tbody>
              {list.map((e) => (
                <tr key={e.id}>
                  <td style={{ fontWeight: 600 }}>{e.description}<div className="hide-sm" style={{ display: 'none' }} /></td>
                  <td className="hide-sm"><Pill tone="n">{e.category}</Pill></td>
                  <td className="hide-sm mono muted">{fmt.dateFull(e.date)}</td>
                  <td className="r num" style={{ color: 'var(--red)', fontWeight: 700 }}>−{fmt.brl(e.amount)}</td>
                  <td className="r"><IconBtn icon="trash" danger onClick={() => store.removeExpense(e.id)} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title="Novo gasto">
        <ExpenseForm onClose={() => setModal(false)} />
      </Modal>
    </div>
  );
}
window.Expenses = Expenses;

/* ---------------- VENDAS ---------------- */
function SaleForm({ onClose, products }) {
  const [v, setV] = useState({ date: today(), product: '', channel: 'Shopee', qty: 1, price: '', cost: '' });
  const set = (k, val) => setV((p) => ({ ...p, [k]: val }));
  function pick(name) {
    const p = products.find((x) => x.name === name);
    setV((s) => ({ ...s, product: name, price: p ? p.price : s.price }));
  }
  const lucro = (Number(v.price) || 0 - 0) ? (Number(v.price) - Number(v.cost || 0)) * (Number(v.qty) || 1) : 0;
  return (
    <>
      <Field label="Produto" hint="Escolha do catálogo ou digite um novo">
        <input className="inp" list="prodlist" value={v.product} onChange={(e) => pick(e.target.value)} placeholder="Ex: Vaso geométrico G" />
        <datalist id="prodlist">{products.map((p) => <option key={p.id} value={p.name} />)}</datalist>
      </Field>
      <div className="grid2">
        <Field label="Canal"><Select value={v.channel} onChange={(val) => set('channel', val)} options={CHANNELS.map((c) => ({ value: c, label: c }))} /></Field>
        <Field label="Quantidade"><Num value={v.qty} onChange={(val) => set('qty', val)} /></Field>
      </div>
      <div className="grid2">
        <Field label="Preço de venda (un)"><Num value={v.price} onChange={(val) => set('price', val)} prefix="R$" /></Field>
        <Field label="Custo de produção (un)" hint="Use a calculadora"><Num value={v.cost} onChange={(val) => set('cost', val)} prefix="R$" /></Field>
      </div>
      <Field label="Data"><input type="date" className="inp" value={v.date} onChange={(e) => set('date', e.target.value)} /></Field>
      <div style={{ background: 'var(--panel-2)', borderRadius: 8, padding: '11px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Lucro estimado</span>
        <span className="mono" style={{ fontWeight: 700, color: 'var(--green)' }}>{fmt.brl(((Number(v.price) || 0) - (Number(v.cost) || 0)) * (Number(v.qty) || 1))}</span>
      </div>
      <div className="modal-f" style={{ margin: '18px -22px -22px', borderTop: '1px solid var(--line)' }}>
        <Button variant="ghost" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" icon="check" onClick={() => { if (v.product && v.price !== '') { store.addSale({ ...v, qty: Number(v.qty) || 1, price: Number(v.price), cost: Number(v.cost) || 0 }); onClose(); } }}>Registrar venda</Button>
      </div>
    </>
  );
}

function Sales() {
  const s = useStore();
  const [modal, setModal] = useState(false);
  const list = [...s.sales].sort((a, b) => (b.date > a.date ? 1 : -1));
  const mesList = s.sales.filter((x) => isThisMonth(x.date));
  const fatMes = mesList.reduce((a, x) => a + x.price * x.qty, 0);
  const lucroMes = mesList.reduce((a, x) => a + (x.price - x.cost) * x.qty, 0);

  return (
    <div className="page">
      <PageHead title="Vendas & Lucro" sub="Cada peça vendida, por canal — com lucro calculado automaticamente."
        action={<Button variant="primary" icon="plus" onClick={() => setModal(true)}>Registrar venda</Button>} />

      <div className="kpis" style={{ gridTemplateColumns: 'repeat(3,1fr)', marginBottom: 18 }}>
        <Kpi label="Faturamento no mês" value={fmt.brl0(fatMes)} />
        <Kpi label="Lucro no mês" dot="g" value={fmt.brl0(lucroMes)} />
        <Kpi label="Vendas registradas" value={s.sales.length} />
      </div>

      <div className="panel">
        {list.length === 0 ? <Empty icon="sale" title="Nenhuma venda registrada" action={<Button variant="primary" icon="plus" onClick={() => setModal(true)}>Registrar venda</Button>}>Comece a registrar suas vendas para acompanhar o lucro.</Empty> : (
          <table className="tbl">
            <thead><tr><th>Produto</th><th className="hide-sm">Canal</th><th className="hide-sm">Data</th><th className="r">Qtd</th><th className="r">Venda</th><th className="r hide-sm">Custo</th><th className="r">Lucro</th><th></th></tr></thead>
            <tbody>
              {list.map((v) => {
                const lucro = (v.price - v.cost) * v.qty;
                return (
                  <tr key={v.id}>
                    <td style={{ fontWeight: 600 }}>{v.product}</td>
                    <td className="hide-sm"><Pill tone="o">{v.channel}</Pill></td>
                    <td className="hide-sm mono muted">{fmt.dateFull(v.date)}</td>
                    <td className="r num">{v.qty}</td>
                    <td className="r num">{fmt.brl(v.price * v.qty)}</td>
                    <td className="r num muted hide-sm">{fmt.brl(v.cost * v.qty)}</td>
                    <td className="r num" style={{ color: 'var(--green)', fontWeight: 700 }}>+{fmt.brl(lucro)}</td>
                    <td className="r"><IconBtn icon="trash" danger onClick={() => store.removeSale(v.id)} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title="Registrar venda">
        <SaleForm products={s.products} onClose={() => setModal(false)} />
      </Modal>
    </div>
  );
}
window.Sales = Sales;
