'use client';

import Link from 'next/link';
import {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { listTeamOptions, type TeamOption } from '@/features/members/api.client';
import { ownerDisplayName } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';
import { useReport } from '@/features/reports/ui/shared';
import { getSequenceAnalytics } from '@/features/sequences/api.client';
import type {
  SequenceAnalytics,
  SequenceAnalyticsQuery,
  SequenceAnalyticsStatus,
  SequenceAnalyticsStepType,
} from '@/features/sequences/types';
import { addDays, mondayOf } from '@/lib/utils/timezone';
import { cn } from '@/lib/utils/cn';
import { ChevronDown, DropMenu, timeAgo, type DropMenuItem } from './DropMenu';
import {
  STEP_TYPE_COLORS,
  StackedBarChart,
  TimeLineChart,
  ValueColumnChart,
  type LinePoint,
} from './SequenceCharts';

export const STATUS_LABELS: Record<SequenceAnalyticsStatus, string> = {
  scheduled: 'Scheduled',
  in_progress: 'In progress',
  paused: 'Paused',
  finished: 'Finished',
  error: 'Error',
};

const STEP_TYPES: Array<{ key: SequenceAnalyticsStepType; short: string; long: string }> = [
  { key: 'automated_email', short: 'Auto email', long: 'Automated email' },
  { key: 'manual_email', short: 'Manual email', long: 'Manual email task' },
  { key: 'call_task', short: 'Call', long: 'Call task' },
  { key: 'task', short: 'General', long: 'General task' },
];

const METRICS = [
  { key: 'meetings', label: 'Booked meetings' },
  { key: 'enrollments', label: 'Enrollments' },
  { key: 'replies', label: 'Replies' },
  { key: 'opened', label: 'Opened' },
  { key: 'clicked', label: 'Clicked' },
] as const;
type MetricKey = (typeof METRICS)[number]['key'];

const FREQUENCIES = [
  { key: 'daily', label: 'Daily' },
  { key: 'weekly', label: 'Weekly' },
  { key: 'monthly', label: 'Monthly' },
  // GAP-r60: HubSpot's Frequency also has Quarterly and Yearly.
  { key: 'quarterly', label: 'Quarterly' },
  { key: 'yearly', label: 'Yearly' },
] as const;
type Frequency = (typeof FREQUENCIES)[number]['key'];

const PAGE_SIZE = 5;

/** 0.5 → "50%", 0.1435 → "14.35%"; nothing to divide → "0%". */
export function pct(part: number, whole: number, decimals = 2): string {
  if (!whole) return '0%';
  return `${Number(((part / whole) * 100).toFixed(decimals))}%`;
}

function shortDate(iso: string, withYear = true): string {
  const d = new Date(iso.length === 10 ? `${iso}T00:00:00` : iso);
  if (Number.isNaN(d.getTime())) return '-';
  return d.toLocaleDateString(undefined, {
    month: 'short',
    day: 'numeric',
    ...(withYear ? { year: 'numeric' } : {}),
  });
}

export function InfoIcon({ hint }: { hint: string }) {
  return (
    <span className="seqa-info" title={hint} aria-label={hint} role="img">
      <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor">
        <circle cx="12" cy="12" r="9" strokeWidth="1.8" />
        <path d="M12 11v6M12 7.5v.5" strokeWidth="2" strokeLinecap="round" />
      </svg>
    </span>
  );
}

/** What a stat's drill-down shows (HubSpot: each stat value opens a modal). */
interface StatDetail {
  label: string;
  value: ReactNode;
  sub: ReactNode;
}
const StatDrillContext = createContext<((stat: StatDetail) => void) | null>(null);

/** A stat's number as "0", "0%" or "$0.00" is empty. */
const isZero = (value: ReactNode) =>
  typeof value === 'string' && Number(value.replace(/[^0-9.-]/g, '')) === 0;

/**
 * Makes the stats under it open a modal on click, with the filters in force (HubSpot: "Filters
 * (2)"). The API gives numbers, not the records behind them, so the modal repeats the numbers.
 */
export function StatDrill({ filters, children }: { filters: string[]; children: ReactNode }) {
  const [stat, setStat] = useState<StatDetail | null>(null);
  const id = 'seqaStatDrill';
  const close = () => setStat(null);
  return (
    <StatDrillContext.Provider value={setStat}>
      {children}
      <CrmModal id={id} open={stat !== null} onClose={close}>
        <ModalHeader id={id} title={stat?.label ?? ''} onClose={close} />
        <div className="modal__body">
          <p className="crm-mt-0">
            <strong>{stat?.value}</strong> <span className="crm-text-muted">{stat?.sub}</span>
          </p>
          {filters.length ? (
            <p className="crm-fs-8 crm-text-muted" title={filters.join('\n')}>
              <strong>Filters ({filters.length})</strong>: {filters.join(' · ')}
            </p>
          ) : null}
          {stat && isZero(stat.value) ? (
            <p className="seqm-empty crm-mb-0">
              There is no data to show in this time frame. Try changing the date range.
            </p>
          ) : null}
        </div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
            Close
          </button>
        </div>
      </CrmModal>
    </StatDrillContext.Provider>
  );
}

export function Stat({
  label,
  hint,
  value,
  sub,
}: {
  label: string;
  hint?: string;
  value: ReactNode;
  sub: ReactNode;
}) {
  const open = useContext(StatDrillContext);
  return (
    <div className="seqa-stat">
      <div className="seqa-stat__label">
        {label}
        {hint ? <InfoIcon hint={hint} /> : null}
      </div>
      <div className="seqa-stat__value">
        {open ? (
          <button
            type="button"
            title={`Show ${label.toLowerCase()}`}
            style={{
              padding: 0,
              border: 0,
              background: 'none',
              color: 'inherit',
              font: 'inherit',
              cursor: 'pointer',
            }}
            onClick={() => open({ label, value, sub })}
          >
            {value}
          </button>
        ) : (
          value
        )}
      </div>
      <div className="seqa-stat__sub">{sub}</div>
    </div>
  );
}

export function Card({
  title,
  actions,
  children,
  className,
}: {
  title: string;
  actions?: ReactNode;
  children: ReactNode;
  className?: string;
}) {
  return (
    <section className={cn('seqa-card', className)}>
      <header className="seqa-card__head">
        <h3 className="seqa-card__title">{title}</h3>
        {actions}
      </header>
      {children}
    </section>
  );
}

// --- Filters (HubSpot: checkbox lists with search, a custom date range) --------------------------

export interface MultiOption {
  value: string;
  label: string;
}
export interface MultiSection {
  title?: string;
  options: MultiOption[];
}

/** Closes `ref`'s popover on an outside click or Esc. */
function useDismiss(open: boolean, onClose: () => void, ref: React.RefObject<HTMLElement | null>) {
  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) onClose();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('mousedown', onDown);
    window.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      window.removeEventListener('keydown', onKey);
    };
    // `onClose` only sets state: the listeners need not change with it.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);
}

