/**
 * TrendApp — Vendas (§10)
 *
 * Layout:
 *  1. Resumo do mês (Fat. pago, Pedidos, Ticket pago, Clientes únicos)
 *  2. Evolução diária (30d, Recharts)
 *  3. Lista de pedidos (com filtros por chips)
 *
 * NÃO exibir: meta individual, margem, custos, imposto, frete,
 * comissão como KPI principal, prescritor.
 */

// (React hooks declarados uma vez em logo.jsx)

function VendasScreen({ payload }) {
  const { go } = useRouter();
  const { tweaks } = useTweaks();
  useLucide([payload]);
  const fmt = window.TrendFmt;

  const { kpisMeuMes, pedidos, diario30d, evolucao12M, loading, error, comissao } = payload;
  const [filtro, setFiltro] = useState('todos');
  const [periodo, setPeriodo] = useState('mes');   // 'mes' | '3m' | '6m'

  const filtrado = useMemo(() => {
    if (filtro === 'todos') return pedidos;
    if (filtro === 'prioritarios') return pedidos.filter(p => p.motivo != null);
    return pedidos.filter(p => p.status === FILTRO_STATUS_MAP[filtro]);
  }, [pedidos, filtro]);

  // Agregado do período selecionado (usa evolucao12M como fonte histórica)
  const agregadoPeriodo = useMemo(() => {
    const meses = evolucao12M || [];
    const n = periodo === 'mes' ? 1 : periodo === '3m' ? 3 : 6;
    const ultimos = meses.slice(-n);
    const somaValor = ultimos.reduce((s, m) => s + (m.valor_pago || 0), 0);
    return { meses: ultimos, somaValor, n };
  }, [evolucao12M, periodo]);

  const totalPago = useMemo(() => {
    if (periodo === 'mes') return pedidos.filter(p => p.status !== 'Cancelado').reduce((s, p) => s + p.valor_pago, 0);
    return agregadoPeriodo.somaValor;
  }, [pedidos, periodo, agregadoPeriodo]);
  const pedidosMes = pedidos.filter(p => p.status !== 'Cancelado').length;
  // Simulação: extrapolar pedidos/ticket para o período selecionado (proporcional ao valor)
  const fatorPeriodo = periodo === 'mes' ? 1 : periodo === '3m' ? 3 : 6;
  const pedidosPeriodo = pedidosMes * fatorPeriodo - (periodo !== 'mes' ? Math.round(pedidosMes * 0.15) : 0);
  const clientesUnicos = useMemo(() => new Set(pedidos.map(p => p.cliente_id)).size, [pedidos]);
  const clientesUnicosPeriodo = periodo === 'mes' ? clientesUnicos : Math.min(clientesUnicos * fatorPeriodo - fatorPeriodo, 15);
  const ticketPago = pedidosPeriodo > 0 ? totalPago / pedidosPeriodo : null;

  // KPIs de evolução (12M)
  const evolucaoKPIs = useMemo(() => {
    const m = evolucao12M || [];
    if (m.length === 0) return null;
    const melhor = m.reduce((max, cur) => cur.valor_pago > max.valor_pago ? cur : max, m[0]);
    const media = m.reduce((s, c) => s + c.valor_pago, 0) / m.length;
    // Tendência 3M vs 3M anterior
    const ultimos3 = m.slice(-3).reduce((s, c) => s + c.valor_pago, 0) / 3;
    const anteriores3 = m.slice(-6, -3).reduce((s, c) => s + c.valor_pago, 0) / 3;
    const tendencia = anteriores3 > 0 ? (ultimos3 - anteriores3) / anteriores3 : null;
    // YTD (Jan até mês atual = últimos 8 meses considerando ago/26)
    const ytd = m.slice(-8).reduce((s, c) => s + c.valor_pago, 0);
    return { melhor, media, tendencia, ytd };
  }, [evolucao12M]);

  const periodoLabel = periodo === 'mes' ? fmt.fmtCompetencia(comissao.competencia)
    : periodo === '3m' ? 'Últimos 3 meses'
    : 'Últimos 6 meses';

  return (
    <div className="page tab-fade">
      <div className="page-body" style={{ paddingTop: 0 }}>
        <HeroHeader
          eyebrow={fmt.fmtCompetencia(comissao.competencia)}
          title="Vendas"
          subtitle="Desempenho e evolução da sua carteira."
          minHeight={220}
          action={{
            icon: 'sliders-horizontal',
            ariaLabel: 'Filtros',
            onClick: () => alert('Filtros — apenas visual no protótipo'),
          }}
        />

        {/* Chips de período — sticky logo abaixo do hero */}
        <div style={{ padding: '4px 20px 0' }}>
          <div style={{
            display: 'flex', gap: 0,
            borderBottom: '1px solid var(--border)',
          }}>
            {[
              { id: 'mes', label: 'Mês atual' },
              { id: '3m',  label: '3M' },
              { id: '6m',  label: '6M' },
            ].map(p => (
              <button
                key={p.id}
                data-active={periodo === p.id ? 'true' : 'false'}
                onClick={() => setPeriodo(p.id)}
                style={{
                  padding: '14px 4px',
                  marginRight: 24,
                  fontSize: 13,
                  fontWeight: 500,
                  color: periodo === p.id ? 'var(--foreground)' : 'var(--muted-foreground)',
                  background: 'transparent',
                  whiteSpace: 'nowrap',
                  borderBottom: periodo === p.id ? '1.5px solid var(--foreground)' : '1.5px solid transparent',
                  marginBottom: '-1px',
                  transition: 'color 120ms ease, border-color 120ms ease',
                }}
              >{p.label}</button>
            ))}
          </div>
        </div>

        <div className="stack" style={{ paddingTop: 8 }}>
          {error && <ErrorBanner onRetry={() => location.reload()} />}

          {/* 1. Resumo do período */}
          <Section title="Resumo" description={periodoLabel}>
            {loading ? (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {Array.from({ length: 4 }).map((_, i) => <SkelCard key={i} h={92} />)}
              </div>
            ) : (
              <KpiGrid>
                <KpiCell label={periodo === 'mes' ? 'Faturamento pago' : 'Faturamento total'} value={fmt.fmtBRL(totalPago, { showCents: false })} delta={periodo === 'mes' ? kpisMeuMes.fatLiquidoDelta : null} />
                <KpiCell label="Pedidos"        value={fmt.fmtInt(pedidosPeriodo)} delta={periodo === 'mes' ? kpisMeuMes.pedidosDelta : null} />
                <KpiCell label="Ticket médio"   value={fmt.fmtBRL(ticketPago, { showCents: false })} delta={periodo === 'mes' ? kpisMeuMes.ticketMedioDelta : null} />
                <KpiCell label="Clientes únicos" value={fmt.fmtInt(clientesUnicosPeriodo)} delta={periodo === 'mes' ? kpisMeuMes.clientesUnicosDelta : null} />
              </KpiGrid>
            )}
          </Section>

          {/* 2. Evolução diária (só no modo mês) */}
          {periodo === 'mes' && (
            <Section title="Evolução diária" description="Últimos 30 dias — valor pago">
              {loading ? <SkelCard h={220} /> : (
                diario30d.length === 0 || diario30d.every(d => d.valor_pago === 0) ? (
                  <div className="card">
                    <EmptyState icon="bar-chart-3" title="Sem movimento no período" description="Registre um pedido para começar a acompanhar sua evolução." />
                  </div>
                ) : (
                  <DiarioChart data={diario30d} />
                )
              )}
            </Section>
          )}

          {/* 3. Histórico 12M mensal */}
          <Section title="Evolução mensal" description="Últimos 12 meses — valor pago">
            {loading ? <SkelCard h={220} /> : (
              !evolucao12M || evolucao12M.length === 0 ? (
                <div className="card">
                  <EmptyState icon="line-chart" title="Sem histórico" description="Ainda não há dados dos meses anteriores." />
                </div>
              ) : (
                <MensalChart data={evolucao12M} periodo={periodo} />
              )
            )}
          </Section>

          {/* 4. Sua evolução — KPIs consolidados */}
          {evolucaoKPIs && (
            <Section title="Sua evolução" description="Consolidado dos últimos 12 meses">
              <KpiGrid>
                <KpiCell label="Melhor mês"    value={fmt.fmtBRL(evolucaoKPIs.melhor.valor_pago, { showCents: false })} hint={evolucaoKPIs.melhor.mes} />
                <KpiCell label="Média mensal"  value={fmt.fmtBRL(evolucaoKPIs.media, { showCents: false })} />
                <KpiCell label="Tendência 3M"  value={evolucaoKPIs.tendencia != null ? `${evolucaoKPIs.tendencia > 0 ? '+' : ''}${(evolucaoKPIs.tendencia * 100).toFixed(1).replace('.', ',')}%` : '—'} hint="vs. 3M anteriores" />
                <KpiCell label="YTD"           value={fmt.fmtBRL(evolucaoKPIs.ytd, { showCents: false })} hint="ano até agora" />
              </KpiGrid>
            </Section>
          )}

          {/* 3. Lista de pedidos */}
          <Section title="Lista de pedidos" description={loading ? '' : `${filtrado.length} ${filtrado.length === 1 ? 'pedido' : 'pedidos'}`}>
            {/* Chips */}
            <div style={{ marginLeft: -20, marginRight: -20 }}>
              <div className="chips" style={{ padding: '2px 20px 8px' }}>
                {FILTROS.map(f => (
                  <button
                    key={f.id}
                    className="chip"
                    data-active={filtro === f.id ? 'true' : 'false'}
                    onClick={() => setFiltro(f.id)}
                  >
                    {f.label}
                    {f.id === 'prioritarios' && pedidos.filter(p => p.motivo != null).length > 0 && (
                      <span style={{
                        marginLeft: 4,
                        padding: '0 5px', borderRadius: 999,
                        background: filtro === 'prioritarios' ? 'var(--background)' : 'var(--destructive)',
                        color: filtro === 'prioritarios' ? 'var(--foreground)' : '#fff',
                        fontSize: 10, fontWeight: 700,
                      }}>{pedidos.filter(p => p.motivo != null).length}</span>
                    )}
                  </button>
                ))}
              </div>
            </div>

            {loading ? (
              <div>
                <SkelCard h={80} /><SkelCard h={80} /><SkelCard h={80} />
              </div>
            ) : filtrado.length === 0 ? (
              <div className="card">
                <EmptyState
                  icon="package-open"
                  title="Nenhum pedido neste filtro"
                  description="Tente alterar o filtro ou o período."
                />
              </div>
            ) : (
              <div>
                {filtrado.map(p => (
                  <PedidoRow key={p.pedido} p={p} onClick={() => go(`/pedido/${p.pedido}`)} showRastreio={tweaks.showRastreio} />
                ))}
              </div>
            )}
          </Section>
        </div>
      </div>
    </div>
  );
}

