'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { loadTeamOptions } from '@/features/custom-properties/useTeamOptions';
import { listAllOwners } from '@/features/owners/api.client';
import { listPipelines } from '@/features/pipelines/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  listSalesReportRecords,
  runSalesReport,
  type SalesDesignGroup,
  type SalesReportInfo,
  type SalesReportQuery,
  type SalesReportRecord,
  type SalesReportResult,
} from '../api.client';
import { DESIGN_GROUPS, defaultRange, designGroupOf } from '../constants';
import { formatFigure } from '../format';
import {
  chartModel,
  compareRows,
  drillRowId,
  formatCell,
  pageList,
  pctDelta,
  recordHref,
  recordTypeLabel,
  recordsSheet,
  sortRows,
  summarizedSheet,
  hasNextStep,
  nextSteps,
  rowLabelOf,
  tableColumns,
  type ReportRow,
  type SortBy,
} from '../model';
import {
  RANGE_ITEMS,
  boundsText,
  formatDay,
  previousLabel,
  rangeBounds,
  rangeText,
  type RangeState,
} from '../ranges';
import {
  EditQuickFiltersDialog,
  ExportDialog,
  RangeDialog,
  RecordsDialog,
  SaveReportDialog,
  SegmentDialog,
  allRecords,
  downloadSheet,
} from './dialogs';
import {
  CHART_TYPES,
  ChartTypeIcon,
  EmptyArt,
  LpI,
  NO_DATA,
  SaCaret,
  SaIcon,
  type ChartType,
} from './icons';
import { MenuPop, SelectPop, type SelectOption } from './layers';
import { ReportChart } from './ReportChart';
import { Delta } from './SalesHome';

/**
 * One sales report (design `shellHtml` / `rvAll`): breadcrumb and actions, the filter bar with
 * quick filters, the summary against the previous period, the chart, the summarized and
 * unsummarized tables, and the settings panel (chart type, comparison, sort).
 */

type QfKey = 'owner' | 'team' | 'pipeline';

export interface ReportState {
  range: RangeState;
  ownerId?: string;
  teamId?: string;
  pipelineId?: string;
  /** Show the previous period in the chart and table (Settings › Comparison). */
  compare: boolean;
  chart: ChartType;
  sortBy: SortBy;
  order: 'asc' | 'desc';
  tab: 'sum' | 'raw';
  page: number;
  size: number;
  settings: boolean;
  /** Quick filters added to the report's own. */
  custom: QfKey[];
}

const isDealGroup = (g: SalesDesignGroup) => g === 'deals' || g === 'forecasts';

export function initialReportState(info: SalesReportInfo): ReportState {
  return {
    range: defaultRange(info.key),
    compare: false,
    chart:
      info.unit === 'percent' || info.unit === 'days' || info.unit === 'hours' ? 'vbar' : 'hbar',
    sortBy: 'none',
    order: 'desc',
    tab: 'sum',
    page: 1,
    size: 25,
    settings: false,
    custom: readCustomQf(info.key),
  };
}

const QF_STORE = (key: string) => `crm.sa.qf.${key}`;
function readCustomQf(key: string): QfKey[] {
  try {
    const v = JSON.parse(localStorage.getItem(QF_STORE(key)) ?? '[]');
    return Array.isArray(v)
      ? v.filter((x): x is QfKey => ['owner', 'team', 'pipeline'].includes(x))
      : [];
  } catch {
    return [];
  }
}
function writeCustomQf(key: string, v: QfKey[]) {
  try {
    localStorage.setItem(QF_STORE(key), JSON.stringify(v));
  } catch {
    /* private window */
  }
}

/** Owners, teams and deal pipelines for the quick filters, loaded once per page. */
let optionsOnce: Promise<FilterOptions> | null = null;
interface FilterOptions {
  owners: SelectOption[];
  teams: SelectOption[];
  pipelines: SelectOption[];
}
function loadFilterOptions(): Promise<FilterOptions> {
  optionsOnce ??= Promise.all([
    listAllOwners().catch(() => []),
    loadTeamOptions().catch(() => []),
    listPipelines({ objectType: 'deal' }).catch(() => []),
  ]).then(([owners, teams, pipes]) => ({
    owners: owners.map((o) => ({
      value: o.userId,
      label: o.name || o.email,
      hint: o.active ? undefined : 'Deactivated',
    })),
    teams: teams.map((t) => ({ value: t.id, label: t.name })),
    pipelines: pipes.filter((p) => !p.archived).map((p) => ({ value: p.id, label: p.name })),
  }));
  return optionsOnce;
}

type Pop =
  | {
      kind: 'range' | 'actions' | 'ctype' | 'addqf' | 'size' | 'cmp' | 'sortby' | 'order';
      el: HTMLElement;
    }
  | { kind: 'qf'; key: QfKey; el: HTMLElement };

type Dialog =
  | { kind: 'export' | 'exportRaw' | 'save' | 'editqf' }
  | { kind: 'segment'; rowId?: string }
  | { kind: 'range'; range: 'rolling' | 'custom' }
  | { kind: 'records'; title: string; rowId?: string };

