// Logicall → Overview (spec 2026-08-11-logicall-submenu-design): duas faixas
// SEM comparação (Fênix laranja / LogiCall teal), séries e product performance.
// Self-contained, SEM mock (dado de parceiro — offline honesto). UI em inglês.

const LG_TEAL = '#0C8F73';

// PCT canônico é pt-BR (vírgula decimal) — página do parceiro precisa de
// ponto decimal em inglês. Mesmas casas decimais do PCT original.
const LG_PCT = (n) => n.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + '%';

// Loading/offline em inglês (LoadingScreen canônico é pt-BR hardcoded — página
// do parceiro precisa das DUAS faces em inglês). Reusado pela LogicallLeads.
const LgLoadingScreen = ({ offline = false }) => (
  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: 320, gap: 10 }}>
    <Spinner size={26} />
    <div style={{ font: '800 18px/1 var(--font-sans)', color: 'var(--fg-1)' }}>
      {offline ? 'API offline' : 'Connecting to the API'}</div>
    <div style={{ font: 'var(--text-body-sm)', color: 'var(--fg-3)' }}>
      {offline ? 'Retrying automatically every 15s…' : 'Loading your data…'}</div>
  </div>
);

const LogicallOverviewView = ({ families = [] }) => {
  const [period, setPeriod] = React.useState('30d');
  const [customRange, setCustomRange] = React.useState(null);
  const [product, setProduct] = React.useState('todos');
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(false);
  const fullLoading = useFullLoading();
  const withLoad = (fn) => (...a) => { fullLoading.mark(); fn(...a); };
  const retry = useAutoRetry(err);   // offline → tenta de novo a cada 15s, sozinho

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

  if (loading && !data) return <LgLoadingScreen />;
  if (!data) return <LgLoadingScreen offline />;

  const fx = data.fenix, lg = data.logicall;
  const carts = fx.abandonedCarts;
  const dash = (v, fmt) => (v == null ? '—' : fmt(v));
  const filtered = product !== 'todos';

  return (
    <div style={{ position: 'relative' }}>
      <div style={lgo.filterRow}>
        <PeriodSelector period={period} setPeriod={withLoad(setPeriod)}
          customRange={customRange} setCustomRange={withLoad(setCustomRange)} lang="en" />
        <Dropdown icon="cart" label="Product" value={product} onChange={withLoad(setProduct)}
          options={[{ key: 'todos', label: 'All' }, ...families.map(f => ({ key: f.name || f, label: f.name || f }))]} />
      </div>

      {filtered && (
        <div style={lgo.notice}><Icon name="alert" size={14} color="currentColor" />
          Product filter applies to the Grupo Fênix strip only — LogiCall numbers and carts are checkout-wide.</div>
      )}
      {!data.bridgeAvailable && (
        <div style={lgo.notice}><Icon name="alert" size={14} color="currentColor" />
          Leads feed offline — cart-based metrics unavailable right now.</div>
      )}

      <div style={lgo.stripEye}><span style={{ color: 'var(--fenix-orange)' }}>●</span> GRUPO FÊNIX</div>
      <div className="kpi-grid" style={{ ...lgo.kpiRow, gridTemplateColumns: 'repeat(3,minmax(0,1fr))' }}>
        <DotKpi eye="Gross Sales" color="var(--fenix-orange)" value={USD(fx.grossSales)}
          sub={`avg ${USD(fx.avgPerDay)}/day`} />
        <DotKpi eye="AOV" color="var(--fenix-blue)" value={USD(fx.aov)} sub="per checkout" />
        <DotKpi eye="Abandoned Carts" color="#CA8A04" value={dash(carts, NUM)}
          sub={data.bridgeAvailable === false ? 'leads feed offline' : `avg ${NUM(fx.cartsAvgPerDay)}/day${filtered ? ' · no product filter' : ''}`} />
      </div>
      <div style={lgo.chartCard}>
        <div style={lgo.cardEye}>Gross sales over time</div>
        <ChannelChart ch={{ key: 'lg-fenix', available: fx.grossSeries.length > 0, series: fx.grossSeries }}
          meta={{ label: 'Grupo Fênix', color: '#FD7119' }} fmtVal={USD} fmtTot={USDk}
          subtitle="Valid sales, gross revenue" granularity={data.granularity} height={200} />
      </div>

      <div style={lgo.stripEye}><span style={{ color: LG_TEAL }}>●</span> LOGICALL</div>
      <div className="kpi-grid" style={{ ...lgo.kpiRow, gridTemplateColumns: 'repeat(6,minmax(0,1fr))' }}>
        <DotKpi eye="Leads Worked" color={LG_TEAL} value={dash(lg.leadsWorked, NUM)}
          sub={data.bridgeAvailable === false ? 'leads feed offline' : 'carts sent to LogiCall'} />
        <DotKpi eye="Conversion" color={LG_TEAL} value={dash(lg.conversionRate, LG_PCT)}
          sub={data.bridgeAvailable === false ? 'leads feed offline' : 'sales ÷ carts'} />
        <DotKpi eye="Sales" color={LG_TEAL} value={NUM(lg.sales)} sub="recovered by phone" />
        <DotKpi eye="Gross Recovered" color={LG_TEAL} value={USD(lg.grossRecovered)} sub="gross, pre-refund" />
        <DotKpi eye="RPL" color={LG_TEAL} value={dash(lg.rpl, USD)}
          sub={data.bridgeAvailable === false ? 'leads feed offline' : 'revenue per lead'} />
        <DotKpi eye="AOV" color={LG_TEAL} value={USD(lg.aov)} sub="per recovered sale" />
      </div>
      <div style={lgo.chartCard}>
        <div style={lgo.cardEye}>Recovered sales over time</div>
        <ChannelChart ch={{ key: 'lg-logicall', available: lg.recoveredSeries.length > 0, series: lg.recoveredSeries }}
          meta={{ label: 'LogiCall', color: LG_TEAL }} fmtVal={NUM} fmtTot={NUM}
          subtitle="Recovered sales count" granularity={data.granularity} height={200} />
      </div>

      <div style={lgo.tableCard}>
        <div style={lgo.cardEye}>Product performance · Grupo Fênix operation</div>
        <div style={lgo.scroll}>
          <table style={lgo.table}>
            <thead><tr>
              <th style={{ ...lgo.th, textAlign: 'left' }}>Product</th>
              <th style={lgo.th}>Revenue</th><th style={lgo.th}>Sales</th><th style={lgo.th}>Approval</th>
            </tr></thead>
            <tbody>
              {(data.products || []).map(p => (
                <tr key={p.name}>
                  <td style={{ ...lgo.td, textAlign: 'left', fontWeight: 600 }}>{p.name}</td>
                  <td style={lgo.td} className="fenix-num">{USD(p.revenue)}</td>
                  <td style={lgo.td} className="fenix-num">{NUM(p.sales)}</td>
                  <td style={lgo.td} className="fenix-num">{dash(p.approval, LG_PCT)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <FullLoadingOverlay show={fullLoading.show && !!data} conn="connecting" />
    </div>
  );
};

const lgo = {
  filterRow: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 16 },
  stripEye: { font: '800 11px/1 var(--font-sans)', letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--fg-2)', margin: '6px 0 10px', display: 'flex', gap: 7, alignItems: 'center' },
  kpiRow: { display: 'grid', 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: 20 },
  tableCard: { background: '#fff', border: '1px solid var(--border-1)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)', padding: '16px 20px 6px', marginBottom: 16 },
  cardEye: { font: 'var(--text-label)', letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 8 },
  scroll: { maxHeight: 480, overflowY: 'auto', overflowX: 'auto' },
  table: { width: '100%', minWidth: 520, borderCollapse: 'collapse' },
  th: { font: '700 10.5px/1 var(--font-sans)', letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--fg-3)', padding: '10px 12px', borderBottom: '1px solid var(--border-2)', textAlign: 'right', whiteSpace: 'nowrap' },
  td: { padding: '10px 12px', borderBottom: '1px solid var(--border-1)', font: 'var(--text-body-sm)', color: 'var(--fg-1)', textAlign: 'right', whiteSpace: 'nowrap' },
  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 },
};

// Tracking do parceiro = AcompanhamentoView parametrizado (spec §4).
const LG_ACOMP_SOURCES = [
  { key: 'direto', label: 'Direct Revenue' }, { key: 'logicall', label: 'LogiCall' },
];
const LogicallAcompView = ({ families = [] }) => (
  <AcompanhamentoView families={families} sources={LG_ACOMP_SOURCES}
    apiPath="/logicall/acompanhamento" eyebrow="Logicall" title="Tracking" lang="en" />
);

window.LogicallOverviewView = LogicallOverviewView;
window.LogicallAcompView = LogicallAcompView;