const FILTROS = [
  { id: 'todos',            label: 'Todos' },
  { id: 'prioritarios',     label: 'Prioritários' },
  { id: 'aguardando_envio', label: 'Aguardando Envio' },
  { id: 'enviado',          label: 'Enviado' },
  { id: 'entrada_farmacia', label: 'Entrada Farmácia' },
  { id: 'entregue',         label: 'Entregue' },
];
const FILTRO_STATUS_MAP = {
  aguardando_envio: 'Aguardando Envio',
  enviado:          'Enviado',
  entrada_farmacia: 'Entrada Farmácia',
  entregue:         'Entregue',
};

// ─── Pedido row — editorial hairline ───────────────────────────────────
function PedidoRow({ p, onClick, showRastreio = true }) {
  const fmt = window.TrendFmt;
  const motivo = p.motivo ? window.TrendMocks.MOTIVOS[p.motivo] : null;
  const statusColor = {
    'Aguardando Envio':         'oklch(0.75 0.14 75)',
    'Enviado':                  'var(--accent-fg)',
    'Entrada Farmácia':         'var(--accent-fg)',
    'Entregue':                 'oklch(0.55 0.12 155)',
    'Receita Pendente':         'oklch(0.62 0.20 25)',
    'Conferência farmacêutica': 'oklch(0.75 0.14 75)',
    'Cancelado':                'var(--muted-foreground)',
  }[p.status];
  return (
    <div
      className="hairline-row"
      style={{ alignItems: 'flex-start', paddingTop: 16, paddingBottom: 16 }}
      onClick={onClick}
      role="button" tabIndex={0}
    >
      {motivo && (
        <span aria-hidden="true" style={{
          marginTop: 6, flexShrink: 0,
          width: 6, height: 6, borderRadius: 999,
          background: 'oklch(0.62 0.20 25)',
        }} />
      )}
      {!motivo && (
        <span aria-hidden="true" style={{
          marginTop: 8, flexShrink: 0,
          width: 6, height: 6, borderRadius: 999,
          background: statusColor,
          opacity: 0.7,
        }} />
      )}
      <div className="grow" style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'baseline', flexWrap: 'wrap' }}>
          <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--foreground)' }}>{p.pedido}</span>
          <span style={{ fontSize: 12, color: 'var(--muted-foreground)' }}>{p.status}</span>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--muted-foreground)', marginTop: 4 }} className="truncate">
          {p.cliente} · {fmt.fmtDate(p.data, { compact: true })} · {p.itens} {p.itens === 1 ? 'item' : 'itens'}
        </div>
        {motivo && (
          <div style={{ fontSize: 12.5, color: 'var(--muted-foreground)', marginTop: 4 }}>
            {motivo.msg}
          </div>
        )}
        {showRastreio && p.rastreio && !motivo && (
          <div style={{ fontSize: 11.5, color: 'var(--muted-foreground)', marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>
            {p.rastreio}
          </div>
        )}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, flexShrink: 0 }}>
        <div className="tabnum" style={{ fontSize: 14, fontWeight: 500, color: 'var(--foreground)' }}>
          {p.status === 'Cancelado' ? '—' : fmt.fmtBRL(p.valor_pago, { showCents: false })}
        </div>
        {p.comissao != null && p.status !== 'Cancelado' && (
          <div style={{ fontSize: 11, color: 'var(--muted-foreground)' }}>
            +<span className="tabnum">{fmt.fmtBRL(p.comissao, { showCents: false })}</span>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Diario chart (Recharts) ───────────────────────────────────────────────
// ─── MensalChart — histórico 12 meses (área) ─────────────────────────────
function MensalChart({ data, periodo }) {
  if (!window.Recharts) return <SkelCard h={220} />;
  const { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid } = window.Recharts;
  const fmt = window.TrendFmt;
  // Highlight últimos N meses conforme período selecionado
  const highlightN = periodo === '3m' ? 3 : periodo === '6m' ? 6 : 1;
  const highlighted = data.map((d, i) => ({
    ...d,
    isHighlight: i >= data.length - highlightN,
  }));

  return (
    <div style={{ marginLeft: -8 }}>
      <div style={{ width: '100%', height: 200 }}>
        <ResponsiveContainer>
          <AreaChart data={highlighted} margin={{ top: 10, right: 8, left: -18, bottom: 0 }}>
            <defs>
              <linearGradient id="areaFill12M" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="var(--foreground)" stopOpacity={0.28} />
                <stop offset="100%" stopColor="var(--foreground)" stopOpacity={0.02} />
              </linearGradient>
            </defs>
            <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" vertical={false} />
            <XAxis
              dataKey="mes"
              tickLine={false}
              axisLine={false}
              tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }}
              interval={1}
            />
            <YAxis
              tickLine={false}
              axisLine={false}
              tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }}
              tickFormatter={(v) => v >= 1000 ? `${(v/1000).toFixed(0)}k` : v.toString()}
              width={40}
            />
            <Tooltip
              contentStyle={{
                background: 'var(--popover)', color: 'var(--popover-foreground)',
                border: '1px solid var(--border)', borderRadius: 10, fontSize: 12,
              }}
              formatter={(v) => [fmt.fmtBRL(v, { showCents: false }), 'Valor pago']}
              labelStyle={{ color: 'var(--muted-foreground)', fontSize: 11 }}
              cursor={{ stroke: 'var(--border)', strokeWidth: 1 }}
            />
            <Area
              type="monotone"
              dataKey="valor_pago"
              stroke="var(--foreground)"
              strokeWidth={1.75}
              fill="url(#areaFill12M)"
              activeDot={{ r: 4, fill: 'var(--foreground)' }}
              dot={(props) => {
                const { cx, cy, index } = props;
                if (index === data.length - 1) {
                  return (
                    <circle cx={cx} cy={cy} r={4} fill="var(--foreground)" />
                  );
                }
                return null;
              }}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

