// ---- Adapters: DB <-> UI ----
const ORDER_STATUS_DB_TO_UI = {
  emitido: 'Emitido', confirmado: 'Confirmado', em_transito: 'Em Trânsito', entregue: 'Entregue', cancelado: 'Cancelado',
};
const ORDER_STATUS_UI_TO_DB = {
  'Emitido': 'emitido', 'Confirmado': 'confirmado', 'Em Trânsito': 'em_transito', 'Entregue': 'entregue', 'Cancelado': 'cancelado',
};
const toUiOrder = (row) => ({
  id: row.id,
  code: row.code,
  total: Number(row.total) || 0,
  status: ORDER_STATUS_DB_TO_UI[row.status] || 'Emitido',
  status_db: row.status,
  emitted_at: row.emitted_at,
  eta_date: row.eta,
  emitido: row.emitted_at ? new Date(row.emitted_at).toLocaleDateString('pt-BR') : '—',
  eta: row.eta ? new Date(row.eta).toLocaleDateString('pt-BR') : '—',
  cotacao: row.quotation?.code || '—',
  quotation_id: row.quotation?.id || row.quotation_id,
  supplier: row.supplier?.name || '—',
  supplier_id: row.supplier?.id || row.supplier_id,
  supplier_obj: row.supplier,
  items: row.itemsCount,
});

