// ---- Adapters: DB row <-> UI shape ----
const STATUS_DB_TO_UI = {
  ativo: 'Ativo', em_avaliacao: 'Em Avaliação', inativo: 'Inativo', bloqueado: 'Bloqueado',
};
const STATUS_UI_TO_DB = {
  'Ativo': 'ativo', 'Em Avaliação': 'em_avaliacao', 'Inativo': 'inativo', 'Bloqueado': 'bloqueado',
};
const toUiSupplier = (row) => ({
  ...row,
  contact:     row.contact_name || '—',
  whats:       row.whatsapp || '—',
  response:    row.response_rate ?? 0,
  avgDelivery: row.avg_delivery || '—',
  status:      STATUS_DB_TO_UI[row.status] || 'Em Avaliação',
});

function ScreenSuppliers({ setRoute }) {
  const { CATEGORIES } = window.SCP;
  const [q, setQ] = useState('');
  const [cat, setCat] = useState('todas');
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [loadErr, setLoadErr] = useState(null);
  const [showNew, setShowNew] = useState(false);
  const [highlightId, setHighlightId] = useState(null);
  const [openSup, setOpenSup] = useState(null);

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

  const list = rows.filter(s =>
    (cat === 'todas' || (s.cats || []).includes(cat)) &&
    (!q || (s.name + (s.cnpj || '') + (s.city || '')).toLowerCase().includes(q.toLowerCase()))
  );
  const statusTone = { Ativo: 'emerald', 'Em Avaliação': 'amber', Inativo: 'muted', Bloqueado: 'coral' };

  const kpis = useMemo(() => {
    const ativos = rows.filter(r => r.status === 'Ativo').length;
    const avaliacao = rows.filter(r => r.status === 'Em Avaliação').length;
    const bloqueados = rows.filter(r => r.status === 'Bloqueado').length;
    const scoreSum = rows.reduce((s, r) => s + (Number(r.score) || 0), 0);
    const scoreAvg = rows.length ? (scoreSum / rows.length) : 0;
    const respSum = rows.reduce((s, r) => s + (Number(r.response) || 0), 0);
    const respAvg = rows.length ? Math.round(respSum / rows.length) : 0;
    const catCount = {};
    rows.forEach(r => (r.cats || []).forEach(k => { catCount[k] = (catCount[k] || 0) + 1; }));
    let topCat = null, topCount = 0;
    Object.entries(catCount).forEach(([k, n]) => { if (n > topCount) { topCount = n; topCat = k; } });
    const topCatLabel = topCat ? (CATEGORIES.find(c => c.key === topCat)?.label || topCat) : '—';
    return { ativos, avaliacao, bloqueados, scoreAvg, respAvg, topCatLabel, topCatCount: topCount };
  }, [rows]);

  const handleCreate = async (data) => {
    try {
      const payload = {
        name: data.name,
        cnpj: data.cnpj || null,
        city: data.city || null,
        address: data.address || null,
        contact_name: data.contact || null,
        whatsapp: data.whats || null,
        email: data.email || null,
        cats: data.cats?.length ? data.cats : ['secos'],
        score: 75, wins: 0, response_rate: 0,
        avg_delivery: null,
        status: 'em_avaliacao',
      };
      const created = await window.scpDb.suppliers.create(payload);
      const uiRow = toUiSupplier(created);
      setRows(prev => [uiRow, ...prev]);
      setShowNew(false);
      setHighlightId(uiRow.id);
      window.scpToast('Fornecedor cadastrado', { kind: 'emerald', sub: uiRow.name });
      setTimeout(() => setHighlightId(null), 2400);
    } catch (e) {
      window.scpToast('Erro ao cadastrar', { kind: 'coral', sub: e.message || 'Tente novamente' });
    }
  };

  const handleDelete = async (supplier) => {
    if (!confirm(`Desativar "${supplier.name}"? Ele sai da lista mas o histórico (cotações, pedidos) fica preservado.`)) return;
    try {
      await window.scpDb.suppliers.remove(supplier.id);
      setRows(prev => prev.filter(r => r.id !== supplier.id));
      setOpenSup(null);
      window.scpToast('Fornecedor desativado', { kind: 'amber', sub: supplier.name });
    } catch (e) {
      window.scpToast('Erro ao desativar', { kind: 'coral', sub: e.message || 'Tente novamente' });
    }
  };

  return (
    <div className="scp-screen scp-fade-in">
      <div className="scp-dash-grid">
        <Stat label="Fornecedores ativos" value={String(kpis.ativos)} sub={`${kpis.avaliacao} em avaliação · ${kpis.bloqueados} bloqueado${kpis.bloqueados === 1 ? '' : 's'}`} icon={<Icon.Supplier size={16}/>}/>
        <Stat label="Score médio" value={kpis.scoreAvg.toFixed(1).replace('.', ',')} sub="Pontualidade + preço + vitórias" icon={<Icon.Star size={16}/>}/>
        <Stat label="Top categoria" value={kpis.topCatLabel} sub={`${kpis.topCatCount} fornecedor${kpis.topCatCount === 1 ? '' : 'es'}`} icon={<Icon.Crown size={16}/>}/>
        <Stat label="Taxa resposta média" value={`${kpis.respAvg}%`} sub="Média de cotações respondidas no prazo" icon={<Icon.Reply 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 fornecedores:</strong>{' '}
          <span style={{ color: 'var(--fg-2)', fontSize: 13 }}>{loadErr}</span>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 6 }}>
            Verifique se o schema foi aplicado no Supabase e se o seed-suppliers.sql foi rodado.
          </div>
        </Card>
      )}

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div className="scp-list-head">
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            <button className={cls('scp-chip', cat === 'todas' && 'active')} onClick={() => setCat('todas')}>Todas categorias</button>
            {CATEGORIES.map(c => (
              <button key={c.key} className={cls('scp-chip', cat === c.key && 'active')} onClick={() => setCat(c.key)}>{c.label}</button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Input icon={<Icon.Search size={16}/>} placeholder="Buscar fornecedor…" value={q} onChange={e => setQ(e.target.value)} />
            <Btn kind="primary" icon={<Icon.Plus size={16}/>} onClick={() => setShowNew(true)}>Novo Fornecedor</Btn>
          </div>
        </div>

        <div className="scp-sup-list">
          {loading && (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
              Carregando fornecedores…
            </div>
          )}
          {!loading && list.length === 0 && (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
              <Icon.Supplier size={28}/>
              <p style={{ margin: 0, fontSize: 13 }}>
                {rows.length === 0 ? 'Nenhum fornecedor cadastrado ainda.' : 'Nenhum fornecedor com este filtro.'}
              </p>
              {rows.length === 0 && (
                <Btn kind="primary" size="sm" icon={<Icon.Plus size={14}/>} onClick={() => setShowNew(true)}>
                  Cadastrar primeiro fornecedor
                </Btn>
              )}
            </div>
          )}
          {!loading && list.map(s => (
            <div
              key={s.id}
              className={cls('scp-sup-row clickable', highlightId === s.id && 'just-added')}
              onClick={() => setOpenSup(s)}
              role="button"
              tabIndex={0}
              onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpenSup(s); } }}
            >
              <Avatar name={s.name} size={42}/>
              <div className="info">
                <div className="head">
                  <span className="n">{s.name}</span>
                  <Badge tone={statusTone[s.status]}>{s.status}</Badge>
                </div>
                <div className="meta">
                  <span>CNPJ <span className="num">{s.cnpj}</span></span>
                  <span>{s.city}</span>
                  <span>{s.contact} · <span className="num">{s.whats}</span></span>
                </div>
                <div className="cats">
                  {s.cats.map(k => {
                    const c = CATEGORIES.find(x => x.key === k);
                    return c ? <Pill key={k} tone={c.tone}>{c.label}</Pill> : null;
                  })}
                </div>
              </div>
              <div className="stats">
                <div><span>Score</span><strong className="num em">{s.score}</strong></div>
                <div><span>Vitórias</span><strong className="num">{s.wins}</strong></div>
                <div><span>Resposta</span><strong className="num">{s.response}%</strong></div>
                <div><span>Entrega</span><strong>{s.avgDelivery}</strong></div>
              </div>
              <div className="acts" onClick={e => e.stopPropagation()}>
                <IconBtn kind="ghost" icon={<Icon.WhatsApp />} title="WhatsApp"/>
                <IconBtn kind="ghost" icon={<Icon.Mail />} title="E-mail"/>
                <IconBtn kind="ghost" icon={<Icon.Edit />} title="Editar"/>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {showNew && <NewSupplierModal onClose={() => setShowNew(false)} onCreate={handleCreate} categories={CATEGORIES} />}

      <Drawer
        open={!!openSup}
        onClose={() => setOpenSup(null)}
        eyebrow={openSup?.id}
        title={openSup?.name || ''}
        headerRight={openSup && <Badge tone={statusTone[openSup.status]}>{openSup.status}</Badge>}
        footer={openSup && (
          <>
            <Btn kind="ghost" icon={<Icon.Trash size={14}/>} onClick={() => handleDelete(openSup)} style={{ color: 'oklch(0.82 0.14 25)', marginRight: 'auto' }}>Excluir</Btn>
            <Btn kind="secondary" icon={<Icon.Mail size={14}/>} onClick={() => {
              if (openSup.email && openSup.email !== '—') window.open(`mailto:${openSup.email}?subject=${encodeURIComponent('Contato · ' + window.SCP.COMPANY.name)}`, '_self');
              else window.scpToast('Sem e-mail cadastrado', { kind: 'amber', sub: openSup.name });
            }}>E-mail</Btn>
            <Btn kind="primary" icon={<Icon.WhatsApp size={14}/>} onClick={() => {
              const num = (openSup.whats || '').replace(/\D/g, '');
              if (num) window.open(`https://wa.me/55${num}`, '_blank', 'noopener');
              else window.scpToast('Sem WhatsApp cadastrado', { kind: 'amber' });
            }}>Abrir WhatsApp</Btn>
          </>
        )}
      >
        {openSup && <SupplierDetail supplier={openSup} categories={CATEGORIES} />}
      </Drawer>
    </div>
  );
}

function SupplierDetail({ supplier: s, categories }) {
  const { BRL } = window.SCP;
  const [recentOrders, setRecentOrders] = useState(null);
  const [products, setProducts] = useState(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      const [orders, prods] = await Promise.all([
        window.scpDb.suppliers.ordersBy(s.id),
        window.scpDb.suppliers.productsBy(s.id),
      ]);
      if (!mounted) return;
      setRecentOrders(orders);
      setProducts(prods);
    })();
    return () => { mounted = false; };
  }, [s.id]);

  return (
    <>
      <div className="scp-detail-hero">
        <Avatar name={s.name} size={52}/>
        <div style={{ minWidth: 0 }}>
          <div className="name">{s.name}</div>
          <div className="meta">{s.city} · {s.id}</div>
          <div className="scp-detail-cats" style={{ marginTop: 8 }}>
            {s.cats.map(k => {
              const c = categories.find(x => x.key === k);
              return c ? <Pill key={k} tone={c.tone}>{c.label}</Pill> : null;
            })}
          </div>
        </div>
      </div>

      <div className="scp-detail-section">
        <h4>Performance</h4>
        <div className="scp-detail-metrics">
          <div className="scp-detail-metric">
            <span className="l">Score</span>
            <span className="v em">{s.score}</span>
            <span className="s">Pontualidade · preço · vitórias</span>
          </div>
          <div className="scp-detail-metric">
            <span className="l">Vitórias</span>
            <span className="v">{s.wins}</span>
            <span className="s">Cotações vencidas (90d)</span>
          </div>
          <div className="scp-detail-metric">
            <span className="l">Taxa de resposta</span>
            <span className="v">{s.response}%</span>
            <span className="s">Cotações respondidas no prazo</span>
          </div>
          <div className="scp-detail-metric">
            <span className="l">Prazo médio</span>
            <span className="v">{s.avgDelivery}</span>
            <span className="s">Entrega após confirmação</span>
          </div>
        </div>
      </div>

      <div className="scp-detail-section">
        <h4>Contato</h4>
        <dl className="scp-detail-kv">
          <dt>CNPJ</dt><dd className="num">{s.cnpj}</dd>
          <dt>Cidade</dt><dd>{s.city}</dd>
          <dt>Endereço</dt><dd>{s.address || '—'}</dd>
          <dt>Responsável</dt><dd>{s.contact}</dd>
          <dt>WhatsApp</dt><dd className="num">{s.whats}</dd>
          <dt>E-mail</dt><dd>{s.email || '—'}</dd>
        </dl>
      </div>

      <div className="scp-detail-section">
        <h4>Produtos fornecidos</h4>
        {products === null ? (
          <div className="scp-detail-empty">Carregando…</div>
        ) : products.length ? (
          <div className="scp-detail-list">
            {products.map(p => (
              <div key={p.id} className="scp-detail-list-row">
                <div>
                  <div className="n">{p.name}</div>
                  <div className="s">{p.code} · {p.unit}</div>
                </div>
                <span className="v">{p.last_price ? BRL(p.last_price) : '—'}</span>
              </div>
            ))}
          </div>
        ) : (
          <div className="scp-detail-empty">Nenhum produto vinculado a este fornecedor.</div>
        )}
      </div>

      <div className="scp-detail-section">
        <h4>Últimos pedidos</h4>
        {recentOrders === null ? (
          <div className="scp-detail-empty">Carregando…</div>
        ) : recentOrders.length ? (
          <div className="scp-detail-list">
            {recentOrders.map(o => (
              <div key={o.id} className="scp-detail-list-row">
                <div>
                  <div className="n num">{o.code}</div>
                  <div className="s">{new Date(o.emitted_at).toLocaleDateString('pt-BR')}</div>
                </div>
                <span className="v">{BRL(o.total)}</span>
              </div>
            ))}
          </div>
        ) : (
          <div className="scp-detail-empty">Sem pedidos recentes deste fornecedor.</div>
        )}
      </div>
    </>
  );
}