export function ReportView({
  info,
  state: st,
  onState,
  onHome,
  onGroup,
  tabs = [],
  onTab,
}: {
  info: SalesReportInfo;
  state: ReportState;
  onState: (next: ReportState) => void;
  onHome: () => void;
  onGroup: (g: SalesDesignGroup) => void;
  /** LP9: the tabs of this report's tab group (the design's `rvTabsHtml`), and opening one. */
  tabs?: { key: string; label: string }[];
  onTab?: (key: string) => void;
}) {
  const toast = useToast();
  const group = designGroupOf(info);
  const groupLabel = DESIGN_GROUPS.find((g) => g.key === group)?.label ?? '';
  const set = (patch: Partial<ReportState>) => onState({ ...st, ...patch });

  const [result, setResult] = useState<SalesReportResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [tick, setTick] = useState(0);
  const [opts, setOpts] = useState<FilterOptions | null>(null);
  const [pop, setPop] = useState<Pop | null>(null);
  const [dialog, setDialog] = useState<Dialog | null>(null);
  /** Export from the records dialog: a row's id, null for the whole report. */
  const [rowExport, setRowExport] = useState<string | null | undefined>(undefined);

  useEffect(() => {
    loadFilterOptions().then(setOpts, () => undefined);
  }, []);

  const bounds = useMemo(() => rangeBounds(st.range), [st.range]);
  /** The filters every call takes (records, segment, save). */
  const query = useMemo<SalesReportQuery>(
    () => ({
      from: bounds.from,
      to: bounds.to,
      ...(st.ownerId ? { ownerId: st.ownerId } : {}),
      ...(st.teamId ? { teamId: st.teamId } : {}),
      ...(st.pipelineId ? { pipelineId: st.pipelineId } : {}),
    }),
    [bounds, st.ownerId, st.teamId, st.pipelineId],
  );

  useEffect(() => {
    const ctrl = new AbortController();
    setError(null);
    runSalesReport(
      info.key,
      { ...query, compare: 'previous_period' },
      { signal: ctrl.signal },
    ).then(setResult, (e: unknown) => {
      if (!ctrl.signal.aborted) setError(errorText(e));
    });
    return () => ctrl.abort();
  }, [info.key, query, tick]);

  // Quick filters: the report's own, then those added (design `qkeys`).
  const fixed: QfKey[] = isDealGroup(group) ? ['owner', 'pipeline'] : ['owner'];
  const allQf: QfKey[] = isDealGroup(group) ? ['owner', 'team', 'pipeline'] : ['owner', 'team'];
  const qfKeys = [...fixed, ...st.custom.filter((k) => allQf.includes(k) && !fixed.includes(k))];
  const qfLabel = (k: QfKey) =>
    k === 'owner'
      ? // LP9: the report's own name for it ("Lead Owner"), else the group's.
        (info.ownerLabel ?? (group === 'activities' ? 'Activity assigned to' : 'Deal owner'))
      : k === 'team'
        ? 'Team'
        : 'Pipeline';
  const qfValue = (k: QfKey) =>
    k === 'owner' ? st.ownerId : k === 'team' ? st.teamId : st.pipelineId;
  const qfOptions = (k: QfKey) =>
    (k === 'owner' ? opts?.owners : k === 'team' ? opts?.teams : opts?.pipelines) ?? [];
  const qfName = (k: QfKey) => qfOptions(k).find((o) => o.value === qfValue(k))?.label;
  const setQf = (k: QfKey, v: string | undefined) =>
    set({ [k === 'owner' ? 'ownerId' : k === 'team' ? 'teamId' : 'pipelineId']: v, page: 1 });
  const anyQf = Boolean(st.ownerId || st.teamId || st.pipelineId);
  const filterCount = 1 + [st.ownerId, st.teamId, st.pipelineId].filter(Boolean).length;
  const setCustom = (custom: QfKey[]) => {
    writeCustomQf(info.key, custom);
    const patch: Partial<ReportState> = { custom };
    // A quick filter taken off the bar stops filtering.
    for (const k of st.custom)
      if (!custom.includes(k) && !fixed.includes(k)) {
        if (k === 'team') patch.teamId = undefined;
        if (k === 'pipeline') patch.pipelineId = undefined;
        if (k === 'owner') patch.ownerId = undefined;
      }
    set(patch);
  };

  const rows: ReportRow[] = useMemo(() => (result ? compareRows(result) : []), [result]);
  const sorted = useMemo(() => sortRows(rows, st.sortBy, st.order), [rows, st.sortBy, st.order]);
  const cols = tableColumns(info);
  const currency = result?.currency ?? 'USD';
  const fmt = (v: number) => formatFigure(v, info.unit, currency);
  const showPrev = st.compare && Boolean(result?.previous);
  const shownResult = result && !showPrev ? { ...result, previous: undefined } : result;
  const model = useMemo(
    () => (shownResult ? chartModel(sorted, shownResult, info.columns.value) : null),
    // shownResult follows result and showPrev
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [sorted, result, showPrev, info.columns.value],
  );
  const empty = result ? !result.rows.length : false;
  const prevText = previousLabel(st.range.key);
  const rText = rangeText(st.range);
  const chips = [rText, `Filters (${filterCount})`];

  const reportUrl = () => {
    const p = new URLSearchParams({ report: info.key, from: bounds.from, to: bounds.to });
    for (const k of ['ownerId', 'teamId', 'pipelineId'] as const) if (st[k]) p.set(k, st[k]!);
    if (st.compare) p.set('compare', 'previous_period');
    return `${window.location.origin}/sales-analytics?${p.toString()}`;
  };
  const builderHref = `/reports/library/new?object=${group === 'activities' ? 'contact' : 'deal'}&returnTo=${encodeURIComponent(`/sales-analytics?report=${info.key}`)}`;
  const exportName = `${info.title} - ${rText}`;

  // KPIs (design `kpiList`): the total, or each series' total for a split report.
  const kpis = useMemo(() => {
    if (!result) return [];
    if (result.series?.length) {
      const sum = (rs: typeof result.rows, id: string) =>
        rs.reduce((a, r) => a + (r.breakdown?.[id] ?? 0), 0);
      return result.series
        .map((s) => ({
          id: s.id,
          label: s.label,
          v: sum(result.rows, s.id),
          pv: result.previous ? sum(result.previous.rows, s.id) : null,
        }))
        .filter((k) => k.v > 0)
        .slice(0, 6);
    }
    if (result.total === null) return [];
    return [
      {
        id: '_',
        label: info.columns.value,
        v: result.total,
        pv: result.previous ? result.previous.total : null,
      },
    ];
  }, [result, info.columns.value]);

  const pages = Math.max(1, Math.ceil(sorted.length / st.size));
  const page = Math.min(st.page, pages);
  const slice = sorted.slice((page - 1) * st.size, page * st.size);

  const openRow = (r: ReportRow) =>
    setDialog({ kind: 'records', title: `${info.title}: ${r.label}`, rowId: drillRowId(r) });

  const selButton = (kind: 'cmp' | 'sortby' | 'order', text: string) => (
    <button
      type="button"
      className="lp-select sa-sel"
      aria-haspopup="listbox"
      aria-expanded={pop?.kind === kind}
      onClick={(e) => setPop(pop?.kind === kind ? null : { kind, el: e.currentTarget })}
    >
      <span>{text}</span>
      <LpI name="chevd" className="lp-i--xs" />
    </button>
  );
  const ct = CHART_TYPES.find((c) => c.key === st.chart) ?? CHART_TYPES[0]!;
  const sortText =
    st.sortBy === 'label'
      ? rowLabelOf(info)
      : st.sortBy === 'value'
        ? info.columns.value
        : 'Report order';

  return (
    <div className={cn('sa-rv sa-rv-area', st.settings && 'has-set')}>
      <div className="sa-rv__main">
        <nav className="sa-crumbs" aria-label="Breadcrumb">
          <button type="button" className="sa-link" onClick={onHome}>
            Sales analytics suite
          </button>
          <span aria-hidden="true">›</span>
          <button type="button" className="sa-link" onClick={() => onGroup(group)}>
            {groupLabel}
          </button>
          <span aria-hidden="true">›</span>
          <span aria-current="page">{info.title}</span>
        </nav>
        <div className="sa-rv__title">
          <h1 className="sa-h1">{info.title}</h1>
          <div className="sa-rep__bar">
            <button
              type="button"
              className="sa-btn sa-btn--icon"
              aria-label="Refresh data"
              onClick={() => {
                setTick((t) => t + 1);
                toast('Report refreshed');
              }}
            >
              <SaIcon name="refresh" />
            </button>
            <button
              type="button"
              className="sa-btn sa-btn--outline"
              onClick={() => setDialog({ kind: 'save' })}
            >
              Save report
            </button>
            <Link className="sa-btn sa-btn--primary" href={builderHref}>
              Edit in report builder
            </Link>
            <button
              type="button"
              className="sa-btn sa-btn--outline"
              aria-haspopup="menu"
              aria-expanded={pop?.kind === 'actions'}
              onClick={(e) =>
                setPop(pop?.kind === 'actions' ? null : { kind: 'actions', el: e.currentTarget })
              }
            >
              Actions
              <SaCaret />
            </button>
          </div>
        </div>

        {tabs.length > 1 ? (
          // LP9: the design's report tabs (sales-analytics.js:4797-4801), above the filters.
          <div className="sa-rtabs" role="tablist" aria-label="Report views">
            {tabs.map((t) => (
              <button
                key={t.key}
                type="button"
                role="tab"
                className={cn('sa-rtab', t.key === info.key && 'is-on')}
                aria-selected={t.key === info.key}
                onClick={() => {
                  if (t.key !== info.key) onTab?.(t.key);
                }}
              >
                {t.label}
              </button>
            ))}
          </div>
        ) : null}
        <div className="sa-rv__filters" role="group" aria-label="Report filters">
          <button
            type="button"
            className="sa-fchip sa-fchip--on"
            aria-haspopup="listbox"
            aria-expanded={pop?.kind === 'range'}
            onClick={(e) =>
              setPop(pop?.kind === 'range' ? null : { kind: 'range', el: e.currentTarget })
            }
          >
            {rText}
            <SaIcon name="caret" className="sa-i--xs" />
          </button>
          <span className="sa-fsep" aria-hidden="true" />
          {qfKeys.map((k) => (
            <button
              key={k}
              type="button"
              className={cn('sa-fchip sa-fq', qfValue(k) && 'sa-fchip--on')}
              aria-haspopup="dialog"
              aria-expanded={pop?.kind === 'qf' && pop.key === k}
              title={qfName(k)}
              onClick={(e) =>
                setPop(
                  pop?.kind === 'qf' && pop.key === k
                    ? null
                    : { kind: 'qf', key: k, el: e.currentTarget },
                )
              }
            >
              {qfLabel(k)}
              {qfValue(k) ? ' (1)' : ''}
              <SaIcon name="caret" className="sa-i--xs" />
            </button>
          ))}
          <button
            type="button"
            className="sa-link sa-fclear"
            disabled={!anyQf}
            onClick={() =>
              set({ ownerId: undefined, teamId: undefined, pipelineId: undefined, page: 1 })
            }
          >
            Clear all
          </button>
          <span className="sa-fsep" aria-hidden="true" />
          <button
            type="button"
            className="sa-round"
            aria-label="Add a quick filter"
            aria-haspopup="dialog"
            aria-expanded={pop?.kind === 'addqf'}
            disabled={qfKeys.length >= allQf.length}
            onClick={(e) =>
              setPop(pop?.kind === 'addqf' ? null : { kind: 'addqf', el: e.currentTarget })
            }
          >
            <SaIcon name="plus" className="sa-i--sm" />
          </button>
          <button
            type="button"
            className="sa-round"
            aria-label="Edit quick filters"
            onClick={() => setDialog({ kind: 'editqf' })}
          >
            <SaIcon name="pencil" className="sa-i--sm" />
          </button>
          <span className="sa-fsep" aria-hidden="true" />
          <button
            type="button"
            className="sa-link sa-fclear"
            disabled={!anyQf && !st.custom.length}
            onClick={() => {
              writeCustomQf(info.key, []);
              set({
                ownerId: undefined,
                teamId: undefined,
                pipelineId: undefined,
                custom: [],
                page: 1,
              });
              toast('Filters reset');
            }}
          >
            Reset filters
          </button>
        </div>

        {error ? (
          <section className="sa-panel">
            <p className="sa-muted" role="alert">
              This report could not be run: {error}
            </p>
          </section>
        ) : !result ? (
          <section className="sa-panel">
            <p className="sa-muted">Loading report…</p>
          </section>
        ) : (
          <>
            <section className="sa-panel sa-sum2" aria-labelledby="saSumH">
              <div className="sa-sum2__head">
                <h2 className="sa-h3" id="saSumH">
                  Report summary
                </h2>
              </div>
              <div className="sa-sum2__grid sa-sum2__grid--one">
                <div className="sa-sum2__l">
                  <div className="sa-chips">
                    {result.previous ? (
                      <span
                        className="sa-chip"
                        title={`Dates included: ${boundsText(result.previous)}`}
                        tabIndex={0}
                      >
                        Compared To | {prevText}
                      </span>
                    ) : null}
                  </div>
                  {empty ? (
                    <div className="sa-empty">
                      <EmptyArt />
                      <p>{NO_DATA}</p>
                    </div>
                  ) : kpis.length ? (
                    <div className="sa-kpis">
                      {kpis.map((k) => (
                        <div
                          key={k.id}
                          className="sa-kpi2 sa-kpi--go"
                          role="button"
                          tabIndex={0}
                          title={k.pv === null ? undefined : `Previous period: ${fmt(k.pv)}`}
                          onClick={() => setDialog({ kind: 'records', title: info.title })}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                              e.preventDefault();
                              setDialog({ kind: 'records', title: info.title });
                            }
                          }}
                        >
                          <p className="sa-kpi2__l">{k.label}</p>
                          <p className="sa-kpi2__v">{fmt(k.v)}</p>
                          <Delta d={k.pv === null ? null : pctDelta(k.v, k.pv)} />
                        </div>
                      ))}
                    </div>
                  ) : (
                    <p className="sa-muted">
                      <strong>Can&apos;t be summarized.</strong> Use the chart and table below to
                      explore the data.
                    </p>
                  )}
                </div>
              </div>
            </section>

            <section className="sa-panel sa-chartp2">
              <button
                type="button"
                className="sa-ctbtn"
                aria-haspopup="listbox"
                aria-expanded={pop?.kind === 'ctype'}
                onClick={(e) =>
                  setPop(pop?.kind === 'ctype' ? null : { kind: 'ctype', el: e.currentTarget })
                }
              >
                <span className="sa-ctbtn__ic">
                  <ChartTypeIcon type={ct.key} />
                </span>
                <b>{ct.label}</b>
                <SaIcon name="caret" className="sa-i--xs" />
              </button>
              <div className="sa-chips">
                {chips.map((c) => (
                  <span key={c} className="sa-chip">
                    {c}
                  </span>
                ))}
              </div>
              {model && model.series.length > 1 && !['kpi', 'table'].includes(st.chart) ? (
                <ul className="sa-leg2">
                  {model.series.map((s, i) => (
                    <li key={s.id}>
                      <i className="sa-dot" style={{ background: `var(--sa-s${(i % 8) + 1})` }} />
                      {s.label}
                    </li>
                  ))}
                </ul>
              ) : null}
              {empty ? (
                <div className="sa-empty">
                  <EmptyArt />
                  <p>{NO_DATA}</p>
                </div>
              ) : st.chart === 'table' ? (
                <SummaryTable
                  rows={sorted}
                  cols={cols}
                  info={info}
                  result={result}
                  showPrev={showPrev}
                  currency={currency}
                  onRow={openRow}
                />
              ) : model ? (
                <>
                  {st.chart !== 'kpi' ? <p className="sa-axisT">{rowLabelOf(info)}</p> : null}
                  <ReportChart
                    model={model}
                    type={st.chart}
                    measure={info.columns.value}
                    fmt={fmt}
                    kpi={
                      <div className="sa-kpibig2">
                        <p className="sa-kpi__l">{info.columns.value}</p>
                        <p className="sa-kpi__v sa-kpi__v--xl">
                          {result.total === null ? '–' : fmt(result.total)}
                        </p>
                        {result.total !== null && result.previous ? (
                          <Delta d={pctDelta(result.total, result.previous.total)} />
                        ) : null}
                      </div>
                    }
                  />
                </>
              ) : null}
            </section>

            <section className="sa-panel sa-tblp">
              <div className="sa-tabs2" role="tablist">
                {(
                  [
                    ['sum', 'Summarized Data'],
                    ['raw', 'Unsummarized Dataset'],
                  ] as const
                ).map(([k, l]) => (
                  <button
                    key={k}
                    type="button"
                    role="tab"
                    className={st.tab === k ? 'is-on' : ''}
                    aria-selected={st.tab === k}
                    onClick={() => set({ tab: k })}
                  >
                    {l}
                  </button>
                ))}
              </div>
              {st.tab === 'sum' ? (
                empty ? (
                  <div className="sa-empty">
                    <EmptyArt />
                    <p>{NO_DATA}</p>
                  </div>
                ) : (
                  <>
                    <SummaryTable
                      rows={slice}
                      cols={cols}
                      info={info}
                      result={result}
                      showPrev={showPrev}
                      currency={currency}
                      onRow={openRow}
                    />
                    <nav className="sa-pager2" aria-label="Table pagination">
                      <button
                        type="button"
                        className="sa-pgt"
                        disabled={page <= 1}
                        onClick={() => set({ page: page - 1 })}
                      >
                        <SaIcon name="back" className="sa-i--sm" />
                        Prev
                      </button>
                      {pageList(page, pages).map((p, i) =>
                        p === '…' ? (
                          <span key={`e${i}`} className="sa-pgel" aria-hidden="true">
                            …
                          </span>
                        ) : (
                          <button
                            key={p}
                            type="button"
                            className={cn('sa-pgn', p === page && 'is-on')}
                            aria-current={p === page ? 'page' : undefined}
                            aria-label={`Page ${p}`}
                            onClick={() => set({ page: p })}
                          >
                            {p}
                          </button>
                        ),
                      )}
                      <button
                        type="button"
                        className="sa-pgt"
                        disabled={page >= pages}
                        onClick={() => set({ page: page + 1 })}
                      >
                        Next
                        <SaIcon name="right" className="sa-i--sm" />
                      </button>
                      <button
                        type="button"
                        className="sa-pgsize"
                        aria-haspopup="menu"
                        aria-expanded={pop?.kind === 'size'}
                        onClick={(e) =>
                          setPop(
                            pop?.kind === 'size' ? null : { kind: 'size', el: e.currentTarget },
                          )
                        }
                      >
                        {st.size} per page
                        <SaIcon name="caret" className="sa-i--xs" />
                      </button>
                    </nav>
                  </>
                )
              ) : (
                <RawDataset info={info} query={query} currency={currency} />
              )}
            </section>
          </>
        )}
      </div>

      <aside
        className={cn('sa-rv__set sa-set', `sa-set--grp-${group}`)}
        hidden={!st.settings}
        aria-label="Report settings"
      >
        {st.settings ? (
          <>
            <details className="sa-set2__adv" open>
              <summary className="sa-set2__head">
                <h2 className="sa-h3 crm-flex-grow-1">Settings</h2>
                <span className="crm-pe-3">
                  <button
                    type="button"
                    className="sa-link"
                    onClick={() => {
                      const d = initialReportState(info);
                      set({ chart: d.chart, compare: d.compare, sortBy: d.sortBy, order: d.order });
                    }}
                  >
                    Reset settings
                  </button>
                </span>
              </summary>
              <div className="sa-set2__sec">
                <p className="sa-fs__l">Chart type</p>
                <div className="sa-ctypes2">
                  {CHART_TYPES.map((c) => (
                    <button
                      key={c.key}
                      type="button"
                      className="sa-ctype2"
                      aria-pressed={st.chart === c.key}
                      title={c.label}
                      onClick={() => set({ chart: c.key })}
                    >
                      <ChartTypeIcon type={c.key} />
                      <span className="sa-sr">{c.label}</span>
                    </button>
                  ))}
                </div>
              </div>
              <details className="sa-set2__adv" open>
                <summary>Advanced</summary>
                <div className="sa-adv">
                  <p className="sa-fs__l">Comparison</p>
                  {selButton('cmp', st.compare ? 'Previous period' : 'No comparison')}
                  <p className="sa-fs__l sa-mt">Sort by</p>
                  {selButton('sortby', sortText)}
                  {st.sortBy !== 'none'
                    ? selButton(
                        'order',
                        st.order === 'asc' ? 'Ascending order' : 'Descending order',
                      )
                    : null}
                </div>
              </details>
            </details>
            <details className="sa-set2__adv sa-set2__adv--about">
              <summary>About</summary>
              <div className="sa-adv sa-small">
                <p>{info.description}</p>
                <p className="sa-fs__l">Report measures</p>
                <p className="sa-muted">These are the metrics this report analyzes:</p>
                <ul className="list-ul-dot">
                  {cols.map((c) => (
                    <li key={c.id}>{c.label}</li>
                  ))}
                </ul>
              </div>
            </details>
            <details className="sa-set2__adv sa-set2__adv--dq data-quality">
              <summary>Data Quality</summary>
              <div className="sa-adv sa-small sa-adv-data-quality">
                <p className="sa-muted">Records with no owner appear as Unassigned.</p>
              </div>
            </details>
          </>
        ) : null}
      </aside>
      <div className="sa-rv__strip">
        <button
          type="button"
          className="sa-x"
          aria-label={st.settings ? 'Close settings' : 'Open settings'}
          aria-pressed={st.settings}
          title={st.settings ? 'Close settings' : 'Open settings'}
          onClick={() => set({ settings: !st.settings })}
        >
          <SaIcon name="pencil" className="sa-i--sm" />
        </button>
      </div>

      {/* popovers */}
      {pop?.kind === 'range' ? (
        <SelectPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          search={false}
          minWidth={230}
          groups={[
            { label: '', options: RANGE_ITEMS.map((r) => ({ value: r.key, label: r.label })) },
          ]}
          value={st.range.key}
          onPick={(v) => {
            if (v === 'rolling' || v === 'custom') setDialog({ kind: 'range', range: v });
            else set({ range: { key: v as RangeState['key'] }, page: 1 });
          }}
        />
      ) : null}
      {pop?.kind === 'qf' ? (
        <SelectPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          groups={[{ label: '', options: qfOptions(pop.key) }]}
          value={qfValue(pop.key) ?? null}
          minWidth={260}
          // Picking the chosen one again clears it.
          onPick={(v) => setQf(pop.key, v === qfValue(pop.key) ? undefined : v)}
        />
      ) : null}
      {pop?.kind === 'addqf' ? (
        <SelectPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          groups={[
            {
              label: '',
              options: allQf
                .filter((k) => !qfKeys.includes(k))
                .map((k) => ({ value: k, label: qfLabel(k) })),
            },
          ]}
          value={null}
          onPick={(v) => setCustom([...st.custom, v as QfKey])}
        />
      ) : null}
      {pop?.kind === 'ctype' ? (
        <SelectPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          search={false}
          groups={[
            { label: '', options: CHART_TYPES.map((c) => ({ value: c.key, label: c.label })) },
          ]}
          value={st.chart}
          onPick={(v) => set({ chart: v as ChartType })}
        />
      ) : null}
      {pop?.kind === 'size' ? (
        <MenuPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          items={[10, 25, 50, 100].map((n) => ({
            label: `${n} per page`,
            on: st.size === n,
            onClick: () => set({ size: n, page: 1 }),
          }))}
        />
      ) : null}
      {pop?.kind === 'cmp' ? (
        <SelectPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          search={false}
          groups={[
            {
              label: '',
              options: [
                { value: 'none', label: 'No comparison' },
                { value: 'prev', label: 'Previous period' },
              ],
            },
          ]}
          value={st.compare ? 'prev' : 'none'}
          onPick={(v) => set({ compare: v === 'prev' })}
        />
      ) : null}
      {pop?.kind === 'sortby' ? (
        <SelectPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          search={false}
          groups={[
            {
              label: '',
              options: [
                { value: 'none', label: 'Report order' },
                { value: 'label', label: rowLabelOf(info) },
                { value: 'value', label: info.columns.value },
              ],
            },
          ]}
          value={st.sortBy}
          onPick={(v) => set({ sortBy: v as SortBy, page: 1 })}
        />
      ) : null}
      {pop?.kind === 'order' ? (
        <SelectPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          search={false}
          groups={[
            {
              label: '',
              options: [
                { value: 'asc', label: 'Ascending order' },
                { value: 'desc', label: 'Descending order' },
              ],
            },
          ]}
          value={st.order}
          onPick={(v) => set({ order: v as 'asc' | 'desc', page: 1 })}
        />
      ) : null}
      {pop?.kind === 'actions' ? (
        <MenuPop
          anchor={pop.el}
          onClose={() => setPop(null)}
          align="end"
          items={[
            {
              label: 'Copy report URL',
              onClick: () => {
                const u = reportUrl();
                if (navigator.clipboard) {
                  navigator.clipboard.writeText(u).then(
                    () => toast('Link copied'),
                    () => toast('Copy failed', 'danger'),
                  );
                } else toast(`Link: ${u}`, 'info');
              },
            },
            { label: 'Export', onClick: () => setDialog({ kind: 'export' }), disabled: !result },
            { label: 'Export unsummarized data', onClick: () => setDialog({ kind: 'exportRaw' }) },
            ...(info.segmentable
              ? [{ label: 'Use in segment', onClick: () => setDialog({ kind: 'segment' }) }]
              : []),
          ]}
        />
      ) : null}

      {/* dialogs */}
      {dialog?.kind === 'export' && result ? (
        <ExportDialog
          name={exportName}
          onClose={() => setDialog(null)}
          run={(name, format) => {
            downloadSheet(
              summarizedSheet(info, showPrev ? result : { ...result, previous: undefined }, sorted),
              name,
              format,
            );
            toast('Export started');
          }}
        />
      ) : null}
      {dialog?.kind === 'exportRaw' ? (
        <ExportDialog
          name={`${exportName} unsummarized`}
          onClose={() => setDialog(null)}
          run={async (name, format) => {
            const recs = await allRecords(info.key, query);
            downloadSheet(recordsSheet(recs), name, format);
            toast('Export started');
          }}
        />
      ) : null}
      {dialog?.kind === 'save' ? (
        <SaveReportDialog
          info={info}
          defaultName={exportName}
          query={{ ...query, ...(st.compare ? { compare: 'previous_period' as const } : {}) }}
          onClose={() => setDialog(null)}
        />
      ) : null}
      {dialog?.kind === 'segment' ? (
        <SegmentDialog
          info={info}
          query={query}
          rowId={dialog.rowId}
          onClose={() => setDialog(null)}
        />
      ) : null}
      {dialog?.kind === 'range' ? (
        <RangeDialog
          kind={dialog.range}
          current={st.range}
          onApply={(range) => set({ range, page: 1 })}
          onClose={() => setDialog(null)}
        />
      ) : null}
      {dialog?.kind === 'editqf' ? (
        <EditQuickFiltersDialog
          custom={st.custom.filter((k) => !fixed.includes(k))}
          options={allQf
            .filter((k) => !fixed.includes(k))
            .map((k) => ({ key: k, label: qfLabel(k) }))}
          onDone={(next) => {
            setCustom(next as QfKey[]);
            toast('Quick filters updated');
          }}
          onClose={() => setDialog(null)}
        />
      ) : null}
      {dialog?.kind === 'records' ? (
        <RecordsDialog
          info={info}
          title={dialog.title}
          query={query}
          rowId={dialog.rowId}
          chips={chips}
          currency={currency}
          onClose={() => setDialog(null)}
          onExport={() => {
            const rowId = dialog.rowId;
            setDialog(null);
            // The row's records, or the whole report's.
            setRowExport(rowId ?? null);
          }}
          onSave={() => setDialog({ kind: 'save' })}
          onSegment={
            info.segmentable ? () => setDialog({ kind: 'segment', rowId: dialog.rowId }) : undefined
          }
        />
      ) : null}
      {rowExport !== undefined ? (
        <ExportDialog
          name={`${exportName} records`}
          onClose={() => setRowExport(undefined)}
          run={async (name, format) => {
            const recs = await allRecords(info.key, {
              ...query,
              ...(rowExport ? { rowId: rowExport } : {}),
            });
            downloadSheet(recordsSheet(recs), name, format);
            toast('Export started');
          }}
        />
      ) : null}
    </div>
  );
}

