function ScreenQuotations({ openQuotation, setRoute }) {
  const { BRL } = window.SCP;
  const [filter, setFilter] = useState('todas');
  const [q, setQ] = useState('');
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [loadErr, setLoadErr] = useState(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const data = await window.scpDb.quotations.list();
        if (mounted) setRows(data);
      } catch (e) {
        if (mounted) setLoadErr(e.message || 'Falha ao carregar cotações');
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  const counts = useMemo(() => {
    const c = { todas: rows.length, aberta: 0, analise: 0, fechada: 0, cancelada: 0 };
    rows.forEach(x => { if (c[x.status] !== undefined) c[x.status]++; });
    return c;
  }, [rows]);

  const filtered = rows.filter(x =>
    (filter === 'todas' || x.status === filter) &&
    (!q || ((x.title || '') + ' ' + (x.code || '')).toLowerCase().includes(q.toLowerCase()))
  );

  const kpis = useMemo(() => {
    const emAndamento = counts.aberta + counts.analise;
    const fechadas = counts.fechada;
    const totalInvited = rows.reduce((s, r) => s + (r.suppliersCount || 0), 0);
    const totalResponded = rows.reduce((s, r) => s + (r.respondedCount || 0), 0);
    const taxa = totalInvited ? Math.round(100 * totalResponded / totalInvited) : 0;
    const fechadasComTempo = rows.filter(r => r.status === 'fechada' && r.closed_at && r.created_at);
    const avgDias = fechadasComTempo.length
      ? fechadasComTempo.reduce((s, r) => s + (new Date(r.closed_at) - new Date(r.created_at)) / 86400000, 0) / fechadasComTempo.length
      : 0;
    return { emAndamento, fechadas, taxa, avgDias };
  }, [rows, counts]);

  return (
    <div className="scp-screen scp-fade-in">
      {/* KPI row */}
      <div className="scp-dash-grid">
        <Stat label="Em andamento" value={String(kpis.emAndamento)} sub={`${counts.aberta} abertas · ${counts.analise} em análise`} icon={<Icon.Quote size={16}/>} delta="ao vivo" deltaTone="emerald"/>
        <Stat label="Fechadas" value={String(kpis.fechadas)} sub={`${counts.cancelada} cancelada${counts.cancelada === 1 ? '' : 's'}`} icon={<Icon.Check size={16}/>}/>
        <Stat label="Taxa resposta" value={`${kpis.taxa}%`} sub="Cotações respondidas no prazo" icon={<Icon.Reply size={16}/>}/>
        <Stat label="Tempo médio fechamento" value={kpis.avgDias ? `${kpis.avgDias.toFixed(1).replace('.', ',')} dias` : '—'} sub="Da criação ao pedido emitido" icon={<Icon.Lightning size={16}/>}/>
      </div>

      {loadErr && (
        <Card style={{ padding: 14, borderColor: 'oklch(0.42 0.10 25 / .55)', background: 'oklch(0.26 0.08 25 / .25)' }}>
          <strong style={{ color: 'oklch(0.88 0.14 25)' }}>Falha ao carregar cotações:</strong>{' '}
          <span style={{ color: 'var(--fg-2)', fontSize: 13 }}>{loadErr}</span>
        </Card>
      )}

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div className="scp-list-head">
          <div className="scp-tabs">
            {[['todas','Todas'],['aberta','Abertas'],['analise','Em Análise'],['fechada','Fechadas'],['cancelada','Canceladas']].map(([k, l]) => (
              <button key={k} className={cls(filter === k && 'active')} onClick={() => setFilter(k)}>
                {l} <span className="scp-tab-count">{counts[k]}</span>
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Input icon={<Icon.Search size={16}/>} placeholder="Buscar por número ou título…" value={q} onChange={e => setQ(e.target.value)} />
            <IconBtn kind="secondary" icon={<Icon.Filter />} title="Filtros"/>
            <IconBtn kind="secondary" icon={<Icon.Download />} title="Exportar"/>
          </div>
        </div>
        <table className="scp-table">
          <thead>
            <tr>
              <th style={{ width: 36 }}><input type="checkbox" className="scp-cb"/></th>
              <th>Cotação</th>
              <th>Status</th>
              <th>Progresso</th>
              <th>Itens</th>
              <th>Prazo</th>
              <th style={{ textAlign: 'right' }}>Valor final</th>
              <th style={{ textAlign: 'right' }}>Economia</th>
              <th style={{ width: 36 }}></th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr><td colSpan={9} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)' }}>Carregando cotações…</td></tr>
            )}
            {!loading && filtered.length === 0 && (
              <tr><td colSpan={9} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)' }}>
                {rows.length === 0 ? 'Nenhuma cotação criada ainda.' : 'Nenhuma cotação com este filtro.'}
              </td></tr>
            )}
            {!loading && filtered.map(x => {
              const pct = x.suppliersCount ? Math.round(100 * x.respondedCount / x.suppliersCount) : 0;
              const status = QSTATUS[x.status] || { tone: 'fg', label: x.status };
              const deadline = x.deadline ? new Date(x.deadline).toLocaleDateString('pt-BR') : '—';
              const created = x.created_at ? new Date(x.created_at).toLocaleDateString('pt-BR') : '—';
              return (
                <tr key={x.id} className="clickable" onClick={() => openQuotation(x.id)}>
                  <td onClick={e => e.stopPropagation()}><input type="checkbox" className="scp-cb"/></td>
                  <td>
                    <div className="em">{x.title}</div>
                    <div className="num" style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>{x.code} · criada {created}</div>
                  </td>
                  <td><Badge tone={status.tone}>{status.label}</Badge></td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div className="scp-progress"><span style={{ width: pct + '%' }} /></div>
                      <span className="num" style={{ fontSize: 11.5, color: 'var(--fg-3)', minWidth: 36 }}>{x.respondedCount}/{x.suppliersCount}</span>
                    </div>
                  </td>
                  <td className="num">{x.itemsCount}</td>
                  <td className="num" style={{ color: 'var(--fg-2)' }}>{deadline}</td>
                  <td className="num em" style={{ textAlign: 'right' }}>{x.total_value ? BRL(x.total_value) : '—'}</td>
                  <td className="num em" style={{ textAlign: 'right', color: x.saving_value ? 'oklch(0.86 0.14 160)' : 'var(--fg-3)' }}>
                    {x.saving_value ? '↓ ' + BRL(x.saving_value) : '—'}
                  </td>
                  <td onClick={e => e.stopPropagation()}>
                    <IconBtn icon={<Icon.Chevron size={16}/>} size="sm" />
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {!loading && (
          <div className="scp-list-foot">
            <span>{filtered.length} cotaç{filtered.length === 1 ? 'ão' : 'ões'}</span>
          </div>
        )}
      </Card>
    </div>
  );
}

(function() {
  if (document.getElementById('scp-quotelist-css')) return;
  const s = document.createElement('style'); s.id = 'scp-quotelist-css';
  s.textContent = `
    .scp-list-head {
      display: flex; justify-content: space-between; align-items: center; gap: 12px;
      padding: 18px 22px; border-bottom: 1px solid var(--border-soft);
      flex-wrap: wrap;
    }
    .scp-list-head .scp-input { width: 280px; }
    .scp-list-foot { display: flex; justify-content: space-between; align-items: center; padding: 14px 22px; border-top: 1px solid var(--border-soft); font-size: 12px; color: var(--fg-3); }

    .scp-tab-count { font-size: 10px; padding: 1px 6px; border-radius: 999px; background: var(--surface-3); color: var(--fg-3); font-weight: 600; margin-left: 4px; }
    .scp-tabs button.active .scp-tab-count { background: oklch(0.30 0.06 160 / .5); color: oklch(0.92 0.14 160); }

    .scp-cb { width: 16px; height: 16px; accent-color: oklch(0.74 0.16 160); cursor: pointer; }

    .scp-progress { width: 100px; height: 6px; background: var(--surface-2); border-radius: 999px; overflow: hidden; }
    .scp-progress > span { display: block; height: 100%; background: linear-gradient(90deg, oklch(0.78 0.16 160), oklch(0.65 0.14 230)); border-radius: 999px; }
  `;
  document.head.appendChild(s);
})();

window.ScreenQuotations = ScreenQuotations;
