// Canais → aba Cornerstone (spec 2026-11-11-cornerstone-parceiro, PR 1). Call center
// parceiro: recebe nossos compradores (leads) e vende por telefone. KPIs (leads enviados,
// pedidos, conversão, receita, ticket médio) + série diária + tabela por agente + rateio por
// família + lista de pedidos. Período = o do FilterBar global da página Canais (sem filtro
// próprio). Dado operacional: sem mock; offline honesto com auto-retry. Prefixo: cs/Cs/CS_.

const CS_COLOR = '#303880';   // CH.cornerstone (token --fenix-blue)

const CS_AGENT_COLS = [
  { key: 'agent',     label: 'Agente',        align: 'left' },
  { key: 'orders',    label: 'Pedidos',       align: 'right', fmt: v => NUM(v) },
  { key: 'revenue',   label: 'Receita',       align: 'right', fmt: v => USD(v) },
  { key: 'avgTicket', label: 'Ticket médio',  align: 'right', fmt: v => USD(v) },
  { key: 'share',     label: '% da receita',  align: 'right', fmt: v => (v == null ? '—' : PCT(v)) },
];
const CS_PROD_COLS = [
  { key: 'family',  label: 'Família',       align: 'left' },
  { key: 'units',   label: 'Unidades',      align: 'right', fmt: v => NUM(v) },
  { key: 'orders',  label: 'Pedidos',       align: 'right', fmt: v => NUM(v) },
  { key: 'revenue', label: 'Receita',       align: 'right', fmt: v => USD(v) },
  { key: 'share',   label: '% da receita',  align: 'right', fmt: v => (v == null ? '—' : PCT(v)) },
];
const CS_ORDER_COLS = [
  { key: 'date',          label: 'Data',     align: 'left',  fmt: v => csFmtDateTime(v), num: true },
  { key: 'orderId',       label: 'Order ID', align: 'left',  mono: true },
  { key: 'agent',         label: 'Agente',   align: 'left' },
  { key: 'items',         label: 'Itens',    align: 'left' },
  { key: 'customerEmail', label: 'Email',    align: 'left',  mono: true },
  { key: 'shipping',      label: 'Frete',    align: 'right', fmt: v => (v ? USD(v) : '—') },
  { key: 'net',           label: 'Receita',  align: 'right', fmt: v => USD(v), strong: true },
];

// date_created chega sem fuso (e adiantado — ressalva da spec): mostra como veio, sem converter.
const csFmtDateTime = (iso) => {
  if (!iso) return '—';
  const [d, t = ''] = iso.split('T');
  const [, M, D] = d.split('-');
  return `${D}/${M} ${t.slice(0, 5)}`;
};

