/* ===========================================================
   Forja 3D — Calculadora de Precificação
   =========================================================== */
function Calculator({ go }) {
  const s = useStore();
  const st = s.settings;
  const fils = s.filaments;

  const [name, setName] = useState('');
  const [filId, setFilId] = useState(fils[0]?.id || 'custom');
  const [customKg, setCustomKg] = useState(100);
  const [grams, setGrams] = useState(80);
  const [hours, setHours] = useState(4);
  const [mins, setMins] = useState(0);
  const [packaging, setPackaging] = useState(st.defaultPackaging);
  const [extra, setExtra] = useState(0);
  const [fail, setFail] = useState(st.failRate);
  const [margin, setMargin] = useState(st.defaultMargin);
  const [fee, setFee] = useState(st.marketplaceFee);
  const [saved, setSaved] = useState(false);

  const fil = fils.find((f) => f.id === filId);
  const costPerKg = filId === 'custom' ? customKg : (fil?.costPerKg || 0);
  const printTimeMin = (Number(hours) || 0) * 60 + (Number(mins) || 0);

  const c = computeCost({ grams: Number(grams) || 0, costPerKg, printTimeMin, packaging: Number(packaging) || 0, margin: Number(margin) || 0, failRate: Number(fail) || 0, marketplaceFee: Number(fee) || 0, extraCost: Number(extra) || 0 }, st);

  const parts = [
    { k: 'Filamento', v: c.filament, color: 'var(--orange)' },
    { k: 'Energia', v: c.energy, color: '#e0a73b' },
    { k: 'Mão de obra', v: c.labor, color: '#5aa9e0' },
    { k: 'Depreciação', v: c.depreciation, color: '#9b7ce0' },
    { k: 'Embalagem', v: c.packaging, color: '#3ec06b' },
    ...(c.extraCost > 0 ? [{ k: 'Custo extra', v: c.extraCost, color: '#8a827a' }] : []),
  ];

  const feeChannels = [
    { label: 'Shopee', v: 14 }, { label: 'Mercado Livre', v: 16 }, { label: 'Elo7', v: 12 }, { label: 'Venda direta', v: 0 },
  ];

  function saveToCatalog() {
    store.addProduct({ name: name || 'Item sem nome', filamentId: filId === 'custom' ? null : filId, weightG: Number(grams) || 0, printTimeMin, price: Math.round(c.finalPrice * 100) / 100, color: fil?.color || 'var(--orange)' });
    setSaved(true);
    setTimeout(() => setSaved(false), 2200);
  }

  return (
    <div className="page">
      <PageHead title="Calculadora de Preço" sub="Calcule o custo real e o preço de venda de cada peça — filamento, energia, mão de obra, depreciação, falhas, embalagem, margem e taxa do marketplace."
        action={<Button variant="ghost" icon="gear" onClick={() => go('config')}>Parâmetros da impressora</Button>} />

      <div className="grid-2c">
        {/* INPUTS */}
        <div className="panel">
          <div className="panel-h"><div className="panel-t"><span className="mark" />Dados da peça</div></div>
          <div className="panel-pad">
            <Field label="Nome do produto (opcional)">
              <Text value={name} onChange={setName} placeholder="Ex: Suporte de fone gamer" />
            </Field>

            <div className="grid2">
              <Field label="Filamento">
                <Select value={filId} onChange={setFilId}
                  options={[...fils.map((f) => ({ value: f.id, label: `${f.name} · ${fmt.brl0(f.costPerKg)}/kg` })), { value: 'custom', label: 'Personalizado…' }]} />
              </Field>
              {filId === 'custom'
                ? <Field label="Custo do filamento"><Num value={customKg} onChange={setCustomKg} prefix="R$" suffix="/kg" /></Field>
                : <Field label="Custo do filamento"><div className="inp" style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--panel-2)' }}>
                    <span style={{ width: 16, height: 16, borderRadius: '50%', background: fil?.color, border: '1px solid var(--line-2)' }} />
                    <span className="mono">{fmt.brl0(costPerKg)}/kg</span></div></Field>}
            </div>

            <div className="grid2">
              <Field label="Peso da peça"><Num value={grams} onChange={setGrams} suffix="g" /></Field>
              <Field label="Tempo de impressão">
                <div style={{ display: 'flex', gap: 8 }}>
                  <Num value={hours} onChange={setHours} suffix="h" />
                  <Num value={mins} onChange={setMins} suffix="min" />
                </div>
              </Field>
            </div>

            <div className="grid2">
              <Field label="Embalagem"><Num value={packaging} onChange={setPackaging} prefix="R$" /></Field>
              <Field label="Custos extras" hint="Imãs, parafusos, tinta…"><Num value={extra} onChange={setExtra} prefix="R$" /></Field>
            </div>

            <div style={{ height: 1, background: 'var(--line)', margin: '6px 0 18px' }} />

            <div className="grid3">
              <Field label="Margem de lucro"><Num value={margin} onChange={setMargin} suffix="%" /></Field>
              <Field label="Reserva p/ falhas"><Num value={fail} onChange={setFail} suffix="%" /></Field>
              <Field label="Taxa marketplace"><Num value={fee} onChange={setFee} suffix="%" /></Field>
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: -4 }}>
              {feeChannels.map((ch) => (
                <button key={ch.label} className="btn btn-sm btn-ghost" style={{ padding: '5px 10px', fontSize: 11.5, borderColor: fee === ch.v ? 'var(--orange)' : 'var(--line)', color: fee === ch.v ? 'var(--orange)' : 'var(--muted)' }} onClick={() => setFee(ch.v)}>{ch.label} {ch.v > 0 ? ch.v + '%' : ''}</button>
              ))}
            </div>
          </div>
        </div>

        {/* RESULT */}
        <div className="section-gap">
          <div className="panel" style={{ background: 'linear-gradient(170deg,#241c12,#1d1916)', borderColor: 'var(--line-2)' }}>
            <div className="panel-pad">
              <div className="kpi-label"><span className="kpi-dot" />Preço de venda sugerido</div>
              <div style={{ fontWeight: 900, fontSize: 46, letterSpacing: -1.5, marginTop: 8, lineHeight: 1 }}>{fmt.brl(c.finalPrice)}</div>
              <div style={{ display: 'flex', gap: 18, marginTop: 16, flexWrap: 'wrap' }}>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Custo total</div>
                  <div className="mono" style={{ fontSize: 17, fontWeight: 700, marginTop: 3 }}>{fmt.brl(c.withFail)}</div>
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Lucro líquido</div>
                  <div className="mono" style={{ fontSize: 17, fontWeight: 700, marginTop: 3, color: 'var(--green)' }}>{fmt.brl(c.profit)}</div>
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Margem real</div>
                  <div className="mono" style={{ fontSize: 17, fontWeight: 700, marginTop: 3, color: 'var(--orange)' }}>{fmt.pct((c.profit / c.withFail) * 100)}</div>
                </div>
              </div>
            </div>
          </div>

          <div className="panel">
            <div className="panel-h"><div className="panel-t"><span className="mark" />Composição do custo</div><span className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{fmt.brl(c.baseCost)}</span></div>
            <div className="panel-pad">
              {/* stacked bar */}
              <div style={{ display: 'flex', height: 14, borderRadius: 4, overflow: 'hidden', marginBottom: 16, background: '#14110f' }}>
                {parts.map((p, i) => <div key={i} style={{ width: (p.v / (c.baseCost || 1)) * 100 + '%', background: p.color }} title={p.k} />)}
              </div>
              {parts.map((p, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--line)' }}>
                  <span style={{ width: 10, height: 10, borderRadius: 2, background: p.color, flexShrink: 0 }} />
                  <span style={{ flex: 1, fontSize: 13.5 }}>{p.k}</span>
                  <span className="mono" style={{ fontSize: 13.5, color: 'var(--muted)' }}>{fmt.pct((p.v / (c.baseCost || 1)) * 100)}</span>
                  <span className="mono" style={{ fontSize: 13.5, fontWeight: 600, minWidth: 72, textAlign: 'right' }}>{fmt.brl(p.v)}</span>
                </div>
              ))}
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0 2px' }}>
                <span style={{ flex: 1, fontSize: 13.5, color: 'var(--muted)' }}>+ Reserva p/ falhas ({fmt.pct(Number(fail) || 0)})</span>
                <span className="mono" style={{ fontSize: 13.5, fontWeight: 600 }}>{fmt.brl(c.failAmount)}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 0' }}>
                <span style={{ flex: 1, fontSize: 13.5, color: 'var(--muted)' }}>+ Taxa marketplace ({fmt.pct(Number(fee) || 0)})</span>
                <span className="mono" style={{ fontSize: 13.5, fontWeight: 600 }}>{fmt.brl(c.feeAmount)}</span>
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10 }}>
            <Button variant="primary" icon={saved ? 'check' : 'box'} onClick={saveToCatalog} style={{ flex: 1, justifyContent: 'center' }}>{saved ? 'Salvo no catálogo!' : 'Salvar no catálogo'}</Button>
            <Button variant="ghost" icon="sale" onClick={() => go('vendas')}>Registrar venda</Button>
          </div>
        </div>
      </div>
    </div>
  );
}
window.Calculator = Calculator;