const POPOVER_STYLE = { position: 'absolute', top: '100%', left: 0, marginTop: 6 } as const;

/** The ✕ that clears a set filter (HubSpot: "(1) Enrolled by ✕"). */
function ClearButton({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <button
      type="button"
      className="seqa-filter"
      aria-label={`Clear ${label}`}
      title={`Clear ${label}`}
      onClick={onClick}
    >
      <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden>
        <path d="m6 6 12 12M18 6 6 18" fill="none" stroke="currentColor" strokeWidth="2" />
      </svg>
    </button>
  );
}

/**
 * A filter chip "(2) Company ▾": a checkbox list with a search box, and a ✕ that clears it
 * (HubSpot's multi-select filters). Sections give "Teams" / "Users" style groups.
 */
export function MultiFilter({
  label,
  count,
  sections,
  isOn,
  onToggle,
  onClear,
  searchLabel,
  footer,
}: {
  label: string;
  /** How many are picked: the chip shows "(count) label". */
  count: number;
  sections: MultiSection[];
  isOn: (value: string) => boolean;
  onToggle: (value: string) => void;
  onClear: () => void;
  searchLabel: string;
  footer?: ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const [term, setTerm] = useState('');
  const ref = useRef<HTMLSpanElement>(null);
  useDismiss(open, () => setOpen(false), ref);
  const needle = term.trim().toLowerCase();
  const shown = sections
    .map((section) => ({
      ...section,
      options: needle
        ? section.options.filter((o) => o.label.toLowerCase().includes(needle))
        : section.options,
    }))
    .filter((section) => section.options.length > 0);
  return (
    <span ref={ref} style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}>
      <button
        type="button"
        className={cn('seqa-filter', count > 0 && 'is-set')}
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => {
          setTerm('');
          setOpen(!open);
        }}
      >
        {count > 0 ? <strong>({count})</strong> : null}
        {label}
        <ChevronDown size={12} />
      </button>
      {count > 0 ? <ClearButton label={label} onClick={onClear} /> : null}
      {open ? (
        <div className="seqm-menu" role="group" aria-label={label} style={POPOVER_STYLE}>
          <input
            type="search"
            className="input seqm-menu__search"
            placeholder={searchLabel}
            aria-label={searchLabel}
            value={term}
            autoFocus
            onChange={(e) => setTerm(e.target.value)}
          />
          {shown.length === 0 ? (
            <p className="seqm-menu__hint crm-mb-0 crm-p-2">No matches</p>
          ) : null}
          {shown.map((section, i) => (
            <div key={section.title ?? i}>
              {section.title ? (
                <p className="seqm-menu__hint crm-mb-0 crm-p-2">{section.title}</p>
              ) : null}
              {section.options.map((o) => (
                <label key={o.value} className="seqm-menu__item">
                  <input
                    type="checkbox"
                    checked={isOn(o.value)}
                    onChange={() => onToggle(o.value)}
                  />
                  <span style={{ flex: 1 }}>{o.label}</span>
                </label>
              ))}
            </div>
          ))}
          {footer ? (
            <>
              <div className="seqm-menu__divider" role="separator" />
              {footer}
            </>
          ) : null}
        </div>
      ) : null}
    </span>
  );
}

/** A MultiFilter over plain values (Company, Status, Folder). */
export function ValuesFilter({
  label,
  options,
  selected,
  onChange,
  searchLabel = 'Search',
}: {
  label: string;
  options: MultiOption[];
  selected: string[];
  onChange: (next: string[]) => void;
  searchLabel?: string;
}) {
  return (
    <MultiFilter
      label={label}
      count={selected.length}
      sections={[{ options }]}
      isOn={(value) => selected.includes(value)}
      onToggle={(value) =>
        onChange(
          selected.includes(value) ? selected.filter((v) => v !== value) : [...selected, value],
        )
      }
      onClear={() => onChange([])}
      searchLabel={searchLabel}
    />
  );
}

/**
 * "Enrolled by": Teams (a team picks all of its members) and Users, with search and a link to
 * where they are managed (HubSpot: "Search users and teams", "Manage users & teams").
 */