// Tabela ordenável padrão ac/ldx (th sticky ▾/▴, hover, tdNum). Estado de ordenação local.
const CsTable = ({ cols, rows, initialSort, rowKey, maxHeight = 420, empty = 'Sem pedidos no período.' }) => {
  const [sortKey, setSortKey] = React.useState(initialSort);
  const [dir, setDir] = React.useState(-1);
  const sortBy = (k) => (k === sortKey ? setDir(-dir) : (setSortKey(k), setDir(-1)));
  const ind = (k) => (sortKey === k ? (dir < 0 ? ' ▾' : ' ▴') : '');
  const list = React.useMemo(() => {
    const l = rows.slice();
    l.sort((a, b) => {
      const av = a[sortKey], bv = b[sortKey];
      if (av == null && bv == null) return 0;
      if (av == null) return 1; if (bv == null) return -1;
      if (typeof av === 'string') return av.localeCompare(bv) * dir;
      return (av - bv) * dir;
    });
    return l;
  }, [rows, sortKey, dir]);
  return (
    <div style={cs.wrap}>
      <div style={{ ...cs.scroll, maxHeight }}>
        <table style={cs.table}>
          <thead><tr>
            {cols.map(c => (
              <th key={c.key} onClick={() => sortBy(c.key)} style={{ ...cs.th, textAlign: c.align }}>{c.label}{ind(c.key)}</th>
            ))}
          </tr></thead>
          <tbody>
            {list.map((r, i) => (
              <tr key={rowKey(r) || i}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--gray-50)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}>
                {cols.map(c => {
                  const isNum = c.align === 'right' || c.num;
                  return (
                    <td key={c.key} className={isNum ? 'fenix-num' : undefined} style={{
                      ...cs.td, textAlign: c.align,
                      ...(c.mono ? { font: '500 12px/1.3 var(--font-mono)', color: 'var(--fg-2)' } : {}),
                      ...(c.strong || c.key === cols[0].key ? { fontWeight: 700 } : {}),
                      // longhands DEPOIS do shorthand `font:` — inline vence a classe .fenix-num
                      ...(isNum ? { fontFamily: 'var(--font-num)', fontVariantNumeric: 'tabular-nums' } : {}),
                    }}>
                      {c.fmt ? c.fmt(r[c.key]) : (r[c.key] == null || r[c.key] === '' ? '—' : r[c.key])}
                    </td>
                  );
                })}
              </tr>
            ))}
            {list.length === 0 && (
              <tr><td colSpan={cols.length} style={cs.empty}>{empty}</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const CsCornerstoneView = ({ period, customRange }) => {
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState(false);
  const [loading, setLoading] = React.useState(true);
  const retry = useAutoRetry(err);   // falhou → tenta de novo a cada 15s, sozinho

  React.useEffect(() => {
    let cancelled = false; setLoading(true);
    fetchCornerstoneAPI({ period, start: customRange?.start, end: customRange?.end })
      .then(d => { if (!cancelled) { setData(d); setErr(false); } })
      .catch(() => { if (!cancelled) setErr(true); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [period, customRange, retry]);

  if (err && !data) return (
    <>
      <LoadingScreen conn="offline" />
      <div style={cs.reconNota}>Sem conexão com a API — a aba Cornerstone reconecta sozinha a cada 15s.</div>
    </>
  );
  if (!data) return <LoadingScreen conn="connecting" />;

  const header = (
    <div style={cs.header}>
      <div>
        <div style={cs.eye}>Canais · parceiro</div>
        <div style={cs.title}>Cornerstone</div>
      </div>
      {loading && <span style={cs.updating}>atualizando…</span>}
    </div>
  );

  if (!data.available) return (
    <div>
      {header}
      <div style={cs.waiting}>Sem integração com a CornerStone neste banco (tabelas ausentes).</div>
    </div>
  );

  const k = data.kpis;
  // 'T12:00:00': bucket date-only → parse LOCAL no eixo (senão rotula o dia anterior em BRT).
  const serie = (data.series || []).map(p => ({ bucket: p.bucket + 'T12:00:00', value: p.value }));

  return (
    <div>
      {header}
      {err && <div style={cs.notice}><Icon name="alert" size={14} color="currentColor" />Falha ao atualizar — mostrando o último dado carregado.</div>}

      <div className="kpi-grid" style={cs.kpiRow}>
        <DotKpi eye="Leads enviados" color={CS_COLOR}
          value={k.leads == null ? '—' : NUM(k.leads)}
          sub={data.leadsAvailable ? 'clientes únicos (email)' : 'sem tabela de leads'} />
        <DotKpi eye="Pedidos" color={CS_COLOR} value={NUM(k.orders)}
          sub={`${NUM(k.agents)} agente${k.agents === 1 ? '' : 's'}`} />
        <DotKpi eye="Conversão" color="var(--fenix-orange)"
          value={k.conversion == null ? '—' : PCT(k.conversion)} sub="pedidos ÷ leads" />
        <DotKpi eye="Receita" color="var(--fenix-orange)" value={USD(k.revenue)}
          sub={k.refundAmount + k.chargebackAmount > 0
            ? `bruto ${USD(k.gross)} − devoluções` : 'líquido · com frete'} />
        <DotKpi eye="Ticket médio" color={CS_COLOR}
          value={k.avgTicket == null ? '—' : USD(k.avgTicket)} sub="receita ÷ pedidos" />
      </div>

      <div style={cs.chartCard}>
        <div style={cs.cardEye}>Série temporal · Cornerstone</div>
        <ChannelChart ch={{ key: 'cs-serie', available: serie.length > 0, series: serie }}
          meta={{ label: 'Cornerstone', color: CS_COLOR }} fmtVal={USD} fmtTot={USDk}
          headerKpi={{ value: k.revenue, delta: null }}
          subtitle={`Receita diária · ${serie.length} dias`} granularity="day" height={220} />
      </div>

      <div style={cs.duo}>
        <div>
          <div style={cs.blockEye}>Por agente</div>
          <CsTable cols={CS_AGENT_COLS} rows={data.agents || []} initialSort="revenue"
            rowKey={r => r.agent} maxHeight={360} />
        </div>
        <div>
          <div style={cs.blockEye}>Por produto · rateio por item (frete proporcional)</div>
          <CsTable cols={CS_PROD_COLS} rows={data.products || []} initialSort="revenue"
            rowKey={r => r.family} maxHeight={360} />
        </div>
      </div>

      <div style={cs.blockEye}>Pedidos · {NUM((data.orders || []).length)}</div>
      <CsTable cols={CS_ORDER_COLS} rows={data.orders || []} initialSort="date"
        rowKey={r => r.orderId} maxHeight={600} />

      <div style={cs.note}>
        Só pedidos <b>completed</b>, janela pela data do pedido. A data chega da CornerStone sem
        fuso e adiantada (correção pendente na ingestão) — exibida como veio. Receita = total com
        frete − refunds − chargebacks. Família pelo nome do item; sem match vai para "Sem produto".
        Nada aqui entra na receita dos afiliados.
      </div>
    </div>
  );
};

const cs = {
  header: { display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 16, flexWrap: 'wrap' },
  eye: { font: 'var(--text-label)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)' },
  title: { font: '800 22px/1.1 var(--font-sans)', color: 'var(--fg-1)', letterSpacing: '-.01em', marginTop: 4 },
  updating: { font: '600 10.5px/1 var(--font-mono)', color: 'var(--fg-4)' },
  kpiRow: { display: 'grid', gridTemplateColumns: 'repeat(5,minmax(0,1fr))', gap: 14, marginBottom: 16 },
  chartCard: { background: '#fff', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)', padding: '16px 20px 8px', marginBottom: 16 },
  cardEye: { font: 'var(--text-label)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 4 },
  blockEye: { font: 'var(--text-label)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)', margin: '0 0 8px' },
  duo: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(360px,1fr))', gap: 16, marginBottom: 16 },
  wrap: { background: '#fff', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' },
  scroll: { overflowY: 'auto', overflowX: 'auto' },
  table: { width: '100%', borderCollapse: 'collapse' },
  th: { font: '700 10.5px/1 var(--font-sans)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)', background: 'var(--bg-sunken)', padding: '11px 14px', borderBottom: '1px solid var(--border-2)', position: 'sticky', top: 0, zIndex: 2, cursor: 'pointer', whiteSpace: 'nowrap', userSelect: 'none' },
  td: { font: '500 13px/1.3 var(--font-sans)', color: 'var(--fg-1)', padding: '11px 14px', borderBottom: '1px solid var(--border-1)', whiteSpace: 'nowrap' },
  empty: { padding: '28px 14px', textAlign: 'center', color: 'var(--fg-4)', font: 'var(--text-body-sm)' },
  notice: { display: 'flex', alignItems: 'center', gap: 6, font: '600 12px/1.4 var(--font-sans)', color: 'var(--warning)', background: 'var(--warning-bg)', padding: '10px 16px', borderRadius: 'var(--r-md)', marginBottom: 12 },
  waiting: { display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 120, color: 'var(--fg-3)', font: '600 13px/1.4 var(--font-sans)', border: '1px dashed var(--border-2)', borderRadius: 'var(--r-md)', padding: 12, textAlign: 'center' },
  reconNota: { textAlign: 'center', font: 'var(--text-body-sm)', color: 'var(--fg-3)', marginTop: -40 },
  note: { font: '500 11.5px/1.5 var(--font-sans)', color: 'var(--fg-4)', marginTop: 12 },
};

Object.assign(window, { CsCornerstoneView });
