/* ===========================================================
   Forja 3D — Filamentos (estoque + custo)
   =========================================================== */
const FIL_TYPES = ['PLA', 'PLA+', 'PETG', 'ABS', 'TPU', 'Silk', 'Wood', 'Nylon', 'Resina', 'Outro'];
const SWATCHES = ['#1a1a1a', '#FF6A1A', '#e0533b', '#3ec06b', '#5aa9e0', '#9b7ce0', '#d4af37', '#cfe8ff', '#ffffff', '#7a7a7a'];

function FilamentForm({ initial, onSave, onClose }) {
  const [f, setF] = useState(initial || { name: '', type: 'PLA', brand: '', color: '#FF6A1A', costPerKg: 100, spoolWeight: 1000, remaining: 1000 });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  return (
    <>
      <div className="grid2">
        <Field label="Nome / identificação"><Text value={f.name} onChange={(v) => set('name', v)} placeholder="Ex: PLA Preto" /></Field>
        <Field label="Marca"><Text value={f.brand} onChange={(v) => set('brand', v)} placeholder="Ex: Voolt" /></Field>
      </div>
      <div className="grid2">
        <Field label="Tipo"><Select value={f.type} onChange={(v) => set('type', v)} options={FIL_TYPES.map((t) => ({ value: t, label: t }))} /></Field>
        <Field label="Custo do rolo (por kg)"><Num value={f.costPerKg} onChange={(v) => set('costPerKg', v)} prefix="R$" suffix="/kg" /></Field>
      </div>
      <div className="grid2">
        <Field label="Peso do rolo cheio"><Num value={f.spoolWeight} onChange={(v) => set('spoolWeight', v)} suffix="g" /></Field>
        <Field label="Quanto resta"><Num value={f.remaining} onChange={(v) => set('remaining', v)} suffix="g" /></Field>
      </div>
      <Field label="Cor">
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {SWATCHES.map((c) => (
            <button key={c} onClick={() => set('color', c)} style={{ width: 30, height: 30, borderRadius: '50%', background: c, border: f.color === c ? '2px solid var(--orange)' : '1px solid var(--line-2)', boxShadow: f.color === c ? '0 0 0 2px var(--bg)' : 'none' }} />
          ))}
        </div>
      </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={() => { onSave(f); onClose(); }}>Salvar filamento</Button>
      </div>
    </>
  );
}

function Filaments() {
  const s = useStore();
  const [modal, setModal] = useState(null); // {mode:'add'|'edit', data}
  const totalValor = s.filaments.reduce((a, f) => a + (f.remaining / 1000) * f.costPerKg, 0);
  const totalKg = s.filaments.reduce((a, f) => a + f.remaining, 0) / 1000;

  return (
    <div className="page">
      <PageHead title="Filamentos" sub="Seu estoque e o custo de cada material. A calculadora usa estes valores para precificar."
        action={<Button variant="primary" icon="plus" onClick={() => setModal({ mode: 'add' })}>Novo filamento</Button>} />

      <div className="kpis" style={{ gridTemplateColumns: 'repeat(3,1fr)', marginBottom: 18 }}>
        <Kpi label="Rolos cadastrados" value={s.filaments.length} />
        <Kpi label="Estoque total" dot="" value={<span>{totalKg.toFixed(2).replace('.', ',')}<small> kg</small></span>} />
        <Kpi label="Valor em estoque" dot="g" value={fmt.brl0(totalValor)} />
      </div>

      {s.filaments.length === 0 ? (
        <div className="panel"><Empty icon="spool" title="Nenhum filamento cadastrado" action={<Button variant="primary" icon="plus" onClick={() => setModal({ mode: 'add' })}>Cadastrar filamento</Button>}>Adicione seus rolos para controlar estoque e custos.</Empty></div>
      ) : (
        <div className="grid-3c">
          {s.filaments.map((f) => {
            const pct = (f.remaining / f.spoolWeight) * 100;
            const low = f.remaining < 200;
            return (
              <div className="panel panel-pad" key={f.id}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                  <div style={{ width: 38, height: 38, borderRadius: '50%', background: f.color, border: '3px solid var(--line-2)', flexShrink: 0, position: 'relative', display: 'grid', placeItems: 'center' }}>
                    <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#14110f', border: '1px solid var(--line)' }} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 15 }}>{f.name}</div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>{f.type} · {f.brand || 'sem marca'}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 2 }}>
                    <IconBtn icon="edit" onClick={() => setModal({ mode: 'edit', data: f })} />
                    <IconBtn icon="trash" danger onClick={() => confirmDel(`Excluir "${f.name}"?`) && store.removeFilament(f.id)} />
                  </div>
                </div>

                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', margin: '16px 0 7px' }}>
                  <span className="mono" style={{ fontSize: 12, color: low ? 'var(--red)' : 'var(--muted)' }}>{fmt.num(f.remaining)}g de {fmt.num(f.spoolWeight)}g</span>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: low ? 'var(--red)' : 'var(--orange)' }}>{low ? 'BAIXO' : fmt.pct(pct)}</span>
                </div>
                <div className="bar thin"><i style={{ width: pct + '%', background: low ? 'var(--red)' : f.color }} /></div>

                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
                  <div><div className="mono" style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Custo</div><div className="mono" style={{ fontWeight: 700, marginTop: 3 }}>{fmt.brl0(f.costPerKg)}/kg</div></div>
                  <div style={{ textAlign: 'right' }}><div className="mono" style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Em estoque</div><div className="mono" style={{ fontWeight: 700, marginTop: 3, color: 'var(--green)' }}>{fmt.brl0((f.remaining / 1000) * f.costPerKg)}</div></div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      <Modal open={!!modal} onClose={() => setModal(null)} title={modal?.mode === 'edit' ? 'Editar filamento' : 'Novo filamento'}>
        {modal && <FilamentForm initial={modal.data}
          onSave={(f) => modal.mode === 'edit' ? store.updateFilament(modal.data.id, f) : store.addFilament(f)}
          onClose={() => setModal(null)} />}
      </Modal>
    </div>
  );
}
window.Filaments = Filaments;