export function EnrolledByFilter({
  selected,
  onChange,
  extraUsers = [],
}: {
  selected: string[];
  onChange: (next: string[]) => void;
  /** People seen in the data who are not in the owners list. */
  extraUsers?: MultiOption[];
}) {
  const { owners } = useOwners(true);
  const [teams, setTeams] = useState<TeamOption[]>([]);
  useEffect(() => {
    let alive = true;
    listTeamOptions().then(
      (r) => alive && setTeams(r.data),
      () => undefined,
    );
    return () => {
      alive = false;
    };
  }, []);
  const users = useMemo(() => {
    const byId = new Map(owners.map((o) => [o.userId, ownerDisplayName(o)]));
    for (const u of extraUsers) if (!byId.has(u.value)) byId.set(u.value, u.label);
    return [...byId]
      .map(([value, label]) => ({ value, label }))
      .sort((a, b) => a.label.localeCompare(b.label));
  }, [owners, extraUsers]);
  const teamOptions = teams
    .filter((t) => t.memberIds.length > 0)
    .map((t) => ({ value: `team:${t.id}`, label: t.name }));
  const members = (value: string) => teams.find((t) => `team:${t.id}` === value)?.memberIds ?? [];
  return (
    <MultiFilter
      label="Enrolled by"
      count={selected.length}
      searchLabel="Search users and teams"
      sections={[
        ...(teamOptions.length ? [{ title: 'Teams', options: teamOptions }] : []),
        { title: 'Users', options: users },
      ]}
      isOn={(value) =>
        value.startsWith('team:')
          ? members(value).length > 0 && members(value).every((id) => selected.includes(id))
          : selected.includes(value)
      }
      onToggle={(value) => {
        if (!value.startsWith('team:')) {
          onChange(
            selected.includes(value) ? selected.filter((v) => v !== value) : [...selected, value],
          );
          return;
        }
        const ids = members(value);
        onChange(
          ids.every((id) => selected.includes(id))
            ? selected.filter((v) => !ids.includes(v))
            : [...new Set([...selected, ...ids])],
        );
      }}
      onClear={() => onChange([])}
      footer={
        <Link className="seqm-menu__item" href="/settings/users">
          Manage users &amp; teams
        </Link>
      }
    />
  );
}

/** Enrollment date: both days, as ISO dates. */
export interface DateRange {
  from: string;
  to: string;
}

export const usDate = (iso: string) => `${iso.slice(5, 7)}/${iso.slice(8, 10)}/${iso.slice(0, 4)}`;

/** "MM/DD/YYYY" to an ISO date; null when it is not a real day. */
function parseUsDate(text: string): string | null {
  const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(text.trim());
  if (!m) return null;
  const [, month, day, year] = m;
  const d = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));
  return d.getUTCFullYear() === Number(year) &&
    d.getUTCMonth() === Number(month) - 1 &&
    d.getUTCDate() === Number(day)
    ? `${year}-${month}-${day}`
    : null;
}

/** Enrollment date as a custom range "MM/DD/YYYY to MM/DD/YYYY", empty by default. */
export function DateRangeFilter({
  value,
  onChange,
  label = 'Enrollment date',
}: {
  value: DateRange | null;
  onChange: (next: DateRange | null) => void;
  label?: string;
}) {
  const [open, setOpen] = useState(false);
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  const ref = useRef<HTMLSpanElement>(null);
  useDismiss(open, () => setOpen(false), ref);
  const fromIso = parseUsDate(from);
  const toIso = parseUsDate(to);
  const problem =
    from && !fromIso
      ? 'Start date: use MM/DD/YYYY.'
      : to && !toIso
        ? 'End date: use MM/DD/YYYY.'
        : fromIso && toIso && fromIso > toIso
          ? 'The start date must be on or before the end date.'
          : null;
  const apply = () => {
    if (!fromIso || !toIso || problem) return;
    onChange({ from: fromIso, to: toIso });
    setOpen(false);
  };
  return (
    <span ref={ref} style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}>
      <button
        type="button"
        className={cn('seqa-filter', value && 'is-set')}
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => {
          setFrom(value ? usDate(value.from) : '');
          setTo(value ? usDate(value.to) : '');
          setOpen(!open);
        }}
      >
        {label}
        {value ? (
          <>
            : <strong>{`${usDate(value.from)} to ${usDate(value.to)}`}</strong>
          </>
        ) : null}
        <ChevronDown size={12} />
      </button>
      {value ? <ClearButton label={label} onClick={() => onChange(null)} /> : null}
      {open ? (
        <form
          className="seqm-menu"
          aria-label={label}
          style={{ ...POPOVER_STYLE, display: 'grid', gap: 8, padding: 12 }}
          onSubmit={(e) => {
            e.preventDefault();
            apply();
          }}
        >
          <label className="field__label" style={{ display: 'grid', gap: 4 }}>
            Start date
            <input
              className="input"
              inputMode="numeric"
              placeholder="MM/DD/YYYY"
              value={from}
              autoFocus
              onChange={(e) => setFrom(e.target.value)}
            />
          </label>
          <label className="field__label" style={{ display: 'grid', gap: 4 }}>
            End date
            <input
              className="input"
              inputMode="numeric"
              placeholder="MM/DD/YYYY"
              value={to}
              onChange={(e) => setTo(e.target.value)}
            />
          </label>
          {problem ? (
            <p className="crm-fs-8 crm-text-danger crm-mb-0" role="alert">
              {problem}
            </p>
          ) : null}
          <button
            type="submit"
            className="btn-crm btn-crm--primary btn-crm--sm"
            disabled={!fromIso || !toIso || problem !== null}
          >
            Apply
          </button>
        </form>
      ) : null}
    </span>
  );
}

/** HubSpot's revenue format: "$0.00" (the US style, in the business currency). */
export function revenueText(amount: number, currency: string): string {
  try {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      currencyDisplay: 'narrowSymbol',
    }).format(amount);
  } catch {
    return `${currency} ${amount.toFixed(2)}`;
  }
}

/** An empty table (HubSpot: no enrollments match the filters). */
function EmptyRow({ cols }: { cols: number }) {
  return (
    <tr>
      <td colSpan={cols} className="seqm-empty">
        No enrollments match the current filters.
        <br />
        <span className="crm-text-muted">
          Try changing your filters or enrolling contacts to see results.
        </span>
      </td>
    </tr>
  );
}