/** The summarized table (design `sumTableHtml`): a value opens the row's records. */
function SummaryTable({
  rows,
  cols,
  info,
  result,
  showPrev,
  currency,
  onRow,
}: {
  rows: ReportRow[];
  cols: ReturnType<typeof tableColumns>;
  info: SalesReportInfo;
  result: SalesReportResult;
  showPrev: boolean;
  currency: string;
  onRow: (r: ReportRow) => void;
}) {
  const fmt = (v: number) => formatFigure(v, info.unit, currency);
  // LP9: the journey's Next step column (design `sa-jrt`, sales-analytics.js:5634).
  const next = hasNextStep(info) ? nextSteps(result.rows) : null;
  return (
    <div className="sa-tablewrap">
      <table className="sa-table sa-table--rv">
        <thead>
          <tr>
            <th scope="col">{rowLabelOf(info)}</th>
            {next ? <th scope="col">Next step</th> : null}
            {cols.map((c) => (
              <th key={c.id} scope="col" className="sa-num">
                {c.label}
              </th>
            ))}
            {showPrev ? (
              <>
                <th scope="col" className="sa-num">
                  Previous period
                </th>
                <th scope="col" className="sa-num">
                  Change
                </th>
              </>
            ) : null}
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r.key}>
              <th scope="row">{r.label}</th>
              {next ? <td>{next.get(r.key) ?? '–'}</td> : null}
              {cols.map((c) => (
                <td
                  key={c.id}
                  className="sa-num sa-tv"
                  tabIndex={0}
                  aria-haspopup="dialog"
                  title="View records"
                  onClick={() => onRow(r)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                      e.preventDefault();
                      onRow(r);
                    }
                  }}
                >
                  {formatCell(c, r, currency)}
                </td>
              ))}
              {showPrev ? (
                <>
                  <td className="sa-num">{r.prev === undefined ? '–' : fmt(r.prev)}</td>
                  <td
                    className={cn('sa-num', r.delta !== null && (r.delta >= 0 ? 'is-up' : 'is-dn'))}
                  >
                    {r.delta === null ? '–' : `${r.delta >= 0 ? '+' : ''}${r.delta.toFixed(1)}%`}
                  </td>
                </>
              ) : null}
            </tr>
          ))}
        </tbody>
        {result.total !== null ? (
          <tfoot>
            <tr>
              <th scope="row">Total</th>
              {next ? <td /> : null}
              <td className="sa-num">{fmt(result.total)}</td>
              {cols.slice(1).map((c) => (
                <td key={c.id} />
              ))}
              {showPrev ? (
                <>
                  <td className="sa-num">
                    {result.previous?.total == null ? '–' : fmt(result.previous.total)}
                  </td>
                  <td />
                </>
              ) : null}
            </tr>
          </tfoot>
        ) : null}
      </table>
    </div>
  );
}

