'use client';

import Link from 'next/link';
import { useEffect, useMemo, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { listAllLists, type CrmList } from '@/features/lists/api.client';
import { dayIn } from '@/features/list-page/listZone';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  CHANNEL_CATEGORIES,
  CHANNEL_CARDS,
  COMPARE_TABLES,
  addCompareColumn,
  compareCandidates,
  compareDateText,
  defaultPerfRange,
  emptyCompare,
  nextTabIndex,
  rangeDays,
  rangePillText,
  removeCompareCol2,
  removeCompareCol3,
  selectCompare,
  shortDate,
  visibleChannels,
  type ChannelCategory,
  type CompareState,
  type PerfSubview,
} from '../performance';
import {
  compareChartConfig,
  historyQuery,
  sizeChartConfig,
  sizeText,
  weekChange as weekChangeOf,
  weekChangeQuery,
  weekChangeText,
} from '../history';
import { NO_VALUE, segmentTypeLabel } from '../segment';
import { SegDropdown } from './primitives';
import {
  breakdownChartConfig,
  breakdownSlices,
  overlapChartConfig,
  type BreakdownKey,
} from '../breakdown';
import { BreakdownLegend } from './BreakdownLegend';
import { engagementChartConfig, engagementValues } from '../engagement';
import { ChartCanvas, themeColor, useBreakdown, useEngagement, useSizes } from './SizeCharts';
import { SegDateRangePicker } from './SegDateRangePicker';

export type { PerfSubview } from '../performance';

const SUBVIEWS: readonly PerfSubview[] = ['breakdown', 'comparison', 'available-channels'];

const AGGREGATIONS = [
  { value: 'over-time', label: 'Over time' },
  { value: 'version', label: 'Over time by version' },
] as const;

const BREAKDOWN_KEYS: readonly { value: BreakdownKey; label: string }[] = [
  { value: 'source', label: 'Source' },
  { value: 'lifecycle', label: 'Lifecycle stage' },
  { value: 'leadStatus', label: 'Lead status' },
  { value: 'owner', label: 'Contact owner' },
];

/** The compare legends' colours (JS:1745-1764). */
const SLOT_COLORS = ['var(--brand)', 'var(--accent)', 'var(--success)'];