// --- Sorting and paging ------------------------------------------------------------------------

type SortDir = 'asc' | 'desc';
export type Sort<K extends string> = { key: K; dir: SortDir };

export function sorted<T, K extends string>(
  rows: T[],
  sort: Sort<K>,
  value: (row: T, key: K) => string | number | null,
): T[] {
  const sign = sort.dir === 'asc' ? 1 : -1;
  return [...rows].sort((a, b) => {
    const x = value(a, sort.key);
    const y = value(b, sort.key);
    if (x === y) return 0;
    if (x === null) return 1;
    if (y === null) return -1;
    return (
      (typeof x === 'string' && typeof y === 'string' ? x.localeCompare(y) : x < y ? -1 : 1) * sign
    );
  });
}

export function SortTh<K extends string>({
  k,
  label,
  sort,
  onSort,
  num,
}: {
  k: K;
  label: string;
  sort: Sort<K>;
  onSort: (next: Sort<K>) => void;
  num?: boolean;
}) {
  const dir = sort.key === k ? sort.dir : null;
  return (
    <th
      scope="col"
      className={num ? 'seqm-num' : undefined}
      aria-sort={dir === 'asc' ? 'ascending' : dir === 'desc' ? 'descending' : 'none'}
    >
      <button
        type="button"
        className={cn('seqm-sort', dir && 'is-sorted')}
        onClick={() =>
          onSort({
            key: k,
            dir: dir === 'desc' ? 'asc' : dir === 'asc' ? 'desc' : num ? 'desc' : 'asc',
          })
        }
      >
        <span>{label}</span>
        <svg className="seqm-sort__icon" viewBox="0 0 24 24" width="13" height="13" aria-hidden>
          {dir === 'asc' ? (
            <path d="M12 19V5m-6 6 6-6 6 6" fill="none" stroke="currentColor" strokeWidth="2" />
          ) : dir === 'desc' ? (
            <path d="M12 5v14m-6-6 6 6 6-6" fill="none" stroke="currentColor" strokeWidth="2" />
          ) : (
            <path
              d="M8 18V6M4 10l4-4 4 4M16 6v12m-4-4 4 4 4-4"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
            />
          )}
        </svg>
      </button>
    </th>
  );
}

/** ‹ Prev 1 2 … 19 20 Next › (design: table footers). */
export function Pager({
  page,
  pages,
  onChange,
}: {
  page: number;
  pages: number;
  onChange: (page: number) => void;
}) {
  if (pages <= 1) return null;
  const shown = [...new Set([1, 2, page - 1, page, page + 1, pages - 1, pages])]
    .filter((p) => p >= 1 && p <= pages)
    .sort((a, b) => a - b);
  return (
    <nav className="seqa-pager" aria-label="Pages">
      <button type="button" disabled={page <= 1} onClick={() => onChange(page - 1)}>
        ‹ Prev
      </button>
      {shown.map((p, i) => (
        <span key={p} className="seqa-pager__group">
          {i > 0 && p - shown[i - 1]! > 1 ? <span aria-hidden>…</span> : null}
          <button
            type="button"
            className={cn(p === page && 'is-current')}
            aria-current={p === page ? 'page' : undefined}
            onClick={() => onChange(p)}
          >
            {p}
          </button>
        </span>
      ))}
      <button type="button" disabled={page >= pages} onClick={() => onChange(page + 1)}>
        Next ›
      </button>
    </nav>
  );
}

function usePaged<T>(rows: T[], resetKey: string) {
  const [state, setState] = useState({ page: 1, key: resetKey });
  const page = state.key === resetKey ? state.page : 1;
  const pages = Math.max(1, Math.ceil(rows.length / PAGE_SIZE));
  const current = Math.min(page, pages);
  return {
    page: current,
    pages,
    rows: rows.slice((current - 1) * PAGE_SIZE, current * PAGE_SIZE),
    setPage: (p: number) => setState({ page: p, key: resetKey }),
  };
}

// --- Series ------------------------------------------------------------------------------------

function bucketOf(day: string, frequency: Frequency): string {
  if (frequency === 'weekly') return mondayOf(day);
  if (frequency === 'monthly') return `${day.slice(0, 7)}-01`;
  if (frequency === 'quarterly') {
    const month = Math.floor((Number(day.slice(5, 7)) - 1) / 3) * 3 + 1;
    return `${day.slice(0, 4)}-${String(month).padStart(2, '0')}-01`;
  }
  if (frequency === 'yearly') return `${day.slice(0, 4)}-01-01`;
  return day;
}

/** "Q4 2026" for the quarter that starts on `key` (YYYY-MM-01). */
function quarterLabel(key: string): string {
  return `Q${Math.floor((Number(key.slice(5, 7)) - 1) / 3) + 1} ${key.slice(0, 4)}`;
}

function seriesOf(data: SequenceAnalytics, metric: MetricKey, frequency: Frequency): LinePoint[] {
  const values = new Map<string, number>();
  for (let day = data.from; day <= data.to; day = addDays(day, 1)) {
    const key = bucketOf(day, frequency);
    if (!values.has(key)) values.set(key, 0);
  }
  for (const d of data.days) {
    const key = bucketOf(d.day, frequency);
    values.set(key, (values.get(key) ?? 0) + d[metric]);
  }
  const keys = [...values.keys()].sort();
  return keys.map((key, i) => {
    const first = i === 0 || key.slice(0, 4) !== keys[i - 1]!.slice(0, 4);
    const label =
      frequency === 'yearly'
        ? key.slice(0, 4)
        : frequency === 'quarterly'
          ? quarterLabel(key)
          : frequency === 'monthly'
            ? new Date(`${key}T00:00:00`).toLocaleDateString(undefined, {
                month: 'short',
                ...(first ? { year: 'numeric' } : {}),
              })
            : shortDate(key, first);
    const title =
      frequency === 'yearly'
        ? key.slice(0, 4)
        : frequency === 'quarterly'
          ? quarterLabel(key)
          : frequency === 'weekly'
            ? `Week of ${shortDate(key)}`
            : frequency === 'monthly'
              ? new Date(`${key}T00:00:00`).toLocaleDateString(undefined, {
                  month: 'long',
                  year: 'numeric',
                })
              : shortDate(key);
    return { label, title, value: values.get(key) ?? 0 };
  });
}