const RAW_PAGE = 25;

/** The Unsummarized Dataset tab (design `rawTableHtml`): the report's records, page by page. */
function RawDataset({
  info,
  query,
  currency,
}: {
  info: SalesReportInfo;
  query: SalesReportQuery;
  currency: string;
}) {
  const [cursors, setCursors] = useState<Array<string | undefined>>([undefined]);
  const [page, setPage] = useState(0);
  const [data, setData] = useState<{
    rows: SalesReportRecord[];
    next: string | null;
    total?: number;
  } | null>(null);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    setCursors([undefined]);
    setPage(0);
  }, [info.key, query]);

  useEffect(() => {
    const ctrl = new AbortController();
    setData(null);
    setErr(null);
    listSalesReportRecords(
      info.key,
      { ...query, limit: RAW_PAGE, cursor: cursors[page] },
      { signal: ctrl.signal },
    ).then(
      (r) => {
        setData({ rows: r.data, next: r.nextCursor, total: r.total });
        if (r.nextCursor) {
          setCursors((c) => {
            const out = c.slice(0, page + 1);
            out[page + 1] = r.nextCursor!;
            return out;
          });
        }
      },
      (e: unknown) => {
        if (!ctrl.signal.aborted) setErr(errorText(e));
      },
    );
    return () => ctrl.abort();
    // The page's cursor is read when the page (or the query) changes.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [info.key, query, page]);

  if (err) {
    return (
      <p className="sa-muted" role="alert">
        The records could not be loaded: {err}
      </p>
    );
  }
  if (!data) return <p className="sa-muted">Loading…</p>;
  if (!data.rows.length && page === 0) {
    return (
      <div className="sa-rawempty">
        <div>
          <h3 className="sa-h3">No records match the current filters.</h3>
          <p className="sa-muted">
            Expecting to see new records? Try again in a few seconds as the system catches up.
          </p>
        </div>
        <EmptyArt />
      </div>
    );
  }
  const count = data.total ?? page * RAW_PAGE + data.rows.length;
  return (
    <>
      <div className="sa-tablewrap">
        <table className="sa-table sa-table--rv">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Type</th>
              <th scope="col">Owner</th>
              <th scope="col">Date</th>
              <th scope="col">Amount</th>
            </tr>
          </thead>
          <tbody>
            {data.rows.map((r) => {
              const href = recordHref(r);
              return (
                <tr key={`${r.objectType}:${r.id}`}>
                  <th scope="row">{href ? <Link href={href}>{r.name}</Link> : r.name}</th>
                  <td>{recordTypeLabel(r.objectType)}</td>
                  <td>{r.ownerName ?? ''}</td>
                  <td>{r.date ? formatDay(r.date.slice(0, 10)) : ''}</td>
                  <td>{r.amount === null ? '' : formatFigure(r.amount, 'currency', currency)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <nav className="sa-pager2" aria-label="Dataset pagination">
        <button
          type="button"
          className="sa-pgt"
          disabled={page === 0}
          onClick={() => setPage((p) => p - 1)}
        >
          <SaIcon name="back" className="sa-i--sm" />
          Prev
        </button>
        <button
          type="button"
          className="sa-pgn is-on"
          aria-current="page"
          aria-label={`Page ${page + 1}`}
        >
          {page + 1}
        </button>
        <button
          type="button"
          className="sa-pgt"
          disabled={!data.next}
          onClick={() => setPage((p) => p + 1)}
        >
          Next
          <SaIcon name="right" className="sa-i--sm" />
        </button>
        <span className="sa-muted sa-pgcount">
          {count.toLocaleString('en-US')}
          {data.total === undefined && data.next ? '+' : ''} records
        </span>
      </nav>
    </>
  );
}
