/* ===========================================================
   Forja 3D — Catálogo de produtos & Histórico de impressões
   =========================================================== */
function ProductForm({ initial, filaments, onSave, onClose }) {
  const [p, setP] = useState(initial || { name: '', filamentId: filaments[0]?.id || null, weightG: 50, printTimeMin: 180, price: '' });
  const set = (k, v) => setP((x) => ({ ...x, [k]: v }));
  const h = Math.floor((p.printTimeMin || 0) / 60), m = (p.printTimeMin || 0) % 60;
  return (
    <>
      <Field label="Nome do produto"><Text value={p.name} onChange={(v) => set('name', v)} placeholder="Ex: Vaso geométrico G" /></Field>
      <div className="grid2">
        <Field label="Filamento"><Select value={p.filamentId || ''} onChange={(v) => set('filamentId', v)} options={[{ value: '', label: '—' }, ...filaments.map((f) => ({ value: f.id, label: f.name }))]} /></Field>
        <Field label="Peso"><Num value={p.weightG} onChange={(v) => set('weightG', v)} suffix="g" /></Field>
      </div>
      <div className="grid2">
        <Field label="Tempo de impressão">
          <div style={{ display: 'flex', gap: 8 }}>
            <Num value={h} onChange={(v) => set('printTimeMin', (Number(v) || 0) * 60 + m)} suffix="h" />
            <Num value={m} onChange={(v) => set('printTimeMin', h * 60 + (Number(v) || 0))} suffix="min" />
          </div>
        </Field>
        <Field label="Preço de venda"><Num value={p.price} onChange={(v) => set('price', v)} prefix="R$" /></Field>
      </div>
      <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 (p.name) { const fil = filaments.find((f) => f.id === p.filamentId); onSave({ ...p, weightG: Number(p.weightG) || 0, price: Number(p.price) || 0, color: fil?.color || 'var(--orange)' }); onClose(); } }}>Salvar</Button>
      </div>
    </>
  );
}