// --- View --------------------------------------------------------------------------------------

export function SequencesAnalyzeTab({
  sequences,
  folders,
}: {
  sequences: Array<{ id: string; name: string }>;
  folders: string[];
}) {
  const me = useCurrentUser();
  const canSeeEveryone = Boolean(me.permissionSet.rules.app.manage_sequences);

  /** Picked companies' names: they stay options when another filter leaves them out. */
  const [companies, setCompanies] = useState<Map<string, string>>(new Map());
  const [companyIds, setCompanyIds] = useState<string[]>([]);
  const [sequenceId, setSequenceId] = useState('');
  const [statuses, setStatuses] = useState<string[]>([]);
  const [folderNames, setFolderNames] = useState<string[]>([]);
  // HubSpot starts on your own enrollments, with no date range.
  const [enrolledBy, setEnrolledBy] = useState<string[]>(canSeeEveryone ? [me.user.id] : []);
  const [range, setRange] = useState<DateRange | null>(null);
  const [seqMode, setSeqMode] = useState<'rates' | 'counts'>('counts');

  const query: SequenceAnalyticsQuery = {
    ...(range && range),
    ...(companyIds.length > 0 && { companyId: companyIds.join(',') }),
    ...(sequenceId && { sequenceId }),
    ...(statuses.length > 0 && { status: statuses.join(',') }),
    ...(folderNames.length > 0 && { folder: folderNames.join(',') }),
    ...(enrolledBy.length > 0 && { enrolledBy: enrolledBy.join(',') }),
  };
  const key = JSON.stringify(query);
  const state = useReport(key, (signal) => getSequenceAnalytics(query, signal));
  const data = state.data;
  useEffect(() => {
    const options = data?.companyOptions;
    if (!options?.length) return;
    setCompanies((current) => {
      const next = new Map(current);
      for (const c of options) next.set(c.id, c.name);
      return next.size === current.size ? current : next;
    });
  }, [data?.companyOptions]);

  const filterMenu = (
    label: string,
    current: string,
    options: Array<{ value: string; label: string }>,
    onPick: (value: string) => void,
    anyLabel = 'All',
  ) => {
    const picked = options.find((o) => o.value === current);
    const items: DropMenuItem[] = [
      { key: '', label: anyLabel, active: !current, onSelect: () => onPick('') },
      ...options.map((o) => ({
        key: o.value,
        label: o.label,
        active: o.value === current,
        onSelect: () => onPick(o.value),
      })),
    ];
    return (
      <DropMenu
        trigger={
          <>
            {label}
            {picked ? (
              <>
                : <strong>{picked.label}</strong>
              </>
            ) : null}
            <ChevronDown size={12} />
          </>
        }
        triggerClassName={cn('seqa-filter', picked && 'is-set')}
        align="start"
        items={items}
      />
    );
  };

  const companyLabel = (id: string) => companies.get(id) ?? 'Selected company';
  // What the stat drill-down names as the filters in force (HubSpot: "Filters (2)").
  const filterNotes = [
    ...(companyIds.length ? [`Company: ${companyIds.map(companyLabel).join(', ')}`] : []),
    ...(sequenceId
      ? [`Sequence: ${sequences.find((s) => s.id === sequenceId)?.name ?? 'Selected sequence'}`]
      : []),
    ...(statuses.length
      ? [`Status: ${statuses.map((v) => STATUS_LABELS[v as SequenceAnalyticsStatus]).join(', ')}`]
      : []),
    ...(folderNames.length ? [`Folder: ${folderNames.join(', ')}`] : []),
    ...(enrolledBy.length ? [`Enrolled by: ${enrolledBy.length} selected`] : []),
    ...(range ? [`Enrollment date: ${usDate(range.from)} to ${usDate(range.to)}`] : []),
  ];

  return (
    <div className="seqa">
      <div className="seqa-filters">
        <ValuesFilter
          label="Company"
          selected={companyIds}
          onChange={setCompanyIds}
          options={[
            ...companyIds
              .filter((id) => !data?.companyOptions?.some((c) => c.id === id))
              .map((id) => ({ value: id, label: companyLabel(id) })),
            ...(data?.companyOptions ?? []).map((c) => ({ value: c.id, label: c.name })),
          ]}
          searchLabel="Search companies"
        />
        {filterMenu(
          'Sequence',
          sequenceId,
          sequences.map((s) => ({ value: s.id, label: s.name })),
          setSequenceId,
          'All sequences',
        )}
        <ValuesFilter
          label="Status"
          selected={statuses}
          onChange={setStatuses}
          options={(Object.keys(STATUS_LABELS) as SequenceAnalyticsStatus[]).map((s) => ({
            value: s,
            label: STATUS_LABELS[s],
          }))}
        />
        <ValuesFilter
          label="Folder"
          selected={folderNames}
          onChange={setFolderNames}
          options={folders.map((f) => ({ value: f, label: f }))}
          searchLabel="Search folders"
        />
        {canSeeEveryone ? (
          <EnrolledByFilter selected={enrolledBy} onChange={setEnrolledBy} />
        ) : null}
        <DateRangeFilter value={range} onChange={setRange} />
      </div>

      {state.forbidden ? (
        <p className="seqm-empty">You do not have permission to see sequence analytics.</p>
      ) : state.error ? (
        <p className="seqm-empty crm-text-danger" role="alert">
          {state.error}{' '}
          <button
            type="button"
            className="btn-crm btn-crm--ghost btn-crm--sm"
            onClick={state.reload}
          >
            Try again
          </button>
        </p>
      ) : !data ? (
        <p className="seqm-empty">Loading analytics…</p>
      ) : (
        <StatDrill filters={filterNotes}>
          <div className={cn('seqa-body', state.loading && 'is-loading')} aria-busy={state.loading}>
            {data.capped ? (
              <p className="seqa-note" role="status">
                Only the newest 20,000 enrollments are counted. Narrow the filters for exact
                numbers.
              </p>
            ) : null}
            <Insights data={data} currency={me.business.currency} />
            <div className="seqa-grid-2">
              <EmailEngagement data={data} />
              <CompanyInsights data={data} />
            </div>
            <PerformanceOverTime data={data} />
            <div className="seqa-grid-2">
              <Card title="Meetings booked by step type">
                <ValueColumnChart
                  ariaLabel="Meetings booked by step type"
                  xTitle="Step type"
                  rows={STEP_TYPES.map((t) => ({
                    key: t.key,
                    label: t.short,
                    value: data.meetingsByStepType[t.key],
                    hint: [
                      `Meetings booked: ${data.meetingsByStepType[t.key]}`,
                      `${data.enrollmentsByStepType[t.key]} step enrollments in view`,
                    ],
                  }))}
                />
              </Card>
              <Card title="Meetings booked by number of touches">
                {data.meetingsByTouches.length === 0 ? (
                  <p className="seqm-empty">No meetings booked by these enrollments.</p>
                ) : (
                  <StackedBarChart
                    ariaLabel="Meetings booked by number of steps completed"
                    xTitle="Number of meetings booked"
                    yTitle="Steps completed"
                    legend={STEP_TYPES.map((t) => ({
                      key: t.key,
                      label: t.long,
                      color: STEP_TYPE_COLORS[t.key],
                    }))}
                    rows={data.meetingsByTouches.map((row) => ({
                      key: String(row.steps),
                      label: String(row.steps),
                      segments: STEP_TYPES.map((t) => ({
                        key: t.key,
                        label: t.long,
                        color: STEP_TYPE_COLORS[t.key],
                        value: row.byType[t.key],
                      })),
                    }))}
                  />
                )}
              </Card>
            </div>
            <SequencePerformance data={data} mode={seqMode} onMode={setSeqMode} />
            <TemplatePerformance data={data} />
            <EngagedContacts data={data} />
          </div>
        </StatDrill>
      )}
    </div>
  );
}