function DiarioChart({ data }) {
  if (!window.Recharts) return <SkelCard h={220} />;
  const { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid } = window.Recharts;
  const fmt = window.TrendFmt;
  const total = data.reduce((s, d) => s + d.valor_pago, 0);
  const nonZero = data.filter(d => d.valor_pago > 0);
  const media = nonZero.length > 0 ? total / nonZero.length : 0;
  const melhor = data.reduce((max, d) => d.valor_pago > max.valor_pago ? d : max, data[0]);

  return (
    <div style={{ marginLeft: -8 }}>
      <div style={{ width: '100%', height: 180 }}>
        <ResponsiveContainer>
          <BarChart data={data} margin={{ top: 10, right: 8, left: -18, bottom: 0 }}>
            <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" vertical={false} />
            <XAxis
              dataKey="dia"
              tickLine={false}
              axisLine={false}
              tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }}
              interval={4}
            />
            <YAxis
              tickLine={false}
              axisLine={false}
              tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }}
              tickFormatter={(v) => v >= 1000 ? `${(v/1000).toFixed(0)}k` : v.toString()}
              width={40}
            />
            <Tooltip
              contentStyle={{
                background: 'var(--popover)', color: 'var(--popover-foreground)',
                border: '1px solid var(--border)', borderRadius: 10, fontSize: 12,
              }}
              formatter={(v) => [fmt.fmtBRL(v, { showCents: false }), 'Valor pago']}
              labelStyle={{ color: 'var(--muted-foreground)', fontSize: 11 }}
              cursor={{ fill: 'color-mix(in oklch, var(--primary) 6%, transparent)' }}
            />
            <Bar dataKey="valor_pago" fill="var(--primary)" radius={[3, 3, 0, 0]} maxBarSize={12} />
          </BarChart>
        </ResponsiveContainer>
      </div>
      <div style={{
        display: 'flex', gap: 20, padding: '10px 12px 4px',
        borderTop: '1px solid var(--border)', marginTop: 4,
      }}>
        <div>
          <div className="eyebrow" style={{ fontSize: 10 }}>Média diária</div>
          <div className="tabnum" style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>{fmt.fmtBRL(media, { showCents: false })}</div>
        </div>
        <div>
          <div className="eyebrow" style={{ fontSize: 10 }}>Melhor dia</div>
          <div className="tabnum" style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>
            {melhor?.valor_pago > 0 ? fmt.fmtBRL(melhor.valor_pago, { showCents: false }) : '—'}
          </div>
          {melhor?.valor_pago > 0 && (
            <div style={{ fontSize: 10, color: 'var(--muted-foreground)' }}>{melhor.dia}</div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Lista de pedidos (rota /pedidos com filtro inicial ?filtro=prioritarios) ─
function PedidosListScreen({ payload }) {
  const { back, go, route } = useRouter();
  const { tweaks } = useTweaks();
  useLucide();
  const filtroInicial = useMemo(() => {
    const q = location.hash.split('?')[1] || '';
    const p = new URLSearchParams(q);
    return p.get('filtro') || 'todos';
  }, [location.hash]);
  const [filtro, setFiltro] = useState(filtroInicial);
  const { pedidos } = payload;
  const filtrado = useMemo(() => {
    if (filtro === 'todos') return pedidos;
    if (filtro === 'prioritarios') return pedidos.filter(p => p.motivo != null);
    return pedidos.filter(p => p.status === FILTRO_STATUS_MAP[filtro]);
  }, [pedidos, filtro]);

  return (
    <div className="page page-enter">
      <PageHeader title="Pedidos" subtitle={`${filtrado.length} ${filtrado.length === 1 ? 'pedido' : 'pedidos'}`} back={() => back('/vendas')} />
      <div style={{ borderBottom: '1px solid var(--border)' }}>
        <div className="chips" style={{ padding: '8px 20px' }}>
          {FILTROS.map(f => (
            <button
              key={f.id} className="chip"
              data-active={filtro === f.id ? 'true' : 'false'}
              onClick={() => setFiltro(f.id)}
            >{f.label}</button>
          ))}
        </div>
      </div>
      <div className="page-body">
        <div className="stack">
          {filtrado.length === 0 ? (
            <div className="card">
              <EmptyState icon="package-open" title="Sem pedidos" description="Nada por aqui neste filtro." />
            </div>
          ) : (
            filtrado.map(p => <PedidoRow key={p.pedido} p={p} onClick={() => go(`/pedido/${p.pedido}`)} showRastreio={tweaks.showRastreio} />)
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Detalhe do pedido ─────────────────────────────────────────────────────
function PedidoDetalheScreen({ payload }) {
  const { back, go, route } = useRouter();
  const [ajudaOpen, setAjudaOpen] = useState(false);
  useLucide([route]);
  const fmt = window.TrendFmt;

  const id = route.params[0];
  const pedido = payload.pedidos.find(p => p.pedido === id);

  if (!pedido) {
    return (
      <div className="page page-enter">
        <PageHeader title="Pedido não encontrado" back={() => back('/vendas')} />
        <div className="page-body">
          <div className="stack">
            <EmptyState icon="search-x" title="Pedido não encontrado" description="Talvez o número tenha mudado ou o pedido tenha sido removido." />
          </div>
        </div>
      </div>
    );
  }

  const motivo = pedido.motivo ? window.TrendMocks.MOTIVOS[pedido.motivo] : null;
  const cliente = payload.clientes.find(c => c.cliente_id === pedido.cliente_id);
  const itens = pedido.itensDetalhe || [];
  const subtotal = itens.reduce((s, it) => s + it.subtotal, 0);

  return (
    <div className="page page-enter">
      <div className="page-body" style={{ paddingTop: 0 }}>
        {/* HeroHeader dark premium */}
        <HeroHeader
          eyebrow={pedido.status}
          title={pedido.pedido}
          subtitle={`${fmt.fmtDate(pedido.data)} · ${cliente?.nome || 'Cliente'}`}
          minHeight={220}
          action={{
            icon: 'arrow-left',
            ariaLabel: 'Voltar',
            onClick: () => back('/vendas'),
          }}
        >
          {/* Valor pago gigante no hero */}
          <div style={{ marginTop: 4 }}>
            <div style={{
              fontSize: 10.5, fontWeight: 400,
              letterSpacing: '0.14em', textTransform: 'uppercase',
              color: 'rgba(245,247,247,0.55)',
              marginBottom: 8,
            }}>{pedido.status === 'Cancelado' ? 'Cancelado' : 'Valor pago'}</div>
            <div style={{
              display: 'flex', alignItems: 'baseline', gap: 4,
              fontVariantNumeric: 'tabular-nums',
            }}>
              <span style={{
                fontSize: 18, fontWeight: 300,
                color: 'rgba(245,247,247,0.55)',
                marginRight: 4,
              }}>R$</span>
              <span style={{
                fontSize: 42, fontWeight: 300,
                letterSpacing: '-0.045em',
                lineHeight: 1,
                color: '#F5F7F7',
              }}>{pedido.status === 'Cancelado' ? '—' : fmt.fmtBRLParts(pedido.valor_pago).int}</span>
              {pedido.status !== 'Cancelado' && (
                <span style={{
                  fontSize: 20, fontWeight: 300,
                  color: 'rgba(245,247,247,0.55)',
                  letterSpacing: '-0.02em',
                }}>{fmt.fmtBRLParts(pedido.valor_pago).dec}</span>
              )}
            </div>
            {pedido.comissao != null && pedido.status !== 'Cancelado' && (
              <div style={{ marginTop: 10, fontSize: 12.5, color: 'rgba(245,247,247,0.65)' }}>
                Comissão · <span style={{ color: '#F5F7F7', fontWeight: 500 }}>{fmt.fmtBRL(pedido.comissao)}</span>
              </div>
            )}
          </div>
        </HeroHeader>

        <div className="stack" style={{ paddingTop: 8 }}>
          {/* Alerta motivo */}
          {motivo && (
            <div style={{
              padding: '14px 0',
              borderBottom: '1px solid var(--border)',
              display: 'flex', gap: 10, alignItems: 'flex-start',
              fontSize: 13,
            }}>
              <span aria-hidden="true" style={{
                marginTop: 6, flexShrink: 0,
                width: 6, height: 6, borderRadius: 999,
                background: 'oklch(0.62 0.20 25)',
              }} />
              <div>
                <div style={{ fontWeight: 500, color: 'oklch(0.55 0.18 25)' }}>Requer atenção</div>
                <div style={{ color: 'var(--muted-foreground)', marginTop: 2 }}>{motivo.msg}</div>
              </div>
            </div>
          )}

          {/* Cliente */}
          {cliente && (
            <Section title="Cliente">
              <div
                className="hairline-row"
                onClick={() => go(`/cliente/${cliente.cliente_id}`)}
                role="button" tabIndex={0}
              >
                <Initials name={cliente.nome} size={40} />
                <div className="grow" style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500 }} className="truncate">{cliente.nome}</div>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 4 }}>
                    <FarolPill farol={cliente.farol} size="sm" />
                    <span style={{ fontSize: 11.5, color: 'var(--muted-foreground)' }}>RFM {cliente.rfm}</span>
                  </div>
                </div>
                <Icon name="arrow-right" size={14} color="var(--muted-foreground)" strokeWidth={1.5} />
              </div>
            </Section>
          )}

          {/* Composição de itens */}
          {itens.length > 0 && (
            <Section title="Composição do pedido" description={`${itens.length} ${itens.length === 1 ? 'SKU' : 'SKUs'}`}>
              <div>
                {itens.map((it, i) => (
                  <ItemPedidoRow key={i} item={it} />
                ))}
              </div>
              <div style={{
                paddingTop: 14, marginTop: 4,
                borderTop: '1px solid var(--border)',
                display: 'flex', justifyContent: 'space-between',
                fontSize: 14,
              }}>
                <span style={{ color: 'var(--muted-foreground)' }}>Total do pedido</span>
                <span className="tabnum" style={{ fontWeight: 500, color: 'var(--foreground)' }}>
                  {fmt.fmtBRL(subtotal)}
                </span>
              </div>
            </Section>
          )}

          {/* Detalhes */}
          <Section title="Detalhes">
            <div>
              <FieldRow label="Número"  value={pedido.pedido} />
              <FieldRow label="Data"    value={fmt.fmtDate(pedido.data)} />
              <FieldRow label="Itens"   value={`${pedido.itens} ${pedido.itens === 1 ? 'item' : 'itens'}`} />
              <FieldRow label="Status atual" value={pedido.status} mono={false} />
              {pedido.rastreio ? (
                <FieldRow label="Rastreio" value={pedido.rastreio} />
              ) : (
                <FieldRow label="Rastreio" value={<span style={{ color: 'var(--muted-foreground)' }}>indisponível</span>} mono={false} />
              )}
            </div>
          </Section>

          {/* Timeline */}
          {pedido.status !== 'Cancelado' && pedido.status !== 'Receita Pendente' && (
            <Section title="Andamento">
              <PedidoTimeline pedido={pedido} />
            </Section>
          )}

          {/* CTA suporte */}
          <button className="btn secondary block" onClick={() => setAjudaOpen(true)}>
            <Icon name="life-buoy" size={16} />
            Preciso de ajuda
          </button>
        </div>
      </div>

      <Sheet open={ajudaOpen} onClose={() => setAjudaOpen(false)} title="Precisa de ajuda?">
        <div style={{ fontSize: 14, color: 'var(--muted-foreground)', lineHeight: 1.5, marginBottom: 16 }}>
          Nossa equipe pode ajudar com informações sobre este pedido. Sua solicitação será registrada.
        </div>
        <div className="field" style={{ marginBottom: 16 }}>
          <label>Descreva o problema</label>
          <textarea
            className="input"
            rows="4"
            placeholder="Ex.: rastreio não atualiza há dias"
            style={{ resize: 'none', minHeight: 96 }}
          />
        </div>
        <button className="btn primary block" onClick={() => { setAjudaOpen(false); alert('Solicitação enviada — apenas visual no protótipo'); }}>
          Enviar solicitação
        </button>
      </Sheet>
    </div>
  );
}

// ─── ItemPedidoRow — composição do pedido ─────────────────────────────────
function ItemPedidoRow({ item }) {
  const fmt = window.TrendFmt;
  return (
    <div className="hairline-row" style={{ cursor: 'default', alignItems: 'flex-start' }}>
      <div className="grow" style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--foreground)' }} className="truncate">
          {item.nome}
        </div>
        <div style={{ fontSize: 12, color: 'var(--muted-foreground)', marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>
          {item.sku} · {item.qtd}× {fmt.fmtBRL(item.valor_unit)}
        </div>
      </div>
      <div className="tabnum" style={{ fontSize: 14, fontWeight: 500, color: 'var(--foreground)', flexShrink: 0 }}>
        {fmt.fmtBRL(item.subtotal)}
      </div>
    </div>
  );
}

// ─── Timeline visual ───────────────────────────────────────────────────────
function PedidoTimeline({ pedido }) {
  const steps = TIMELINE_MAP[pedido.status] || [pedido.status];
  const currentIdx = TIMELINE_ORDER.indexOf(pedido.status);
  const items = TIMELINE_ORDER.map((s, i) => ({
    label: s,
    done: currentIdx >= 0 && i <= currentIdx,
    current: currentIdx === i,
  }));
  useLucide();
  return (
    <div className="card">
      {items.map((item, i) => (
        <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', paddingBottom: i === items.length - 1 ? 0 : 12 }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
            <div style={{
              width: 20, height: 20, borderRadius: 999,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: item.done ? (item.current ? 'var(--primary)' : 'var(--success)') : 'var(--muted)',
              color: item.done ? '#fff' : 'var(--muted-foreground)',
              border: item.done ? 'none' : '1px solid var(--border)',
            }}>
              {item.done && !item.current ? <Icon name="check" size={11} /> : item.current ? <span style={{ width: 6, height: 6, borderRadius: 999, background: '#fff' }} /> : null}
            </div>
            {i < items.length - 1 && (
              <div style={{ width: 2, flex: 1, minHeight: 20, background: item.done ? 'var(--success)' : 'var(--border)', marginTop: 2 }} />
            )}
          </div>
          <div style={{ paddingTop: 1, minHeight: 22 }}>
            <div style={{
              fontSize: 13, fontWeight: item.current ? 600 : 400,
              color: item.done ? 'var(--foreground)' : 'var(--muted-foreground)',
            }}>
              {item.label}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
const TIMELINE_ORDER = ['Aguardando Envio', 'Enviado', 'Entrada Farmácia', 'Entregue'];
const TIMELINE_MAP = {
  'Aguardando Envio': ['Aguardando Envio'],
  'Enviado':          ['Aguardando Envio', 'Enviado'],
  'Entrada Farmácia': ['Aguardando Envio', 'Enviado', 'Entrada Farmácia'],
  'Entregue':         ['Aguardando Envio', 'Enviado', 'Entrada Farmácia', 'Entregue'],
  'Receita Pendente': ['Receita Pendente'],
};

Object.assign(window, { VendasScreen, PedidosListScreen, PedidoDetalheScreen, PedidoRow });