function isoDay(d: Date): string {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

/**
 * DI-3: the Performance tab (`data-vcs-tab-pane="performance"`, PHP:353-1149; JS:673-2193). The
 * segment size chart and table, the Segment Size Report and the 7-day changes come from the size
 * history (API #229); the breakdown pie and legend from the list's breakdown (API #258); the
 * Segment Overlap doughnut from the chosen lists' sizes. The other charts keep their canvases but
 * draw nothing, and every number the API lacks is `--`. The compare picker reads the real contact
 * lists.
 */
export function PerformancePane({
  list,
  subview,
  onSubview,
  weekChange,
}: {
  list: CrmList;
  subview: PerfSubview;
  onSubview: (v: PerfSubview) => void;
  /** This segment's 7-day change (SegmentView loads it for the Overview too); null until known. */
  weekChange?: number | null;
}) {
  const toast = useToast();
  const { timeZone } = useUserPrefs();
  const createdDay = (() => {
    const at = new Date(list.createdAt);
    return Number.isNaN(at.getTime()) ? undefined : isoDay(dayIn(at, timeZone));
  })();

  // Sub-nav (JS:2126-2193)
  const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
  const mounted = useRef(false);
  useEffect(() => {
    if (!mounted.current) {
      mounted.current = true;
      return;
    }
    const btn = tabRefs.current[SUBVIEWS.indexOf(subview)];
    btn?.scrollIntoView?.({ behavior: 'smooth', block: 'nearest', inline: 'center' });
  }, [subview]);
  const onNavKey = (e: React.KeyboardEvent) => {
    const current = tabRefs.current.findIndex((b) => b === document.activeElement);
    if (current === -1) return;
    const next = nextTabIndex(e.key, current, SUBVIEWS.length);
    if (next === null) return;
    e.preventDefault();
    tabRefs.current[next]?.focus();
    onSubview(SUBVIEWS[next]!);
  };

  // Breakdown (PHP:377-549)
  const [range, setRange] = useState(() => defaultPerfRange(timeZone));
  const [agg, setAgg] = useState<(typeof AGGREGATIONS)[number]['value']>('over-time');
  const [viewMode, setViewMode] = useState<'chart' | 'table'>('chart');
  const [breakdownKey, setBreakdownKey] = useState<BreakdownKey>('source');

  // Comparison (PHP:552-977)
  const [compareRange, setCompareRange] = useState(() => defaultPerfRange(timeZone));
  const [compare, setCompare] = useState<CompareState>(emptyCompare);
  const [lists, setLists] = useState<CrmList[] | null>(null);
  const [search, setSearch] = useState<{ 2: string; 3: string }>({ 2: '', 3: '' });
  const fetched = useRef(false);
  const openCol3 = useRef(false);

  useEffect(() => {
    if (subview !== 'comparison' || fetched.current) return;
    fetched.current = true;
    let live = true;
    let done = false;
    listAllLists()
      .then((res) => {
        if (!live) return;
        done = true;
        setLists(res.lists);
      })
      .catch((err: unknown) => {
        if (!live) return;
        done = true;
        setLists([]);
        toast(errorText(err), 'danger');
      });
    return () => {
      live = false;
      // Left before the lists came back (or a StrictMode re-run): fetch again next time.
      if (!done) fetched.current = false;
    };
  }, [subview, toast]);

  // +Add opens column 3's menu (JS:1990-1996).
  useEffect(() => {
    if (!compare.col3 || !openCol3.current) return;
    openCol3.current = false;
    document.getElementById('vcsCompareToggleBtn3')?.click();
  }, [compare.col3]);

  // Size history (API #229). The chart draws only on the client, once Chart.js has loaded.
  const sizeQuery = useMemo(() => historyQuery(range, timeZone), [range, timeZone]);
  const sizes = useSizes(list.id, sizeQuery, subview === 'breakdown', list.memberCount);
  const sizeLabel = agg === 'version' ? 'Version 1' : list.name;
  const sizeConfig = useMemo(
    () =>
      sizes
        ? sizeChartConfig({
            days: sizes,
            label: sizeLabel,
            type: 'line',
            colors: {
              brand: themeColor('--brand', '#2456e6'),
              brandSoft: themeColor('--brand-soft', 'rgba(36, 86, 230, 0.08)'),
            },
          })
        : null,
    [sizes, sizeLabel],
  );

  // Breakdown pie and legend (API #258), in the design's colours (JS:1193-1196).
  const breakdown = useBreakdown(list.id, breakdownKey, subview === 'breakdown', list.memberCount);
  const slices = useMemo(
    () =>
      breakdown
        ? breakdownSlices(breakdown, breakdownKey, [
            themeColor('--brand', '#2456e6'),
            themeColor('--accent', '#f28f23'),
            themeColor('--success', '#067647'),
            themeColor('--warning', '#b54708'),
          ])
        : null,
    [breakdown, breakdownKey],
  );
  const breakdownConfig = useMemo(() => (slices ? breakdownChartConfig(slices) : null), [slices]);

  // SEG2b C6b: "In the last 30 days" (JS:1277-1385): the two email counts; `--` where no data.
  const engagement = useEngagement(list.id, subview === 'breakdown', list.memberCount);
  const engagementConfig = useMemo(
    () =>
      engagement === undefined
        ? null
        : engagementChartConfig(engagementValues(engagement), themeColor('--brand', '#2456e6')),
    [engagement],
  );

  const comparing = subview === 'comparison';
  // Segment Overlap Report: each chosen list's size (JS:1769-1781).
  const overlapConfig = useMemo(() => {
    if (!comparing) return null;
    const colors = [
      themeColor('--brand', '#2456e6'),
      themeColor('--accent', '#f28f23'),
      themeColor('--success', '#067647'),
    ];
    const chosen = [list, compare.slot2, compare.slot3].filter((l): l is CrmList => !!l);
    return overlapChartConfig(
      chosen.map((l, i) => ({ name: l.name, size: l.memberCount, color: colors[i]! })),
    );
  }, [comparing, list, compare.slot2, compare.slot3]);
  const weekQuery = useMemo(() => weekChangeQuery(timeZone), [timeZone]);
  const week2 = useSizes(
    compare.slot2?.id ?? null,
    weekQuery,
    comparing,
    compare.slot2?.memberCount,
  );
  const week3 = useSizes(
    compare.slot3?.id ?? null,
    weekQuery,
    comparing,
    compare.slot3?.memberCount,
  );
  const compareQuery = useMemo(
    () => historyQuery(compareRange, timeZone),
    [compareRange, timeZone],
  );
  const report1 = useSizes(list.id, compareQuery, comparing, list.memberCount);
  const report2 = useSizes(
    compare.slot2?.id ?? null,
    compareQuery,
    comparing,
    compare.slot2?.memberCount,
  );
  const report3 = useSizes(
    compare.slot3?.id ?? null,
    compareQuery,
    comparing,
    compare.slot3?.memberCount,
  );
  const reportConfig = useMemo(() => {
    // Drawn once every chosen list's sizes are in.
    if (!report1 || (compare.slot2 && !report2) || (compare.slot3 && !report3)) return null;
    const series = [{ label: list.name, days: report1 }];
    if (compare.slot2 && report2) series.push({ label: compare.slot2.name, days: report2 });
    if (compare.slot3 && report3) series.push({ label: compare.slot3.name, days: report3 });
    return compareChartConfig({
      series,
      colors: [
        themeColor('--brand', '#2456e6'),
        themeColor('--accent', '#f28f23'),
        themeColor('--success', '#067647'),
      ],
      fills: [
        themeColor('--brand-soft', 'rgba(36, 86, 230, 0.08)'),
        'rgba(242, 143, 35, 0.08)',
        'rgba(6, 118, 71, 0.08)',
      ],
    });
  }, [report1, report2, report3, compare.slot2, compare.slot3, list.name]);
  const cardChange = (slot: 1 | 2 | 3) =>
    weekChangeText(slot === 1 ? (weekChange ?? null) : weekChangeOf(slot === 2 ? week2 : week3));

  // Available channels (PHP:980-1146)
  const [channelCat, setChannelCat] = useState<ChannelCategory>('all');
  const shown = visibleChannels(channelCat);

  const infoTip = (tip: string, label: string) => (
    <div className="vcs-tooltip-trigger" data-tooltip={tip}>
      <button type="button" className="vcs-perf-info-btn" aria-label={label}>
        <CrmIcon name="info" className="iconSize-14" />
      </button>
    </div>
  );

  const comparePicker = (slot: 2 | 3) => {
    const selected = slot === 2 ? compare.slot2 : compare.slot3;
    const items = lists ? compareCandidates(lists, list.id, search[slot]) : null;
    return (
      <SegDropdown
        className="vcs-compare-dropdown"
        toggle={
          <>
            <span className="vcs-compare-select-text" id={`vcsCompareSelectedText${slot}`}>
              {selected ? selected.name : 'Select segment to compare'}
            </span>
            <CrmIcon name="chevron-down" className="iconSize-12" />
          </>
        }
        toggleClassName="vcs-compare-select-btn"
        toggleId={`vcsCompareToggleBtn${slot}`}
        menuClassName="vcs-compare-menu"
      >
        {(close) => (
          <>
            <div className="vcs-compare-search-wrap">
              <input
                type="text"
                className="vcs-compare-search-input"
                placeholder="Search"
                id={`vcsCompareSearch${slot}`}
                autoComplete="off"
                value={search[slot]}
                onChange={(e) => setSearch((s) => ({ ...s, [slot]: e.target.value }))}
              />
              <CrmIcon name="search" className="iconSize-14" />
            </div>
            <div className="vcs-compare-items-list" id={`vcsCompareList${slot}`}>
              {items && items.length === 0 ? (
                <div className="crm-p-3 crm-text-muted crm-fs-8 text-center">No segments found</div>
              ) : (
                items?.map((l) => (
                  <button
                    key={l.id}
                    type="button"
                    className={cn('vcs-compare-item', selected?.id === l.id && 'is-selected')}
                    data-slot={slot}
                    data-seg-id={l.id}
                    onClick={() => {
                      setCompare((s) => selectCompare(s, slot, l));
                      close();
                    }}
                  >
                    <span className="vcs-compare-item-name">{l.name}</span>
                  </button>
                ))
              )}
            </div>
          </>
        )}
      </SegDropdown>
    );
  };

  const overviewCard = (slot: 1 | 2 | 3, seg: CrmList | null) => {
    const ids = slot !== 1;
    return (
      <div
        key={slot}
        className="vcs-compare-overview-card"
        data-col-card={slot}
        id={ids ? `vcsCompareOverviewCard${slot}` : undefined}
        hidden={!seg}
      >
        <div className="vcs-compare-overview-card__header">
          {seg ? (
            <Link
              href={`/lists/${seg.id}`}
              className="vcs-compare-card-title"
              id={ids ? `vcsCompareCardTitle${slot}` : undefined}
              title={seg.name}
            >
              {seg.name}
            </Link>
          ) : (
            <a href="#" className="vcs-compare-card-title" id={`vcsCompareCardTitle${slot}`}>
              {NO_VALUE}
            </a>
          )}
          <div className="vcs-compare-card-meta">
            <div className="vcs-compare-meta-item">
              <span className="vcs-compare-meta-label">Segment type</span>
              <span
                className="vcs-compare-meta-val"
                id={ids ? `vcsCompareCardType${slot}` : undefined}
              >
                <span className="vcs-compare-bullet"></span>{' '}
                {seg ? segmentTypeLabel(seg) : NO_VALUE}
              </span>
            </div>
            <div className="vcs-compare-meta-item">
              <span className="vcs-compare-meta-label">Create date</span>
              <span
                className="vcs-compare-meta-val"
                id={ids ? `vcsCompareCardDate${slot}` : undefined}
              >
                {compareDateText(seg?.createdAt, timeZone)}
              </span>
            </div>
          </div>
        </div>
        <div className="vcs-compare-overview-card__metrics">
          <div className="vcs-compare-metric-row">
            <span className="vcs-compare-k">SIZE</span>
            <span
              className="vcs-compare-v vcs-compare-v--brand"
              id={ids ? `vcsCompareCardSize${slot}` : undefined}
            >
              {seg ? seg.memberCount : NO_VALUE}
            </span>
          </div>
          <div className="vcs-compare-metric-row">
            <span className="vcs-compare-k">USED IN</span>
            <span
              className="vcs-compare-v vcs-compare-v--brand"
              id={ids ? `vcsCompareCardUsed${slot}` : undefined}
            >
              {NO_VALUE}
            </span>
          </div>
          <div className="vcs-compare-metric-row">
            <span className="vcs-compare-k">7-DAY CHANGE</span>
            <span
              className="vcs-compare-v vcs-compare-v--muted"
              id={ids ? `vcsCompareCardChange${slot}` : undefined}
            >
              {seg ? cardChange(slot) : NO_VALUE}
            </span>
          </div>
        </div>
      </div>
    );
  };

  const legendNames = [list, compare.slot2, compare.slot3].filter((l): l is CrmList => !!l);

  return (
    <div className="vcs-perf-layout">
      <nav
        className="set-tabs set-tabs--boxed vcs-subnav-tabs vcs-perf-sidebar"
        role="tablist"
        aria-label="Performance navigation"
        onKeyDown={onNavKey}
      >
        <button
          type="button"
          className={cn('set-tab vcs-perf-nav-btn', subview === 'breakdown' && 'is-active active')}
          data-perf-nav="breakdown"
          role="tab"
          aria-selected={subview === 'breakdown'}
          ref={(el) => {
            tabRefs.current[0] = el;
          }}
          onClick={() => onSubview('breakdown')}
        >
          <span>Segment breakdown</span>
        </button>
        <button
          type="button"
          className={cn('set-tab vcs-perf-nav-btn', subview === 'comparison' && 'is-active active')}
          data-perf-nav="comparison"
          role="tab"
          aria-selected={subview === 'comparison'}
          ref={(el) => {
            tabRefs.current[1] = el;
          }}
          onClick={() => onSubview('comparison')}
        >
          <span>Segment comparison</span>
          <span className="vcs-perf-dot-purple" aria-hidden="true"></span>
        </button>
        <button
          type="button"
          className={cn(
            'set-tab vcs-perf-nav-btn vcs-perf-nav-btn--channel',
            subview === 'available-channels' && 'is-active active',
          )}
          data-perf-nav="available-channels"
          role="tab"
          aria-selected={subview === 'available-channels'}
          ref={(el) => {
            tabRefs.current[2] = el;
          }}
          onClick={() => onSubview('available-channels')}
        >
          <span className="vcs-perf-nav-channel-inner">
            <CrmIcon name="sparkles" className="iconSize-14" />
            <span>Available channels</span>
          </span>
        </button>
      </nav>

      <div className="vcs-perf-content">
        {/* Subview 1: Segment breakdown (PHP:377-549) */}
        <div
          className="vcs-perf-subview is-active"
          id="vcsPerfBreakdownView"
          hidden={subview !== 'breakdown'}
        >
          <div className="vcs-perf-topbar">
            <h2 className="vcs-perf-title">Segment size</h2>
            <div className="vcs-perf-date-picker">
              <span className="vcs-perf-date-label">Date range:</span>
              <div className="cad-date-picker-wrap quick-filters-container" id="vcsPerfDatePicker">
                <SegDateRangePicker
                  start={range.start}
                  end={range.end}
                  onChange={(start, end) => setRange({ start, end })}
                  allTimeStart={createdDay}
                  startId="vcsPerfStartDate"
                  endId="vcsPerfEndDate"
                />
              </div>
            </div>
          </div>

          <div className="vcs-perf-card">
            <div className="vcs-perf-card__header">
              <div className="vcs-perf-card__controls-left">
                <SegDropdown
                  toggle={
                    <>
                      <span id="vcsPerfOverTimeVal">
                        {AGGREGATIONS.find((a) => a.value === agg)!.label}
                      </span>
                      <CrmIcon name="chevron-down" className="iconSize-12" />
                    </>
                  }
                  toggleClassName="lp-btn lp-btn--outline lp-btn--sm"
                  toggleId="vcsPerfOverTimeBtn"
                  menuClassName=""
                >
                  {AGGREGATIONS.map((a) => (
                    <button
                      key={a.value}
                      type="button"
                      className={cn('dropdown__item', agg === a.value && 'is-selected')}
                      data-perf-agg={a.value}
                      onClick={() => setAgg(a.value)}
                    >
                      {a.label}
                    </button>
                  ))}
                </SegDropdown>

                <div
                  className="vcs-perf-view-toggle"
                  role="group"
                  aria-label="Chart / Table view toggle"
                >
                  <button
                    type="button"
                    className={cn('vcs-perf-toggle-btn', viewMode === 'chart' && 'is-active')}
                    id="vcsPerfTypeChart"
                    title="Chart view"
                    aria-pressed={viewMode === 'chart'}
                    onClick={() => setViewMode('chart')}
                  >
                    <CrmIcon name="chart" className="iconSize-14" />
                  </button>
                  <button
                    type="button"
                    className={cn('vcs-perf-toggle-btn', viewMode === 'table' && 'is-active')}
                    id="vcsPerfTypeTable"
                    title="Table view"
                    aria-pressed={viewMode === 'table'}
                    onClick={() => setViewMode('table')}
                  >
                    <svg
                      className="icon iconSize-14"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="1.8"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      aria-hidden="true"
                    >
                      <rect x="3" y="4" width="18" height="16" rx="2" />
                      <path d="M3 10h18M3 15h18M10 4v16" />
                    </svg>
                  </button>
                </div>

                {infoTip(
                  'Counts the active contacts in this segment measured daily over the selected date range.',
                  'Chart information',
                )}
              </div>
            </div>

            <div className="vcs-perf-card__badge-row">
              <span className="vcs-perf-filter-pill" id="vcsPerfRangePill">
                {rangePillText(range.start, range.end)}
              </span>
            </div>

            <div
              className="vcs-perf-chart-container vcs-perf-chart-container--line"
              id="vcsPerfChartWrap"
              hidden={viewMode !== 'chart'}
            >
              <ChartCanvas
                id="vcsPerfSizeChart"
                config={viewMode === 'chart' ? sizeConfig : null}
              />
            </div>

            <div
              className="vcs-perf-table-wrap"
              id="vcsPerfTableWrap"
              hidden={viewMode !== 'table'}
            >
              <div className="vcs-perf-table-header">
                <span className="vcs-perf-table-column-name" id="vcsPerfTableColName">
                  {agg === 'version' ? 'Version 1' : list.name}
                </span>
              </div>
              <div className="vcs-perf-table-list" id="vcsPerfTableList">
                {viewMode === 'table' &&
                  rangeDays(range.start, range.end).map((d) => (
                    <div key={d} className="vcs-perf-table-row">
                      <span className="vcs-perf-table-cell-date">{shortDate(d)}</span>
                      <span className="vcs-perf-table-cell-val">{sizeText(sizes, d)}</span>
                    </div>
                  ))}
              </div>
            </div>
          </div>

          <div className="vcs-perf-card">
            <div className="vcs-perf-card__header">
              <h3 className="vcs-perf-card__title">Contacts breakdown and engagement</h3>
              <div className="vcs-perf-card__controls-right crm-d-flex crm-align-items-center crm-gap-2">
                <div className="vcs-perf-select-wrap">
                  <span className="vcs-perf-control-label">Segment contacts by:</span>
                  <SegDropdown
                    toggle={
                      <>
                        <span id="vcsPerfBreakdownVal">
                          {BREAKDOWN_KEYS.find((k) => k.value === breakdownKey)!.label}
                        </span>
                        <CrmIcon name="chevron-down" className="iconSize-12" />
                      </>
                    }
                    toggleClassName="lp-btn lp-btn--outline lp-btn--sm"
                    toggleId="vcsPerfBreakdownBtn"
                  >
                    {BREAKDOWN_KEYS.map((k) => (
                      <button
                        key={k.value}
                        type="button"
                        className={cn('dropdown__item', breakdownKey === k.value && 'is-selected')}
                        data-breakdown-key={k.value}
                        onClick={() => setBreakdownKey(k.value)}
                      >
                        {k.label}
                      </button>
                    ))}
                  </SegDropdown>
                </div>
              </div>
            </div>

            <div className="vcs-perf-breakdown-body">
              <div className="vcs-perf-pie-box">
                <ChartCanvas id="vcsPerfBreakdownChart" config={breakdownConfig} />
              </div>
              <BreakdownLegend slices={slices} />
            </div>
          </div>

          <div className="vcs-perf-card">
            <div className="vcs-perf-card__header crm-flex-column crm-align-items-start crm-gap-1">
              <h3 className="vcs-perf-card__title">
                In the last 30 days, this is the count of contacts in this segment who:
              </h3>
              <div className="vcs-perf-event-legend">
                <span
                  className="vcs-perf-legend-bullet"
                  style={{ backgroundColor: 'var(--brand)' }}
                ></span>
                <span className="crm-fs-8 crm-text-muted">(Count) Contacts</span>
              </div>
            </div>

            <div className="vcs-perf-chart-container vcs-perf-chart-container--bar">
              <ChartCanvas id="vcsPerfEventsChart" config={engagementConfig} />
            </div>
          </div>
        </div>

        {/* Subview 2: Segment comparison (PHP:552-977) */}
        <div
          className="vcs-perf-subview"
          id="vcsPerfComparisonView"
          hidden={subview !== 'comparison'}
        >
          <div className="vcs-perf-card vcs-compare-card">
            <div className="vcs-compare-head-row">
              <div></div>
              <button
                type="button"
                disabled
                className="lp-btn lp-btn--outline lp-btn--sm vcs-compare-builder-btn"
                id="vcsOpenReportBuilder"
              >
                <span>Open in Report Builder</span>
                <CrmIcon name="external" className="iconSize-14" />
              </button>
            </div>

            <div className="vcs-compare-hero">
              <h2 className="vcs-compare-hero-title">Compare segments</h2>
              <p className="vcs-compare-hero-subtitle">
                Choose the segments you want to compare below. You can add up to 3 segments to
                compare.
              </p>
            </div>

            <div className="vcs-compare-daterange-wrap">
              <span className="vcs-perf-date-label">Date range:</span>
              <div
                className="cad-date-picker-wrap quick-filters-container"
                id="vcsCompareDatePicker"
              >
                <SegDateRangePicker
                  start={compareRange.start}
                  end={compareRange.end}
                  onChange={(start, end) => setCompareRange({ start, end })}
                  allTimeStart={createdDay}
                  startId="vcsCompareStartDate"
                  endId="vcsCompareEndDate"
                />
              </div>
            </div>

            <div className="vcs-compare-selectors-grid" id="vcsCompareSelectorsGrid">
              <div className="vcs-compare-col" data-compare-col="1">
                <label className="vcs-compare-col-label">Segment</label>
                <div
                  className="vcs-compare-select-btn vcs-compare-select-btn--static"
                  title={list.name}
                >
                  <span className="vcs-compare-select-text">{list.name}</span>
                  <CrmIcon name="chevron-down" className="iconSize-12" />
                </div>
              </div>

              <div className="vcs-compare-col" data-compare-col="2">
                <div className="vcs-compare-col-header">
                  <label className="vcs-compare-col-label">Segment</label>
                  <button
                    type="button"
                    className="vcs-compare-remove-btn"
                    id="vcsCompareRemoveCol2"
                    title="Remove segment"
                    hidden={!compare.col3}
                    // SEG1 B6: the design keeps the pickers' search text (JS:2027-2076).
                    onClick={() => setCompare(removeCompareCol2)}
                  >
                    <CrmIcon name="trash" className="iconSize-12" />
                    <span>Remove</span>
                  </button>
                </div>
                <div className="vcs-compare-picker-row">
                  {comparePicker(2)}
                  <button
                    type="button"
                    className="vcs-compare-add-btn"
                    id="vcsCompareAddBtn"
                    hidden={compare.col3}
                    onClick={() => {
                      openCol3.current = true;
                      setCompare(addCompareColumn);
                    }}
                  >
                    +Add
                  </button>
                </div>
              </div>

              <div
                className="vcs-compare-col"
                data-compare-col="3"
                id="vcsCompareCol3"
                hidden={!compare.col3}
              >
                <div className="vcs-compare-col-header">
                  <label className="vcs-compare-col-label">Segment</label>
                  <button
                    type="button"
                    className="vcs-compare-remove-btn"
                    id="vcsCompareRemoveCol3"
                    title="Remove segment"
                    onClick={() => setCompare(removeCompareCol3)}
                  >
                    <CrmIcon name="trash" className="iconSize-12" />
                    <span>Remove</span>
                  </button>
                </div>
                <div className="vcs-compare-picker-row">{comparePicker(3)}</div>
              </div>
            </div>

            <div className="vcs-compare-section">
              <h3 className="vcs-compare-section-title">Overview</h3>
              <div className="vcs-compare-overview-grid" id="vcsCompareOverviewGrid">
                {overviewCard(1, list)}
                {overviewCard(2, compare.slot2)}
                {overviewCard(3, compare.slot3)}
              </div>
            </div>

            {COMPARE_TABLES.map((t) => (
              <div key={t.id} className="vcs-compare-section">
                <h3 className="vcs-compare-section-title">{t.title}</h3>
                <table className="vcs-compare-data-table" id={t.id}>
                  <tbody>
                    {t.rows.map((row) => (
                      <tr key={row}>
                        <td className="vcs-compare-td--label">{row}</td>
                        <td className="vcs-compare-td--val" data-col-metric="1">
                          {NO_VALUE}
                        </td>
                        <td
                          className="vcs-compare-td--val"
                          data-col-metric="2"
                          hidden={!compare.slot2}
                        >
                          {NO_VALUE}
                        </td>
                        <td
                          className="vcs-compare-td--val"
                          data-col-metric="3"
                          hidden={!compare.slot3}
                        >
                          {NO_VALUE}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ))}
          </div>

          <div className="vcs-perf-card vcs-compare-report-card">
            <div className="vcs-perf-card__header">
              <div className="crm-d-flex crm-align-items-center crm-gap-1">
                <h3 className="vcs-perf-card__title">Segment Overlap Report</h3>
                {infoTip(
                  'Compares contact overlap across selected segments.',
                  'Overlap report information',
                )}
              </div>
            </div>

            <div className="vcs-perf-card__badge-row">
              <span className="vcs-perf-filter-pill">Filters (1)</span>
            </div>

            <div className="vcs-compare-overlap-legend" id="vcsCompareOverlapLegend">
              {legendNames.map((l, i) => (
                <div key={`${i}-${l.id}`} className="vcs-perf-legend-item">
                  <span
                    className="vcs-perf-legend-bullet"
                    style={{ backgroundColor: SLOT_COLORS[i] }}
                  ></span>
                  <span
                    className="vcs-perf-legend-label"
                    id={i === 0 ? 'vcsOverlapLegendName1' : undefined}
                    title={l.name}
                  >
                    {l.name}
                  </span>
                </div>
              ))}
            </div>

            <div className="vcs-compare-overlap-chart-container">
              <div className="vcs-compare-overlap-circle-wrap">
                <ChartCanvas id="vcsCompareOverlapChart" config={overlapConfig} />
              </div>
            </div>
          </div>

          <div className="vcs-perf-card vcs-compare-report-card">
            <div className="vcs-perf-card__header">
              <div className="crm-d-flex crm-align-items-center crm-gap-1">
                <h3 className="vcs-perf-card__title">Segment Size Report</h3>
                {infoTip(
                  'Compares segment sizes over time across the selected date range.',
                  'Size report information',
                )}
              </div>
            </div>

            <div
              className="vcs-perf-chart-container vcs-perf-chart-container--line"
              id="vcsCompareSizeWrap"
            >
              <ChartCanvas id="vcsCompareSizeChart" config={comparing ? reportConfig : null} />
            </div>
          </div>
        </div>

        {/* Subview 3: Available channels (PHP:980-1146) */}
        <div
          className="vcs-perf-subview"
          id="vcsPerfChannelsView"
          hidden={subview !== 'available-channels'}
        >
          <div className="vcs-channels-filters" role="tablist" aria-label="Channel categories">
            {CHANNEL_CATEGORIES.map((c) => (
              <button
                key={c.value}
                type="button"
                className={cn('vcs-channels-pill', channelCat === c.value && 'is-active')}
                data-channel-cat={c.value}
                onClick={() => setChannelCat(c.value)}
              >
                {c.label}
              </button>
            ))}
          </div>

          <div className="vcs-channels-grid" id="vcsChannelsGrid">
            {CHANNEL_CARDS.map((card) => (
              <div
                key={card.title}
                className="vcs-channel-card"
                data-cat={card.cat}
                hidden={!shown.includes(card)}
              >
                <div className="vcs-channel-card__body">
                  <span className={`vcs-channel-badge vcs-channel-badge--${card.cat}`}>
                    {card.badge}
                  </span>
                  <h3 className="vcs-channel-title">{card.title}</h3>
                  <p className="vcs-channel-desc">{card.desc}</p>
                </div>
                <div className="vcs-channel-card__foot">
                  {card.href ? (
                    // SEG1 A6: the page the design links to.
                    <Link className="vcs-channel-link" href={card.href}>
                      <span>{card.link}</span>
                      <CrmIcon name="external" className="iconSize-14" />
                    </Link>
                  ) : null}
                </div>
              </div>
            ))}
          </div>

          <div className="vcs-channels-empty" id="vcsChannelsEmpty" hidden={shown.length > 0}>
            <p className="crm-text-muted crm-mb-0">No available channels found in this category.</p>
          </div>
        </div>
      </div>
    </div>
  );
}