function Catalog({ go }) {
  const s = useStore();
  const [modal, setModal] = useState(null);
  const st = s.settings;

  function costOf(p) {
    const fil = s.filaments.find((f) => f.id === p.filamentId);
    const c = computeCost({ grams: p.weightG, costPerKg: fil?.costPerKg || 100, printTimeMin: p.printTimeMin, packaging: st.defaultPackaging, margin: 0, failRate: st.failRate, marketplaceFee: 0, extraCost: 0 }, st);
    return c.withFail;
  }

  return (
    <div className="page">
      <PageHead title="Catálogo de Produtos" sub="Seus itens criados, com custo e margem calculados a partir do filamento e dos parâmetros da impressora."
        action={<Button variant="primary" icon="plus" onClick={() => setModal({ mode: 'add' })}>Novo produto</Button>} />

      {s.products.length === 0 ? <div className="panel"><Empty icon="box" title="Catálogo vazio" action={<Button variant="primary" icon="calc" onClick={() => go('calculadora')}>Ir para calculadora</Button>}>Crie produtos pela calculadora ou adicione manualmente.</Empty></div> : (
        <div className="grid-3c">
          {s.products.map((p) => {
            const fil = s.filaments.find((f) => f.id === p.filamentId);
            const cost = costOf(p);
            const lucro = p.price - cost;
            const margin = cost > 0 ? (lucro / cost) * 100 : 0;
            return (
              <div className="panel" key={p.id} style={{ overflow: 'hidden' }}>
                {/* thumb placeholder w/ filament color tint */}
                <div style={{ height: 96, background: `repeating-linear-gradient(135deg, ${p.color || 'var(--orange)'}22 0 10px, transparent 10px 20px), var(--panel-2)`, borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                  <span style={{ width: 30, height: 30, borderRadius: '50%', background: p.color || 'var(--orange)', border: '3px solid var(--line-2)' }} />
                  <span className="mono" style={{ position: 'absolute', bottom: 8, left: 10, fontSize: 9.5, color: 'var(--muted-2)', textTransform: 'uppercase', letterSpacing: 1 }}>foto do produto</span>
                </div>
                <div className="panel-pad" style={{ padding: 16 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                    <div style={{ fontWeight: 700, fontSize: 15 }}>{p.name}</div>
                    <div style={{ display: 'flex', gap: 2 }}>
                      <IconBtn icon="edit" onClick={() => setModal({ mode: 'edit', data: p })} />
                      <IconBtn icon="trash" danger onClick={() => confirmDel(`Excluir "${p.name}"?`) && store.removeProduct(p.id)} />
                    </div>
                  </div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>{fil?.name || 'sem filamento'} · {fmt.num(p.weightG)}g · {fmt.hm(p.printTimeMin)}</div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 8, marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
                    <div style={{ flexShrink: 0 }}>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Custo {fmt.brl0(cost)}</div>
                      <div style={{ fontWeight: 800, fontSize: 22, marginTop: 2, whiteSpace: 'nowrap' }}>{fmt.brl(p.price)}</div>
                    </div>
                    <Pill tone={margin >= 80 ? 'g' : margin >= 30 ? 'o' : 'r'}>{lucro >= 0 ? '+' : ''}{fmt.pct(margin)}</Pill>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      <Modal open={!!modal} onClose={() => setModal(null)} title={modal?.mode === 'edit' ? 'Editar produto' : 'Novo produto'}>
        {modal && <ProductForm initial={modal.data} filaments={s.filaments} onSave={(p) => modal.mode === 'edit' ? store.updateProduct(modal.data.id, p) : store.addProduct(p)} onClose={() => setModal(null)} />}
      </Modal>
    </div>
  );
}
window.Catalog = Catalog;

/* ===========================================================
   Histórico de impressões
   =========================================================== */
function PrintForm({ filaments, products, onClose }) {
  const [p, setP] = useState({ date: today(), product: '', filamentId: filaments[0]?.id || null, grams: '', timeMin: '', status: 'sucesso' });
  const set = (k, v) => setP((x) => ({ ...x, [k]: v }));
  const h = Math.floor((Number(p.timeMin) || 0) / 60), m = (Number(p.timeMin) || 0) % 60;
  return (
    <>
      <Field label="Produto / peça">
        <input className="inp" list="histprod" value={p.product} onChange={(e) => set('product', e.target.value)} placeholder="Ex: Vaso geométrico G" />
        <datalist id="histprod">{products.map((x) => <option key={x.id} value={x.name} />)}</datalist>
      </Field>
      <div className="grid2">
        <Field label="Filamento"><Select value={p.filamentId || ''} onChange={(v) => set('filamentId', v)} options={[{ value: '', label: '—' }, ...filaments.map((f) => ({ value: f.id, label: f.name }))]} /></Field>
        <Field label="Filamento usado"><Num value={p.grams} onChange={(v) => set('grams', v)} suffix="g" /></Field>
      </div>
      <div className="grid2">
        <Field label="Tempo">
          <div style={{ display: 'flex', gap: 8 }}>
            <Num value={h} onChange={(v) => set('timeMin', (Number(v) || 0) * 60 + m)} suffix="h" />
            <Num value={m} onChange={(v) => set('timeMin', h * 60 + (Number(v) || 0))} suffix="min" />
          </div>
        </Field>
        <Field label="Resultado">
          <div className="seg" style={{ width: '100%' }}>
            <button className={p.status === 'sucesso' ? 'on' : ''} style={{ flex: 1 }} onClick={() => set('status', 'sucesso')}>Sucesso</button>
            <button className={p.status === 'falha' ? 'on' : ''} style={{ flex: 1 }} onClick={() => set('status', 'falha')}>Falha</button>
          </div>
        </Field>
      </div>
      <Field label="Data"><input type="date" className="inp" value={p.date} onChange={(e) => set('date', e.target.value)} /></Field>
      <div className="field-hint" style={{ marginTop: -8 }}>Registrar consome a gramagem do estoque do filamento.</div>
      <div className="modal-f" style={{ margin: '12px -22px -22px', borderTop: '1px solid var(--line)' }}>
        <Button variant="ghost" onClick={onClose}>Cancelar</Button>
        <Button variant="primary" icon="check" onClick={() => {
          if (p.product) {
            store.addPrint({ ...p, grams: Number(p.grams) || 0, timeMin: Number(p.timeMin) || 0 });
            const fil = filaments.find((f) => f.id === p.filamentId);
            if (fil && Number(p.grams)) store.updateFilament(fil.id, { remaining: Math.max(0, fil.remaining - Number(p.grams)) });
            onClose();
          }
        }}>Registrar impressão</Button>
      </div>
    </>
  );
}

function History() {
  const s = useStore();
  const [modal, setModal] = useState(false);
  const [filt, setFilt] = useState('todas');
  const list = s.prints.filter((p) => filt === 'todas' || p.status === filt).sort((a, b) => (b.date > a.date ? 1 : -1));
  const totG = s.prints.reduce((a, p) => a + p.grams, 0);
  const totH = s.prints.reduce((a, p) => a + p.timeMin, 0) / 60;
  const ok = s.prints.filter((p) => p.status === 'sucesso').length;
  const taxa = s.prints.length ? (ok / s.prints.length) * 100 : 0;

  return (
    <div className="page">
      <PageHead title="Histórico de Impressões" sub="Cada job da impressora — material gasto, tempo e resultado. Falhas ajudam a calibrar a reserva de risco."
        action={<Button variant="primary" icon="plus" onClick={() => setModal(true)}>Registrar impressão</Button>} />

      <div className="kpis" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 18 }}>
        <Kpi label="Impressões" value={s.prints.length} />
        <Kpi label="Filamento gasto" value={<span>{(totG / 1000).toFixed(2).replace('.', ',')}<small> kg</small></span>} />
        <Kpi label="Horas de máquina" value={<span>{totH.toFixed(0)}<small> h</small></span>} />
        <Kpi label="Taxa de sucesso" dot={taxa >= 90 ? 'g' : 'r'} value={fmt.pct(taxa)} />
      </div>

      <div className="toolbar">
        <div className="seg">
          {[['todas', 'Todas'], ['sucesso', 'Sucessos'], ['falha', 'Falhas']].map(([v, l]) => <button key={v} className={filt === v ? 'on' : ''} onClick={() => setFilt(v)}>{l}</button>)}
        </div>
      </div>

      <div className="panel">
        {list.length === 0 ? <Empty icon="history" title="Nenhuma impressão registrada" action={<Button variant="primary" icon="plus" onClick={() => setModal(true)}>Registrar impressão</Button>}>Acompanhe cada job da sua impressora.</Empty> : (
          <table className="tbl">
            <thead><tr><th>Peça</th><th className="hide-sm">Filamento</th><th className="hide-sm">Data</th><th className="r">Material</th><th className="r hide-sm">Tempo</th><th className="r">Resultado</th><th></th></tr></thead>
            <tbody>
              {list.map((p) => {
                const fil = s.filaments.find((f) => f.id === p.filamentId);
                return (
                  <tr key={p.id}>
                    <td style={{ fontWeight: 600 }}>{p.product}</td>
                    <td className="hide-sm">
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
                        <span style={{ width: 12, height: 12, borderRadius: '50%', background: fil?.color || 'var(--muted-2)', border: '1px solid var(--line-2)' }} />
                        <span className="muted" style={{ fontSize: 13 }}>{fil?.name || '—'}</span>
                      </span>
                    </td>
                    <td className="hide-sm mono muted">{fmt.dateFull(p.date)}</td>
                    <td className="r num">{fmt.num(p.grams)}g</td>
                    <td className="r num muted hide-sm">{fmt.hm(p.timeMin)}</td>
                    <td className="r">{p.status === 'sucesso' ? <Pill tone="g">Sucesso</Pill> : <Pill tone="r">Falha</Pill>}</td>
                    <td className="r"><IconBtn icon="trash" danger onClick={() => store.removePrint(p.id)} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title="Registrar impressão">
        <PrintForm filaments={s.filaments} products={s.products} onClose={() => setModal(false)} />
      </Modal>
    </div>
  );
}
window.History = History;
