/* COMERCIAL · SIMULADOR — ecrã de simulação financeira sobre os 44 equipamentos.
 * Form no topo + 3 cards de plano lado-a-lado com €/m², €/mês, investimento, ROI. */

const fmtE = (n) => Math.round(n).toLocaleString('pt-PT') + ' €';
const fmtEur2 = (n) => n.toLocaleString('pt-PT', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';

// ───── Cálculos (mock mas coerentes) ─────
function calcularSimulacao(eq, volume, plano) {
  if (!eq) return null;
  const vol = volume || eq.typicalVol;
  // Preço de venda por m² estimado (varia por categoria)
  const pvpPorM2 = eq.cat.includes('Flatbed') ? 28 : eq.cat.includes('Têxtil') ? 12 : eq.cat.includes('UV') ? 22 : 16;
  const receitaMensal = vol * pvpPorM2;
  const custoTinta = vol * 8 * eq.inkPerM2 * 50; // €/m²
  const custoMedia = vol * 4.5;
  const custoOperador = 1800;

  // Por plano
  let mensalidade = 0, invInicial = 0, manutencao = 0, tco60m = 0;
  if (plano === 'pronto') {
    invInicial = eq.price;
    manutencao = eq.price * 0.04 / 12; // 4% a.a. em mant.
    tco60m = eq.price + manutencao * 60;
  } else if (plano === 'printplan') {
    // All-inclusive 60m · inclui tinta + mant + financiamento
    mensalidade = eq.price / 60 * 1.18 + eq.price * 0.002 + 280; // base + mant + software
    invInicial = eq.price * 0.05; // entrada 5%
    manutencao = 0; // incluída
    tco60m = invInicial + mensalidade * 60;
  } else if (plano === 'digirent') {
    // Renting 48m · sem aquisição · só OPEX
    mensalidade = eq.price / 48 * 1.22 + 180;
    invInicial = 0;
    manutencao = 0;
    tco60m = mensalidade * 48;
  }

  const custoTotalMensal = custoTinta + custoMedia + custoOperador + (plano === 'pronto' ? manutencao : mensalidade);
  const lucroMensal = receitaMensal - custoTotalMensal;
  const custoPorM2 = custoTotalMensal / (vol || 1);
  const margem = receitaMensal > 0 ? (lucroMensal / receitaMensal) * 100 : 0;
  const paybackMeses = invInicial > 0 && lucroMensal > 0 ? Math.ceil(invInicial / lucroMensal) : 0;
  const roi60m = tco60m > 0 ? ((lucroMensal * 60 - invInicial) / (tco60m || 1)) * 100 : 0;

  return {
    invInicial, mensalidade, custoPorM2, receitaMensal, lucroMensal, margem,
    paybackMeses, tco60m, custoTinta, custoMedia, custoOperador, manutencao,
  };
}

// ───── Equipment picker ─────
const EquipPicker = ({ value, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const selected = EQUIPAMENTOS.find(e => e.id === value);

  const filtered = React.useMemo(() => {
    const q = query.toLowerCase();
    if (!q) return EQUIPAMENTOS;
    return EQUIPAMENTOS.filter(e =>
      e.name.toLowerCase().includes(q) || e.cat.toLowerCase().includes(q) || e.brand.toLowerCase().includes(q),
    );
  }, [query]);

  const grouped = React.useMemo(() => {
    const g = {};
    filtered.forEach(e => { (g[e.cat] = g[e.cat] || []).push(e); });
    return g;
  }, [filtered]);

  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(v => !v)} style={{
        width: '100%', padding: '10px 12px', textAlign: 'left',
        background: 'var(--bg-elev)', color: 'var(--text)',
        border: '1px solid var(--border)', borderRadius: 8, cursor: 'pointer',
        fontFamily: 'inherit', fontSize: 13,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          {selected ? (
            <>
              <div style={{ fontWeight: 600 }}>{selected.brand} · {selected.name}</div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 1 }}>{selected.cat} · {selected.width}</div>
            </>
          ) : (
            <span style={{ color: 'var(--text-dim)' }}>Escolhe equipamento…</span>
          )}
        </div>
        <Icon name="chevron-down" size={14} style={{ color: 'var(--text-muted)' }} />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 70 }} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0,
            background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 10,
            boxShadow: 'var(--shadow-lg)', zIndex: 71,
            maxHeight: 380, overflowY: 'auto',
          }} className="scrollbar">
            <div style={{ padding: 10, borderBottom: '1px solid var(--border)', position: 'sticky', top: 0, background: 'var(--bg-elev)', zIndex: 2 }}>
              <div style={{ position: 'relative' }}>
                <Icon name="search" size={12} style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-dim)' }} />
                <input
                  autoFocus
                  placeholder="Procurar entre 44 modelos…"
                  value={query}
                  onChange={e => setQuery(e.target.value)}
                  style={{
                    width: '100%', padding: '6px 10px 6px 26px',
                    background: 'var(--bg)', color: 'var(--text)',
                    border: '1px solid var(--border)', borderRadius: 6,
                    fontSize: 12, outline: 'none', fontFamily: 'inherit',
                  }}
                />
              </div>
            </div>
            {Object.keys(grouped).length === 0 && (
              <div style={{ padding: 20, textAlign: 'center', color: 'var(--text-muted)', fontSize: 12 }}>Nada encontrado.</div>
            )}
            {Object.entries(grouped).map(([cat, items]) => (
              <div key={cat}>
                <div style={{
                  padding: '6px 12px', fontSize: 10, fontWeight: 600,
                  color: 'var(--text-dim)', letterSpacing: '0.08em',
                  fontFamily: 'var(--font-mono)', background: 'var(--bg-sunken)',
                  position: 'sticky', top: 50, zIndex: 1,
                }}>{cat.toUpperCase()}</div>
                {items.map(e => (
                  <button key={e.id} onClick={() => { onChange(e.id); setOpen(false); setQuery(''); }} style={{
                    width: '100%', textAlign: 'left', padding: '8px 12px',
                    background: value === e.id ? 'color-mix(in oklch, var(--ai-500) 10%, transparent)' : 'transparent',
                    color: 'var(--text)', border: 'none', cursor: 'pointer',
                    display: 'flex', alignItems: 'center', gap: 8,
                    fontFamily: 'inherit', fontSize: 12.5,
                  }}
                  onMouseEnter={e2 => { if (value !== e.id) e2.currentTarget.style.background = 'var(--bg-sunken)'; }}
                  onMouseLeave={e2 => { if (value !== e.id) e2.currentTarget.style.background = 'transparent'; }}
                  >
                    <span style={{ flex: 1 }}>
                      <strong>{e.brand}</strong> · {e.name}
                      {e.popular && <span style={{ marginLeft: 6, fontSize: 9, padding: '1px 5px', borderRadius: 3, background: 'color-mix(in oklch, var(--warning) 18%, transparent)', color: 'var(--warning)', fontWeight: 700 }}>POPULAR</span>}
                    </span>
                    <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{fmtE(e.price)}</span>
                  </button>
                ))}
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

// ───── Plan card ─────
const PlanoCard = ({ plano, eq, vol, highlight, onAction }) => {
  const sim = calcularSimulacao(eq, vol, plano.id);
  if (!sim) return null;
  const color = plano.id === 'printplan' ? 'var(--ai-500)' : plano.id === 'digirent' ? 'var(--accent-500)' : 'var(--text)';

  return (
    <div style={{
      position: 'relative',
      padding: 20,
      borderRadius: 14,
      background: highlight ? `color-mix(in oklch, ${color} 6%, var(--bg-elev))` : 'var(--bg-elev)',
      border: `1px solid ${highlight ? `color-mix(in oklch, ${color} 40%, var(--border))` : 'var(--border)'}`,
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      {highlight && (
        <div style={{
          position: 'absolute', top: -10, left: 16,
          padding: '3px 10px', borderRadius: 999,
          background: color, color: '#fff',
          fontSize: 10, fontWeight: 700, letterSpacing: '0.06em',
          fontFamily: 'var(--font-mono)',
        }}>RECOMENDADO</div>
      )}

      <div>
        <div className="font-display" style={{ fontSize: 18, fontWeight: 700, color, letterSpacing: '-0.01em' }}>
          {plano.label}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>{plano.short}</div>
      </div>

      {/* Key metric */}
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 2 }}>
          {plano.id === 'pronto' ? 'INVESTIMENTO INICIAL' : 'MENSALIDADE'}
        </div>
        <div className="font-display" style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
          {plano.id === 'pronto' ? fmtE(sim.invInicial) : fmtE(sim.mensalidade)}
          {plano.id !== 'pronto' && <span style={{ fontSize: 13, color: 'var(--text-muted)', fontWeight: 400 }}>/mês</span>}
        </div>
        {plano.id !== 'pronto' && sim.invInicial > 0 && (
          <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>
            entrada {fmtE(sim.invInicial)}
          </div>
        )}
      </div>

      <div style={{ height: 1, background: 'var(--border)' }} />

      {/* Breakdown */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { label: 'Custo por m²', value: fmtEur2(sim.custoPorM2), mono: true },
          { label: 'Receita mensal', value: fmtE(sim.receitaMensal) },
          { label: 'Lucro mensal', value: fmtE(sim.lucroMensal), positive: sim.lucroMensal > 0, bold: true },
          { label: 'Margem', value: `${sim.margem.toFixed(1)}%`, positive: sim.margem > 20 },
        ].map((r, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
            <span style={{ color: 'var(--text-muted)' }}>{r.label}</span>
            <span className={r.mono ? 'font-mono' : ''} style={{
              color: r.positive === false ? 'var(--danger)' : r.positive ? 'var(--success)' : 'var(--text)',
              fontWeight: r.bold ? 700 : 500,
            }}>{r.value}</span>
          </div>
        ))}
      </div>

      <div style={{ height: 1, background: 'var(--border)' }} />

      {/* Footer KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <div style={{ padding: 10, background: 'var(--bg-sunken)', borderRadius: 8 }}>
          <div style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>PAYBACK</div>
          <div className="font-display" style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>
            {sim.paybackMeses ? `${sim.paybackMeses}m` : '—'}
          </div>
        </div>
        <div style={{ padding: 10, background: 'var(--bg-sunken)', borderRadius: 8 }}>
          <div style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>TCO 60M</div>
          <div className="font-display" style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>
            {fmtE(sim.tco60m / 1000)}k
          </div>
        </div>
      </div>
    </div>
  );
};

// ───── Main screen ─────
const ScreenComercialSimulador = ({ onNav }) => {
  const [eqId, setEqId] = React.useState('ucjv330-160');
  const [volume, setVolume] = React.useState(800);
  const [cliente, setCliente] = React.useState(null);
  const [clienteQuery, setClienteQuery] = React.useState('');
  const [highlight, setHighlight] = React.useState('printplan');

  const eq = EQUIPAMENTOS.find(e => e.id === eqId);
  const clienteFiltered = clienteQuery
    ? SIM_CLIENTES_SUGESTOES.filter(c => c.name.toLowerCase().includes(clienteQuery.toLowerCase()))
    : [];

  const pickCliente = (c) => {
    setCliente(c);
    setClienteQuery(c.name);
    setVolume(c.volumeSugerido);
  };

  return (
    <div style={{ minHeight: 'calc(100vh - var(--topbar-h))', background: 'var(--bg)' }}>
      {/* Header */}
      <div style={{ padding: '24px 32px 20px', borderBottom: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, marginBottom: 4 }}>
          <div style={{ flex: 1 }}>
            <div className="font-display" style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em' }}>Simulador</div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>
              44 modelos · 3 planos · compara lado-a-lado. <span style={{ color: 'var(--ai-500)' }}>
                <Icon name="sparkle" size={11} style={{ color: 'inherit' }} />
                {' '}Podes também pedir à Digi: <em>"simula UCJV330 para o Olimpo"</em>.
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Form */}
      <div style={{ padding: '20px 32px', background: 'var(--bg-elev)', borderBottom: '1px solid var(--border)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2.2fr 1fr 1.5fr', gap: 14, alignItems: 'end' }}>
          <div>
            <label style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>EQUIPAMENTO</label>
            <EquipPicker value={eqId} onChange={setEqId} />
          </div>
          <div>
            <label style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>
              VOLUME <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--text-dim)' }}>(m²/mês)</span>
            </label>
            <input
              type="number"
              value={volume}
              onChange={e => setVolume(Number(e.target.value) || 0)}
              style={{
                width: '100%', padding: '10px 12px',
                background: 'var(--bg)', color: 'var(--text)',
                border: '1px solid var(--border)', borderRadius: 8,
                fontSize: 13, fontFamily: 'var(--font-mono)', fontWeight: 600, outline: 'none',
              }}
            />
            {eq && (
              <div style={{ fontSize: 10.5, color: 'var(--text-dim)', marginTop: 4 }}>
                típico para este modelo: {eq.typicalVol} m²/mês
              </div>
            )}
          </div>
          <div style={{ position: 'relative' }}>
            <label style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 6, display: 'block' }}>
              CLIENTE <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--text-dim)' }}>(opcional)</span>
            </label>
            <input
              type="text"
              value={clienteQuery}
              onChange={e => { setClienteQuery(e.target.value); setCliente(null); }}
              placeholder="Procurar na carteira…"
              style={{
                width: '100%', padding: '10px 12px',
                background: 'var(--bg)', color: 'var(--text)',
                border: '1px solid var(--border)', borderRadius: 8,
                fontSize: 13, outline: 'none', fontFamily: 'inherit',
              }}
            />
            {clienteFiltered.length > 0 && !cliente && (
              <div style={{
                position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0, zIndex: 50,
                background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 8,
                boxShadow: 'var(--shadow-lg)', overflow: 'hidden',
              }}>
                {clienteFiltered.map(c => (
                  <button key={c.id} onClick={() => pickCliente(c)} style={{
                    width: '100%', textAlign: 'left', padding: '8px 12px',
                    background: 'transparent', color: 'var(--text)', border: 'none',
                    cursor: 'pointer', fontSize: 12.5, fontFamily: 'inherit',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-sunken)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >
                    <span>{c.name}</span>
                    <span style={{ fontSize: 10.5, color: 'var(--text-muted)' }}>volume {c.volumeSugerido} m²</span>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Results */}
      <div style={{ padding: '22px 32px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
            COMPARATIVO · 3 PLANOS · 60 MESES
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>
            <span style={{ color: 'var(--ai-500)' }}>
              <Icon name="sparkle" size={10} style={{ color: 'inherit', marginRight: 3 }} />
              Digi sugere PrintPlan
            </span> — equilíbrio entre cashflow e controlo total.
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {PLANOS_SIM.map(p => (
            <PlanoCard key={p.id} plano={p} eq={eq} vol={volume} highlight={highlight === p.id} />
          ))}
        </div>

        {/* Actions */}
        <div style={{
          marginTop: 20, padding: 16, borderRadius: 12,
          background: 'var(--bg-elev)', border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
        }}>
          <div style={{ flex: 1, minWidth: 200, fontSize: 12.5, color: 'var(--text-muted)' }}>
            {cliente ? (
              <>Simulação pronta para <strong style={{ color: 'var(--text)' }}>{cliente.name}</strong>. O que queres fazer?</>
            ) : (
              <>Simulação calculada. Associa a um cliente para personalizar a proposta.</>
            )}
          </div>
          <button className="btn btn-sm"><Icon name="download" size={12} />Gerar PDF</button>
          <button className="btn btn-sm"><Icon name="chat" size={12} />Enviar via WA</button>
          <button className="btn btn-sm"><Icon name="user" size={12} />Guardar no cliente</button>
          <button className="btn btn-sm" style={{ background: 'var(--ai-500)', color: '#fff', borderColor: 'transparent' }}>
            <Icon name="sparkle" size={12} />
            Pedir à Digi explicar
          </button>
        </div>
      </div>
    </div>
  );
};

window.ScreenComercialSimulador = ScreenComercialSimulador;