export function Insights({ data, currency }: { data: SequenceAnalytics; currency: string }) {
  const i = data.insights;
  const revenue = data.insights.revenue;
  const main = revenue.find((r) => r.currency === currency) ?? revenue[0];
  const others = revenue.filter((r) => r !== main);
  return (
    <Card title="Insights">
      <div className="seqa-stats seqa-stats--6">
        <Stat
          label="Total enrollments"
          value={i.enrollments.toLocaleString()}
          sub={`${i.contacts.toLocaleString()} Contacts`}
        />
        <Stat
          label="Meeting rate"
          hint="Enrollments that ended because the contact booked a meeting, of all enrollments."
          value={pct(i.meetings, i.enrollments)}
          sub={`${i.meetings.toLocaleString()} Meetings Booked`}
        />
        <Stat
          label="Reply rate"
          hint="Enrollments with a reply to one of their emails, of all enrollments."
          value={pct(i.replies, i.enrollments)}
          sub={`${i.replies.toLocaleString()} Replies`}
        />
        <Stat
          label="Deal rate"
          hint="Deals linked to an enrolled contact and created after the enrollment, per enrollment."
          value={pct(i.dealsCreated, i.enrollments)}
          sub={`${i.dealsCreated.toLocaleString()} Deals Created`}
        />
        <Stat
          label="Total revenue"
          hint={
            others.length
              ? `Won deals created after the enrollment. Also: ${others
                  .map((r) => revenueText(r.amount, r.currency))
                  .join(', ')}.`
              : 'Amounts of the won deals created after the enrollment.'
          }
          value={revenueText(main?.amount ?? 0, main?.currency ?? currency)}
          sub={`${i.dealsClosed.toLocaleString()} Deals Closed`}
        />
        <Stat
          label="No response"
          hint="Enrollments with no reply and no meeting booked."
          value={pct(i.noResponse, i.enrollments)}
          sub={`${i.noResponse.toLocaleString()} No Response`}
        />
      </div>
    </Card>
  );
}

export function EmailEngagement({ data }: { data: SequenceAnalytics }) {
  const e = data.email;
  const hint = (what: string) =>
    `Enrollments that ${what}, of the ${e.emailed.toLocaleString()} enrollments sent an email.`;
  return (
    <Card title="Email engagement">
      <div className="seqa-stats seqa-stats--4">
        <Stat
          label="Open rate"
          hint={hint('opened an email (machine opens left out)')}
          value={pct(e.opened, e.emailed)}
          sub={`${e.opened.toLocaleString()} Opens`}
        />
        <Stat
          label="Click rate"
          hint={hint('clicked a link')}
          value={pct(e.clicked, e.emailed)}
          sub={`${e.clicked.toLocaleString()} Clicks`}
        />
        <Stat
          label="Bounce rate"
          hint={hint('hard-bounced')}
          value={pct(e.bounced, e.emailed)}
          sub={`${e.bounced.toLocaleString()} Bounced`}
        />
        <Stat
          label="Unsubscribe rate"
          hint={hint('unsubscribed')}
          value={pct(e.unsubscribed, e.emailed)}
          sub={`${e.unsubscribed.toLocaleString()} Unsubscribes`}
        />
      </div>
    </Card>
  );
}