function NewSupplierModal({ onClose, onCreate, categories }) {
  const [name, setName] = useState('');
  const [cnpj, setCnpj] = useState('');
  const [city, setCity] = useState('');
  const [address, setAddress] = useState('');
  const [contact, setContact] = useState('');
  const [whats, setWhats] = useState('');
  const [email, setEmail] = useState('');
  const [cats, setCats] = useState([]);

  const emailValid = !email || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const canSubmit = name.trim().length >= 2 && emailValid;

  const toggleCat = (k) => {
    setCats(cats.includes(k) ? cats.filter(x => x !== k) : [...cats, k]);
  };

  const submit = () => {
    if (!canSubmit) return;
    onCreate({
      name: name.trim(), cnpj: cnpj.trim(), city: city.trim(),
      address: address.trim(), contact: contact.trim(),
      whats: whats.trim(), email: email.trim(), cats,
    });
  };

  return ReactDOM.createPortal((
    <div className="scp-modal-mask" onClick={onClose}>
      <div className="scp-modal scp-modal-sup" onClick={e => e.stopPropagation()}>
        <div className="scp-modal-head">
          <h3>Novo Fornecedor</h3>
          <IconBtn icon={<Icon.X size={14}/>} size="sm" onClick={onClose}/>
        </div>
        <div className="scp-modal-body" style={{ padding: '18px 22px' }}>
          <div className="scp-wfield-list">
            <div className="scp-field">
              <span>Razão social / Nome <em style={{ color: 'oklch(0.74 0.18 25)', fontStyle: 'normal' }}>*</em></span>
              <Input placeholder="Ex.: Hortifruti São Pedro" value={name} onChange={e => setName(e.target.value)} autoFocus />
            </div>
            <div className="scp-field-row">
              <div className="scp-field">
                <span>CNPJ</span>
                <Input placeholder="00.000.000/0000-00" value={cnpj} onChange={e => setCnpj(e.target.value)} />
              </div>
              <div className="scp-field">
                <span>Cidade · UF</span>
                <Input placeholder="São Paulo · SP" value={city} onChange={e => setCity(e.target.value)} />
              </div>
            </div>
            <div className="scp-field-row">
              <div className="scp-field">
                <span>Contato</span>
                <Input placeholder="Nome do responsável" value={contact} onChange={e => setContact(e.target.value)} />
              </div>
              <div className="scp-field">
                <span>WhatsApp</span>
                <Input placeholder="(11) 9 0000-0000" value={whats} onChange={e => setWhats(e.target.value)} />
              </div>
            </div>
            <div className="scp-field">
              <span>E-mail</span>
              <Input placeholder="comercial@fornecedor.com.br" type="email" value={email} onChange={e => setEmail(e.target.value)} />
              {email && !emailValid && <small style={{ fontSize: 11, color: 'oklch(0.84 0.14 78)' }}>E-mail inválido</small>}
            </div>
            <div className="scp-field">
              <span>Endereço completo</span>
              <Input placeholder="Rua, número, bairro, cidade · UF · CEP" value={address} onChange={e => setAddress(e.target.value)} />
            </div>
            <div className="scp-field">
              <span>Categorias de atuação</span>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {categories.map(c => (
                  <button
                    key={c.key}
                    className={cls('scp-chip', cats.includes(c.key) && 'active')}
                    onClick={() => toggleCat(c.key)}
                    type="button"
                  >
                    {c.label}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
        <div className="scp-modal-foot">
          <span>Será cadastrado como <strong style={{ color: 'oklch(0.88 0.13 78)' }}>Em Avaliação</strong></span>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn kind="ghost" onClick={onClose}>Cancelar</Btn>
            <Btn kind="primary" disabled={!canSubmit} onClick={submit} icon={<Icon.Check size={14}/>}>Cadastrar fornecedor</Btn>
          </div>
        </div>
      </div>
    </div>
  ), document.body);
}

(function() {
  if (document.getElementById('scp-sup-css')) return;
  const s = document.createElement('style'); s.id = 'scp-sup-css';
  s.textContent = `
    .scp-sup-list { display: flex; flex-direction: column; }
    .scp-sup-row {
      display: grid; grid-template-columns: 42px 1.4fr 1fr auto; gap: 16px; padding: 16px 22px;
      align-items: center; border-bottom: 1px solid var(--border-soft);
      transition: background .12s;
    }
    .scp-sup-row:hover { background: var(--surface-2); }
    .scp-sup-row.clickable { cursor: pointer; transition: background .12s; }
    .scp-sup-row.clickable:focus-visible { outline: none; background: var(--surface-2); box-shadow: inset 3px 0 0 oklch(0.78 0.16 160); }
    .scp-sup-row:last-child { border-bottom: 0; }
    .scp-sup-row .info .head { display: flex; align-items: center; gap: 8px; }
    .scp-sup-row .info .n { font-size: 14px; font-weight: 600; color: var(--fg); }
    .scp-sup-row .info .meta { display: flex; gap: 16px; flex-wrap: wrap; font-size: 11.5px; color: var(--fg-3); margin-top: 4px; }
    .scp-sup-row .info .cats { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 8px; }
    .scp-sup-row .stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; min-width: 320px; }
    .scp-sup-row .stats > div { display: flex; flex-direction: column; gap: 2px; align-items: flex-start; }
    .scp-sup-row .stats span { font-size: 10px; color: var(--fg-3); text-transform: uppercase; letter-spacing: .08em; font-weight: 600; }
    .scp-sup-row .stats strong { font-size: 16px; font-weight: 600; color: var(--fg); }
    .scp-sup-row .stats strong.em { color: oklch(0.92 0.14 160); }
    .scp-sup-row .stats strong.num { font-family: 'JetBrains Mono', monospace; }
    .scp-sup-row .acts { display: flex; gap: 4px; }
    .scp-sup-row.just-added {
      background: oklch(0.26 0.06 160 / .35);
      animation: justAddedPulse 2.4s ease-out;
    }
    @keyframes justAddedPulse {
      0%   { background: oklch(0.34 0.10 160 / .55); box-shadow: inset 3px 0 0 oklch(0.78 0.16 160); }
      100% { background: oklch(0.205 0.012 250); box-shadow: inset 3px 0 0 transparent; }
    }
    .scp-modal-sup { width: 640px; }
    .scp-modal-sup .scp-modal-body { max-height: 60vh; }
    .scp-modal-sup .scp-input { width: 100%; }
  `;
  document.head.appendChild(s);
})();

window.ScreenSuppliers = ScreenSuppliers;