function ScreenOrders({ setRoute, openQuotation }) {
  const { BRL } = window.SCP;
  const [filter, setFilter] = useState('todos');
  const [openOrder, setOpenOrder] = useState(null);
  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.orders.list();
        if (mounted) setRows(data.map(toUiOrder));
      } catch (e) {
        if (mounted) setLoadErr(e.message || 'Falha ao carregar pedidos');
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  const counts = useMemo(() => {
    const c = { todos: rows.length, 'Emitido': 0, 'Confirmado': 0, 'Em Trânsito': 0, 'Entregue': 0, 'Cancelado': 0 };
    rows.forEach(o => { if (c[o.status] !== undefined) c[o.status]++; });
    return c;
  }, [rows]);

  const filtered = rows.filter(o => filter === 'todos' || o.status === filter);

  const kpis = useMemo(() => {
    const monthNow = new Date().getMonth();
    const yearNow = new Date().getFullYear();
    const thisMonth = rows.filter(r => {
      if (!r.emitted_at) return false;
      const d = new Date(r.emitted_at);
      return d.getMonth() === monthNow && d.getFullYear() === yearNow;
    });
    const totalMes = thisMonth.reduce((s, r) => s + r.total, 0);
    const emTransito = counts['Em Trânsito'] + counts['Confirmado'];
    const todayStr = new Date().toISOString().slice(0, 10);
    const entregaHoje = rows.filter(r => r.eta_date === todayStr && (r.status === 'Em Trânsito' || r.status === 'Confirmado')).length;
    const atrasados = rows.filter(r => r.eta_date && r.eta_date < todayStr && r.status !== 'Entregue' && r.status !== 'Cancelado').length;
    const validOrders = rows.filter(r => r.status !== 'Cancelado');
    const ticketMedio = validOrders.length ? validOrders.reduce((s, r) => s + r.total, 0) / validOrders.length : 0;
    const itensMedio = validOrders.length ? validOrders.reduce((s, r) => s + (r.items || 0), 0) / validOrders.length : 0;
    return { totalMes, qtdMes: thisMonth.length, emTransito, entregaHoje, atrasados, ticketMedio, itensMedio };
  }, [rows, counts]);

  const updateStatus = async (order, newStatusUi) => {
    try {
      const newStatusDb = ORDER_STATUS_UI_TO_DB[newStatusUi];
      const updated = await window.scpDb.orders.updateStatus(order.id, newStatusDb);
      setRows(prev => prev.map(r => r.id === order.id ? toUiOrder({ ...updated, supplier: order.supplier_obj, quotation: { code: order.cotacao, id: order.quotation_id }, itemsCount: order.items }) : r));
      setOpenOrder(null);
      window.scpToast(`Pedido ${newStatusUi}`, { kind: 'emerald', sub: order.code });
    } catch (e) {
      window.scpToast('Erro ao atualizar', { kind: 'coral', sub: e.message });
    }
  };

  return (
    <div className="scp-screen scp-fade-in">
      <div className="scp-dash-grid">
        <Stat label="Pedidos do mês" value={String(kpis.qtdMes)} sub={`${BRL(kpis.totalMes)} em compras`} icon={<Icon.Order size={16}/>}/>
        <Stat label="Em trânsito" value={String(kpis.emTransito)} sub={`${kpis.entregaHoje} com entrega prevista hoje`} icon={<Icon.Truck size={16}/>} delta={kpis.emTransito > 0 ? 'acompanhar' : 'ok'} deltaTone={kpis.emTransito > 0 ? 'amber' : 'emerald'}/>
        <Stat label="Atrasados" value={String(kpis.atrasados)} delta={kpis.atrasados === 0 ? 'ok' : 'atenção'} deltaTone={kpis.atrasados === 0 ? 'emerald' : 'coral'} sub={kpis.atrasados === 0 ? 'Todos no prazo' : 'Verificar transportadora'} icon={<Icon.Check size={16}/>}/>
        <Stat label="Ticket médio" value={BRL(kpis.ticketMedio)} sub={`${kpis.itensMedio.toFixed(1).replace('.', ',')} itens por pedido`} icon={<Icon.Cart 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 pedidos:</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">
            {[['todos','Todos'],['Emitido','Emitido'],['Confirmado','Confirmado'],['Em Trânsito','Em Trânsito'],['Entregue','Entregue'],['Cancelado','Cancelado']].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 }}>
            <Btn kind="ghost" icon={<Icon.Download size={16}/>}>Exportar</Btn>
          </div>
        </div>

        <table className="scp-table">
          <thead>
            <tr>
              <th>Pedido</th>
              <th>Fornecedor</th>
              <th>Itens</th>
              <th style={{ textAlign: 'right' }}>Valor</th>
              <th>Status</th>
              <th>Emitido</th>
              <th>Previsão</th>
              <th>Cotação</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr><td colSpan={9} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)' }}>Carregando pedidos…</td></tr>
            )}
            {!loading && filtered.length === 0 && (
              <tr><td colSpan={9} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)' }}>
                {rows.length === 0 ? 'Nenhum pedido emitido ainda. Pedidos são criados automaticamente ao aprovar uma cotação.' : 'Nenhum pedido com este filtro.'}
              </td></tr>
            )}
            {!loading && filtered.map(o => {
              const tone = OSTATUS[o.status]?.tone || 'muted';
              return (
                <tr key={o.id} className="clickable" onClick={() => setOpenOrder(o)}>
                  <td className="em num">{o.code}</td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Avatar name={o.supplier} size={26}/>
                      <span>{o.supplier}</span>
                    </div>
                  </td>
                  <td className="num">{o.items}</td>
                  <td className="num em" style={{ textAlign: 'right' }}>{BRL(o.total)}</td>
                  <td><Badge tone={tone}>{o.status}</Badge></td>
                  <td className="num" style={{ color: 'var(--fg-3)' }}>{o.emitido}</td>
                  <td className="num">{o.eta}</td>
                  <td className="num" style={{ color: 'var(--fg-3)' }}>{o.cotacao}</td>
                  <td onClick={e => e.stopPropagation()}>
                    <div style={{ display: 'flex', gap: 4 }}>
                      <IconBtn icon={<Icon.Eye size={14}/>} size="sm" kind="ghost" title="Visualizar" onClick={() => setOpenOrder(o)}/>
                      <IconBtn icon={<Icon.Download size={14}/>} size="sm" kind="ghost" title="PDF"/>
                      <IconBtn icon={<Icon.WhatsApp size={14}/>} size="sm" kind="ghost" title="WhatsApp"/>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      {/* Live tracking timeline */}
      <Card style={{ padding: 22 }}>
        <SectionHead title="Rastreio em tempo real" sub="Pedidos em trânsito · clique para detalhes" right={<Pill tone="amber">{kpis.emTransito} em trânsito</Pill>}/>
        <div className="scp-track-list">
          {rows.filter(o => o.status === 'Em Trânsito' || o.status === 'Confirmado').length === 0 && (
            <div className="scp-detail-empty" style={{ padding: 20 }}>Nenhum pedido em trânsito no momento.</div>
          )}
          {rows.filter(o => o.status === 'Em Trânsito' || o.status === 'Confirmado').map(o => (
            <div key={o.id} className="scp-track clickable" onClick={() => setOpenOrder(o)} role="button" tabIndex={0}>
              <div className="head">
                <Avatar name={o.supplier} size={26}/>
                <span className="t"><strong>{o.supplier}</strong> · {o.code}</span>
                <Pill tone={o.status === 'Em Trânsito' ? 'amber' : 'violet'}>{o.status}</Pill>
                <span className="eta num">ETA {o.eta}</span>
              </div>
              <div className="bar">
                {['Emitido', 'Confirmado', 'Em Trânsito', 'Entregue'].map((stage, i) => {
                  const idx = ['Emitido', 'Confirmado', 'Em Trânsito', 'Entregue'].indexOf(o.status);
                  return (
                    <div key={stage} className={cls('stage', i <= idx && 'done', i === idx && 'current')}>
                      <span className="dot"/>
                      <span className="l">{stage}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Drawer
        open={!!openOrder}
        onClose={() => setOpenOrder(null)}
        eyebrow={openOrder?.code}
        title={openOrder ? `Pedido para ${openOrder.supplier}` : ''}
        headerRight={openOrder && <Badge tone={OSTATUS[openOrder.status]?.tone || 'muted'}>{openOrder.status}</Badge>}
        footer={openOrder && (
          <>
            <Btn kind="ghost" icon={<Icon.WhatsApp size={14}/>} onClick={() => {
              const num = (openOrder.supplier_obj?.whatsapp || '').replace(/\D/g, '');
              if (num) window.open(`https://wa.me/55${num}?text=${encodeURIComponent('Olá! Sobre o pedido ' + openOrder.code)}`, '_blank', 'noopener');
              else window.scpToast('Fornecedor sem WhatsApp cadastrado', { kind: 'amber' });
            }}>WhatsApp</Btn>
            <Btn kind="secondary" icon={<Icon.Download size={14}/>} onClick={() => window.scpToast('Gerando PDF do pedido', { kind: 'sky', sub: openOrder.code + ' · download em ~3s' })}>Baixar PDF</Btn>
            {openOrder.status === 'Emitido' && (
              <Btn kind="secondary" icon={<Icon.Check size={14}/>} onClick={() => updateStatus(openOrder, 'Confirmado')}>Marcar Confirmado</Btn>
            )}
            {openOrder.status === 'Confirmado' && (
              <Btn kind="secondary" icon={<Icon.Truck size={14}/>} onClick={() => updateStatus(openOrder, 'Em Trânsito')}>Marcar em Trânsito</Btn>
            )}
            {openOrder.status === 'Em Trânsito' && (
              <Btn kind="secondary" icon={<Icon.Check size={14}/>} onClick={() => updateStatus(openOrder, 'Entregue')}>Marcar Entregue</Btn>
            )}
            <Btn kind="primary" icon={<Icon.Eye size={14}/>} onClick={() => {
              if (openOrder.quotation_id && openQuotation) {
                openQuotation(openOrder.quotation_id);
                setOpenOrder(null);
              } else if (setRoute) {
                setRoute('quotations');
                setOpenOrder(null);
              }
            }}>Ver cotação</Btn>
          </>
        )}
      >
        {openOrder && <OrderDetail order={openOrder} />}
      </Drawer>
    </div>
  );
}

function OrderDetail({ order: o }) {
  const { BRL } = window.SCP;
  const supplier = o.supplier_obj;
  const [orderItems, setOrderItems] = useState(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const full = await window.scpDb.orders.getById(o.id);
        if (mounted) setOrderItems(full.items || []);
      } catch (e) {
        if (mounted) setOrderItems([]);
      }
    })();
    return () => { mounted = false; };
  }, [o.id]);

  const stages = ['Emitido', 'Confirmado', 'Em Trânsito', 'Entregue'];
  const idx = o.status === 'Cancelado' ? -1 : stages.indexOf(o.status);
  const cancelled = o.status === 'Cancelado';

  return (
    <>
      <div className="scp-detail-hero" style={{ background: 'oklch(0.20 0.012 250 / .5)', border: '1px solid var(--border-soft)' }}>
        <Avatar name={o.supplier} size={52}/>
        <div style={{ minWidth: 0 }}>
          <div className="name">{o.supplier}</div>
          <div className="meta">{o.code} · emitido em {o.emitido}</div>
        </div>
      </div>

      <div className="scp-detail-section">
        <h4>Resumo</h4>
        <div className="scp-detail-metrics">
          <div className="scp-detail-metric">
            <span className="l">Valor total</span>
            <span className="v em">{BRL(o.total)}</span>
            <span className="s">{o.items} itens no pedido</span>
          </div>
          <div className="scp-detail-metric">
            <span className="l">Previsão</span>
            <span className="v">{o.eta}</span>
            <span className="s">Entrega ao restaurante</span>
          </div>
        </div>
      </div>

      <div className="scp-detail-section">
        <h4>Rastreio</h4>
        <div className="scp-track" style={{ background: 'var(--surface-2)' }}>
          <div className="bar">
            {stages.map((stage, i) => (
              <div key={stage} className={cls('stage', !cancelled && i <= idx && 'done', !cancelled && i === idx && 'current')}>
                <span className="dot"/>
                <span className="l">{stage}</span>
              </div>
            ))}
          </div>
          {cancelled && (
            <div style={{ marginTop: 12, padding: '8px 12px', background: 'oklch(0.28 0.08 25 / .4)', border: '1px solid oklch(0.42 0.10 25)', borderRadius: 8, fontSize: 12.5, color: 'oklch(0.88 0.14 25)' }}>
              Pedido cancelado
            </div>
          )}
        </div>
      </div>

      <div className="scp-detail-section">
        <h4>Itens do pedido</h4>
        {orderItems === null ? (
          <div className="scp-detail-empty">Carregando itens…</div>
        ) : orderItems.length ? (
          <div className="scp-detail-list">
            {orderItems.map(it => (
              <div key={it.id} className="scp-detail-list-row">
                <div>
                  <div className="n">{it.name_snapshot}</div>
                  <div className="s">{Number(it.qty)} {it.unit_snapshot || ''} · unit. {BRL(it.unit_price)}</div>
                </div>
                <span className="v">{BRL(Number(it.qty) * Number(it.unit_price))}</span>
              </div>
            ))}
          </div>
        ) : (
          <div className="scp-detail-empty">Sem itens registrados.</div>
        )}
      </div>

      <div className="scp-detail-section">
        <h4>Dados do pedido</h4>
        <dl className="scp-detail-kv">
          <dt>Código</dt><dd className="num">{o.code}</dd>
          <dt>Fornecedor</dt><dd>{o.supplier}</dd>
          <dt>Itens</dt><dd className="num">{o.items}</dd>
          <dt>Valor</dt><dd className="num">{BRL(o.total)}</dd>
          <dt>Emitido em</dt><dd className="num">{o.emitido}</dd>
          <dt>Previsão</dt><dd className="num">{o.eta}</dd>
          <dt>Cotação origem</dt><dd className="num">{o.cotacao}</dd>
        </dl>
      </div>

      {supplier && (
        <div className="scp-detail-section">
          <h4>Sobre o fornecedor</h4>
          <div className="scp-detail-metrics">
            <div className="scp-detail-metric">
              <span className="l">Score</span>
              <span className="v em">{supplier.score}</span>
            </div>
            <div className="scp-detail-metric">
              <span className="l">Cidade</span>
              <span className="v" style={{ fontSize: 14 }}>{supplier.city || '—'}</span>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

(function() {
  if (document.getElementById('scp-orders-css')) return;
  const s = document.createElement('style'); s.id = 'scp-orders-css';
  s.textContent = `
    .scp-track-list { display: flex; flex-direction: column; gap: 14px; margin-top: 6px; }
    .scp-track { padding: 14px 16px; border-radius: 12px; background: var(--surface-2); border: 1px solid var(--border-soft); transition: background .12s, border-color .12s; }
    .scp-track.clickable { cursor: pointer; }
    .scp-track.clickable:hover { background: var(--surface-3); border-color: var(--border); }
    .scp-track .head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 14px; }
    .scp-track .head .t { font-size: 13px; color: var(--fg-2); flex: 1; min-width: 0; }
    .scp-track .head .t strong { color: var(--fg); font-weight: 600; }
    .scp-track .head .eta { font-size: 12px; color: var(--fg-3); font-family: 'JetBrains Mono', monospace; }
    .scp-track .bar { display: grid; grid-template-columns: repeat(4, 1fr); position: relative; }
    .scp-track .bar::before {
      content: ""; position: absolute; left: 8px; right: 8px; top: 7px;
      height: 2px; background: var(--border);
    }
    .scp-track .stage { display: flex; flex-direction: column; align-items: center; gap: 6px; position: relative; z-index: 1; }
    .scp-track .stage .dot { width: 16px; height: 16px; border-radius: 999px; background: var(--surface-3); border: 2px solid var(--border); }
    .scp-track .stage.done .dot { background: oklch(0.74 0.16 160); border-color: oklch(0.74 0.16 160); }
    .scp-track .stage.current .dot { box-shadow: 0 0 0 4px oklch(0.74 0.16 160 / .25); animation: pulseDot 1.4s ease-in-out infinite; }
    @keyframes pulseDot { 50% { box-shadow: 0 0 0 8px oklch(0.74 0.16 160 / .12); } }
    .scp-track .stage .l { font-size: 10.5px; color: var(--fg-4); text-transform: uppercase; letter-spacing: .08em; font-weight: 600; }
    .scp-track .stage.done .l { color: var(--fg-2); }
    .scp-track .stage.current .l { color: oklch(0.92 0.14 160); }
  `;
  document.head.appendChild(s);
})();

window.ScreenOrders = ScreenOrders;