export function CompanyInsights({ data }: { data: SequenceAnalytics }) {
  const c = data.companies;
  // Contacts with a company per company, not enrollments (QA 16 Oct #112).
  const avg = c.enrolled ? Number(((c.contacts ?? 0) / c.enrolled).toFixed(1)) : 0;
  return (
    <Card title="Company insights">
      <div className="seqa-stats seqa-stats--3">
        <Stat
          label="Companies enrolled"
          hint="Distinct primary companies of the enrolled contacts."
          value={c.enrolled.toLocaleString()}
          sub={`Avg ${avg} Contacts per Company`}
        />
        <Stat
          label="Engaged rate"
          hint="Companies with an enrollment that opened, clicked or replied."
          value={pct(c.engaged, c.enrolled)}
          sub={`${c.engaged.toLocaleString()} Companies Engaged`}
        />
        <Stat
          label="Meeting rate"
          hint="Companies with a meeting booked."
          value={pct(c.booked, c.enrolled)}
          sub={`${c.booked.toLocaleString()} Companies Booked`}
        />
      </div>
    </Card>
  );
}

type SeqKey =
  'name' | 'createdAt' | 'enrolled' | 'opened' | 'clicked' | 'replied' | 'meetings' | 'bounced';

function SequencePerformance({
  data,
  mode,
  onMode,
}: {
  data: SequenceAnalytics;
  mode: 'rates' | 'counts';
  onMode: (mode: 'rates' | 'counts') => void;
}) {
  const [sort, setSort] = useState<Sort<SeqKey>>({ key: 'enrolled', dir: 'desc' });
  const rows = useMemo(
    () =>
      sorted(data.sequences, sort, (row, k) => {
        if (k === 'name' || k === 'createdAt') return row[k];
        if (mode === 'counts' || k === 'enrolled') return row[k];
        const base = k === 'replied' || k === 'meetings' ? row.enrolled : row.emailed;
        return base ? row[k] / base : 0;
      }),
    [data.sequences, sort, mode],
  );
  const cell = (part: number, base: number) =>
    mode === 'counts' ? part.toLocaleString() : pct(part, base);
  const th = (k: SeqKey, label: string, num = true) => (
    <SortTh k={k} label={label} sort={sort} onSort={setSort} num={num} />
  );
  return (
    <Card
      title="Sequence performance"
      actions={
        <div className="seqa-toggle" role="group" aria-label="Show">
          {(['rates', 'counts'] as const).map((m) => (
            <button
              key={m}
              type="button"
              className={cn(mode === m && 'is-active')}
              aria-pressed={mode === m}
              onClick={() => onMode(m)}
            >
              {m === 'rates' ? 'Rates' : 'Counts'}
            </button>
          ))}
        </div>
      }
    >
      <div className="seqa-table-wrap">
        <table className="seqm-table seqa-table">
          <thead>
            <tr>
              {th('name', 'Sequence', false)}
              {th('createdAt', 'Created', false)}
              {th('enrolled', 'Enrolled')}
              {th('opened', 'Opens')}
              {th('clicked', 'Clicks')}
              {th('replied', 'Replies')}
              {th('meetings', 'Meetings')}
              {th('bounced', 'Bounces')}
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <EmptyRow cols={8} />
            ) : (
              rows.map((row) => (
                <tr key={row.sequenceId}>
                  <td>
                    <Link className="seqm-name" href={`/sequences/${row.sequenceId}`}>
                      {row.name || 'Untitled sequence'}
                    </Link>
                  </td>
                  <td>
                    {shortDate(row.createdAt)}
                    {row.ownerName ? <div className="seqm-meta">by {row.ownerName}</div> : null}
                  </td>
                  <td className="seqm-num">{row.enrolled.toLocaleString()}</td>
                  <td className="seqm-num">{cell(row.opened, row.emailed)}</td>
                  <td className="seqm-num">{cell(row.clicked, row.emailed)}</td>
                  <td className="seqm-num">{cell(row.replied, row.enrolled)}</td>
                  <td className="seqm-num">{cell(row.meetings, row.enrolled)}</td>
                  <td className="seqm-num">{cell(row.bounced, row.emailed)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

type TplKey = 'name' | 'createdAt' | 'updatedAt' | 'sends' | 'opened' | 'clicked' | 'replied';

function TemplatePerformance({ data }: { data: SequenceAnalytics }) {
  const [sort, setSort] = useState<Sort<TplKey>>({ key: 'sends', dir: 'desc' });
  const rows = useMemo(
    () =>
      sorted(data.templates, sort, (row, k) =>
        k === 'name' || k === 'createdAt' || k === 'updatedAt' || k === 'sends'
          ? row[k]
          : row.sends
            ? row[k] / row.sends
            : 0,
      ),
    [data.templates, sort],
  );
  const paged = usePaged(rows, JSON.stringify([sort, data.from, data.to, data.templates.length]));
  const th = (k: TplKey, label: string, num = true) => (
    <SortTh k={k} label={label} sort={sort} onSort={setSort} num={num} />
  );
  return (
    <Card title="Template performance">
      <div className="seqa-table-wrap">
        <table className="seqm-table seqa-table">
          <thead>
            <tr>
              {th('name', 'Template', false)}
              {th('createdAt', 'Created', false)}
              {th('updatedAt', 'Last updated', false)}
              {th('sends', 'Sends')}
              {th('opened', 'Open rate')}
              {th('clicked', 'Click rate')}
              {th('replied', 'Reply rate')}
            </tr>
          </thead>
          <tbody>
            {paged.rows.length === 0 ? (
              <EmptyRow cols={7} />
            ) : (
              paged.rows.map((row) => (
                <tr key={row.key}>
                  <td>
                    <strong>{row.name}</strong>
                    <div className="seqm-meta">{row.sequenceName}</div>
                  </td>
                  <td>
                    {shortDate(row.createdAt)}
                    {row.createdByName ? (
                      <div className="seqm-meta">by {row.createdByName}</div>
                    ) : null}
                  </td>
                  <td title={new Date(row.updatedAt).toLocaleString()}>{timeAgo(row.updatedAt)}</td>
                  <td className="seqm-num">{row.sends.toLocaleString()}</td>
                  <td className="seqm-num">{pct(row.opened, row.sends, 0)}</td>
                  <td className="seqm-num">{pct(row.clicked, row.sends, 0)}</td>
                  <td className="seqm-num">{pct(row.replied, row.sends, 0)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
      <Pager page={paged.page} pages={paged.pages} onChange={paged.setPage} />
    </Card>
  );
}

type ContactKey =
  | 'name'
  | 'companyName'
  | 'sequenceName'
  | 'status'
  | 'lastStepAt'
  | 'nextStepAt'
  | 'sent'
  | 'opens'
  | 'clicks';

function EngagedContacts({ data }: { data: SequenceAnalytics }) {
  const [sort, setSort] = useState<Sort<ContactKey>>({ key: 'opens', dir: 'desc' });
  const rows = useMemo(
    () =>
      sorted(data.contacts, sort, (row, k) =>
        k === 'status' ? STATUS_LABELS[row.status] : row[k],
      ),
    [data.contacts, sort],
  );
  const paged = usePaged(rows, JSON.stringify([sort, data.from, data.to, data.contacts.length]));
  const th = (k: ContactKey, label: string, num = false) => (
    <SortTh k={k} label={label} sort={sort} onSort={setSort} num={num} />
  );
  return (
    <Card title="Highly engaged contacts">
      <div className="seqa-table-wrap">
        <table className="seqm-table seqa-table">
          <thead>
            <tr>
              {th('name', 'Contact enrolled')}
              {th('companyName', 'Company')}
              {th('sequenceName', 'Sequence')}
              {th('status', 'Status')}
              {th('lastStepAt', 'Last step date')}
              {th('nextStepAt', 'Next step date')}
              {th('sent', 'Emails sent', true)}
              {th('opens', 'Email opens', true)}
              {th('clicks', 'Email clicks', true)}
            </tr>
          </thead>
          <tbody>
            {paged.rows.length === 0 ? (
              <EmptyRow cols={9} />
            ) : (
              paged.rows.map((row) => (
                <tr key={row.enrollmentId}>
                  <td>
                    <Link className="seqa-contact" href={`/contacts/${row.contactId}`}>
                      {row.name}
                    </Link>
                    {row.email ? <div className="seqm-meta">{row.email}</div> : null}
                  </td>
                  <td>{row.companyName ?? '-'}</td>
                  <td>
                    <Link className="seqm-name" href={`/sequences/${row.sequenceId}`}>
                      {row.sequenceName}
                    </Link>
                  </td>
                  <td>
                    <span className={`seqa-status seqa-status--${row.status}`}>
                      {STATUS_LABELS[row.status]}
                    </span>
                  </td>
                  <td>{row.lastStepAt ? shortDate(row.lastStepAt) : '-'}</td>
                  <td>{row.nextStepAt ? shortDate(row.nextStepAt) : '-'}</td>
                  <td className="seqm-num">{row.sent || '-'}</td>
                  <td className="seqm-num">{row.opens || '-'}</td>
                  <td className="seqm-num">{row.clicks || '-'}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
      <Pager page={paged.page} pages={paged.pages} onChange={paged.setPage} />
    </Card>
  );
}

/** "Performance over time": one metric by day, week or month of enrollment (Analyze, Performance). */
export function PerformanceOverTime({
  data,
  basicMetrics = false,
}: {
  data: SequenceAnalytics;
  /** Only Booked meetings and Enrollments (HubSpot's Performance tab). */
  basicMetrics?: boolean;
}) {
  const metrics = basicMetrics ? METRICS.slice(0, 2) : METRICS;
  const [metric, setMetric] = useState<MetricKey>('meetings');
  const [frequency, setFrequency] = useState<Frequency>('weekly');
  const points = seriesOf(data, metric, frequency);
  return (
    <Card title="Performance over time" actions={null}>
      <div className="seqa-chart-controls">
        <DropMenu
          trigger={
            <>
              <strong>{METRICS.find((m) => m.key === metric)!.label}</strong>
              <ChevronDown size={12} />
            </>
          }
          triggerClassName="seqa-filter"
          align="start"
          items={metrics.map((m) => ({
            key: m.key,
            label: m.label,
            active: m.key === metric,
            onSelect: () => setMetric(m.key),
          }))}
        />
        <DropMenu
          trigger={
            <>
              Frequency: <strong>{FREQUENCIES.find((f) => f.key === frequency)!.label}</strong>
              <ChevronDown size={12} />
            </>
          }
          triggerClassName="seqa-filter"
          align="start"
          items={FREQUENCIES.map((f) => ({
            key: f.key,
            label: f.label,
            active: f.key === frequency,
            onSelect: () => setFrequency(f.key),
          }))}
        />
      </div>
      {points.some((p) => p.value > 0) ? (
        <TimeLineChart
          points={points}
          seriesLabel={METRICS.find((m) => m.key === metric)!.label}
          xTitle="Enrollment date"
        />
      ) : (
        <p className="seqm-empty">
          There is no data to show in this time frame. Try changing the date range.
        </p>
      )}
    </Card>
  );
}
