"use client";

import type * as React from "react";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import "./SupportOverview.css";

export type SupportDay = { date: string; human: number; ai: number };
export type SupportMetrics = {
  conversations: number;
  firstResponseSeconds: number;
  aiResolvedPercent: number;
  satisfactionPercent: number;
  /** [AI resolved, human resolved, escalated], each expressed as a percentage */
  resolutionMix: [number, number, number];
};
export type SupportChannel = {
  id: string;
  name: string;
  data: SupportDay[];
  metrics: SupportMetrics;
};
export type SupportOverviewProps = {
  channels?: SupportChannel[];
  title?: string;
  className?: string;
  /** Called only when a day is selected by the user, not during auto-play. */
  onDaySelect?: (day: SupportDay, channel: SupportChannel) => void;
};

type Series = "human" | "ai";
const PURPLE = "var(--brand)";
const CORAL = "#ff928a";
const PALE = "#eae7ff";
const COLORS = [PURPLE, CORAL, PALE];
const SEGMENTS = ["AI resolved", "Human resolved", "Escalated"];
const CHART = { width: 800, height: 228, x0: 40, x1: 773, y0: 18, y1: 171 };
const nf = new Intl.NumberFormat("en-US");
const HUMAN = [
  70, 59, 18, 74, 34, 67, 46, 96, 89, 61, 92, 84, 30, 76, 11, 78, 11, 96, 82,
  47, 86, 79, 51, 48, 74, 26, 96, 84, 46, 40,
];
const AI = [
  46, 23, 52, 71, 38, 20, 95, 35, 77, 95, 58, 48, 68, 54, 60, 34, 22, 55, 96,
  26, 95, 14, 82, 70, 68, 75, 90, 70, 87, 36,
];
const SAMPLE_DATA: SupportDay[] = HUMAN.map((human, i) => ({
  date: `2026-06-${String(i + 1).padStart(2, "0")}`,
  human,
  ai: AI[i],
}));
const SAMPLE_METRICS: SupportMetrics = {
  conversations: 2456,
  firstResponseSeconds: 38,
  aiResolvedPercent: 74,
  satisfactionPercent: 96,
  resolutionMix: [65, 28, 7],
};

/** Demo-only values; pass `channels` with your backend data in production. */
export const sampleSupportChannels: SupportChannel[] = [
  {
    id: "all",
    name: "All channels",
    data: SAMPLE_DATA,
    metrics: SAMPLE_METRICS,
  },
  {
    id: "website",
    name: "Website",
    data: SAMPLE_DATA.map((d) => ({
      ...d,
      human: Math.round(d.human * 0.52),
      ai: Math.round(d.ai * 0.54),
    })),
    metrics: {
      conversations: 1200,
      firstResponseSeconds: 35,
      aiResolvedPercent: 77,
      satisfactionPercent: 97,
      resolutionMix: [70, 24, 6],
    },
  },
  {
    id: "messenger",
    name: "Messenger",
    data: SAMPLE_DATA.map((d) => ({
      ...d,
      human: Math.round(d.human * 0.32),
      ai: Math.round(d.ai * 0.31),
    })),
    metrics: {
      conversations: 800,
      firstResponseSeconds: 42,
      aiResolvedPercent: 70,
      satisfactionPercent: 95,
      resolutionMix: [60, 33, 7],
    },
  },
  {
    id: "whatsapp",
    name: "WhatsApp",
    data: SAMPLE_DATA.map((d) => ({
      ...d,
      human: Math.round(d.human * 0.16),
      ai: Math.round(d.ai * 0.15),
    })),
    metrics: {
      conversations: 456,
      firstResponseSeconds: 39,
      aiResolvedPercent: 72,
      satisfactionPercent: 96,
      resolutionMix: [61, 30, 9],
    },
  },
];

function dateInfo(value: string) {
  const d = new Date(`${value}T12:00:00`);
  if (Number.isNaN(d.getTime())) return { short: value, full: value };
  return {
    short: d.toLocaleString("en-US", { month: "short", day: "numeric" }),
    full: d.toLocaleString("en-US", {
      month: "long",
      day: "numeric",
      year: "numeric",
    }),
  };
}
const xAt = (i: number, total: number) =>
  CHART.x0 + (total < 2 ? 0.5 : i / (total - 1)) * (CHART.x1 - CHART.x0);
const yAt = (v: number, max: number) =>
  CHART.y1 - (Math.max(0, Math.min(max, v)) / max) * (CHART.y1 - CHART.y0);

function smoothLine(points: { x: number; y: number }[]) {
  if (!points.length) return "";
  if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
  const d = [`M ${points[0].x} ${points[0].y}`];
  for (let i = 0; i < points.length - 1; i++) {
    const p0 = points[Math.max(i - 1, 0)],
      p1 = points[i],
      p2 = points[i + 1],
      p3 = points[Math.min(i + 2, points.length - 1)];
    const c1x = p1.x + (p2.x - p0.x) / 6,
      c2x = p2.x - (p3.x - p1.x) / 6;
    const c1y = Math.max(
      CHART.y0,
      Math.min(CHART.y1, p1.y + (p2.y - p0.y) / 6),
    );
    const c2y = Math.max(
      CHART.y0,
      Math.min(CHART.y1, p2.y - (p3.y - p1.y) / 6),
    );
    d.push(
      `C ${c1x.toFixed(2)} ${c1y.toFixed(2)} ${c2x.toFixed(2)} ${c2y.toFixed(2)} ${p2.x} ${p2.y}`,
    );
  }
  return d.join(" ");
}
function areaPath(points: { x: number; y: number }[]) {
  if (points.length < 2) return "";
  return `${smoothLine(points)} L ${points[points.length - 1].x} ${CHART.y1} L ${points[0].x} ${CHART.y1} Z`;
}
function useEntered(ref: React.RefObject<HTMLElement | null>) {
  const [entered, setEntered] = useState(false);
  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    if (typeof IntersectionObserver === "undefined") {
      setEntered(true);
      return;
    }
    const obs = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setEntered(true);
          obs.disconnect();
        }
      },
      { threshold: 0.12, rootMargin: "0px 0px 32px 0px" },
    );
    obs.observe(element);
    return () => obs.disconnect();
  }, [ref]);
  return entered;
}
function useCountUp(target: number, enabled: boolean, delay = 0) {
  const [shown, setShown] = useState(0);
  useEffect(() => {
    if (!enabled) return;
    const reduced =
      typeof window !== "undefined" &&
      window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    if (reduced) {
      setShown(target);
      return;
    }
    let frame = 0,
      timeout = 0;
    const duration = 1050;
    timeout = window.setTimeout(() => {
      let start: number | null = null;
      const step = (now: number) => {
        if (start === null) start = now;
        const progress = Math.min(1, (now - start) / duration);
        const eased = 1 - (1 - progress) ** 4;
        setShown(Math.round(target * eased));
        if (progress < 1) frame = window.requestAnimationFrame(step);
      };
      setShown(0);
      frame = window.requestAnimationFrame(step);
    }, delay);
    return () => {
      window.clearTimeout(timeout);
      window.cancelAnimationFrame(frame);
    };
  }, [target, enabled, delay]);
  return enabled ? shown : target;
}
function Count({
  value,
  active,
  delay = 0,
  suffix = "",
  formatted = false,
}: {
  value: number;
  active: boolean;
  delay?: number;
  suffix?: string;
  formatted?: boolean;
}) {
  const amount = useCountUp(value, active, delay);
  return (
    <>
      {formatted ? nf.format(amount) : amount}
      {suffix}
    </>
  );
}
/**
 * Self-contained stroke icons (no icon font, icon library or external assets).
 * Their paths never overlap in a way that hides the subject at small sizes.
 */
function Icon({
  name,
}: {
  name: "conversations" | "response" | "resolved" | "satisfaction";
}) {
  return (
    <span className="so-metric-icon" aria-hidden="true">
      <svg
        className="so-metric-svg"
        xmlns="http://www.w3.org/2000/svg"
        width={24}
        height={24}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth={1.9}
        strokeLinecap="round"
        strokeLinejoin="round"
        focusable="false"
        aria-hidden="true"
      >
        {name === "conversations" && (
          <>
            <path d="M20 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h9a4 4 0 0 1 4 4v8Z" />
            <path d="M7.5 9.5h8M7.5 13h5.5" />
          </>
        )}
        {name === "response" && (
          <>
            <circle cx="12" cy="13.5" r="8" />
            <path d="M9 2.5h6M12 9.5v4l2.5 1.5M19 5l1.5-1.5" />
          </>
        )}
        {name === "resolved" && (
          <>
            <path d="M20 11.2V12a8 8 0 1 1-4.7-7.3" />
            <path d="m8.5 11.8 3.2 3.2L21 5.7" />
          </>
        )}
        {name === "satisfaction" && (
          <path
            className="so-star-shape"
            d="m12 2.6 2.9 5.9 6.5.95-4.7 4.57 1.11 6.48L12 17.44l-5.81 3.06 1.11-6.48L2.6 9.45l6.5-.95L12 2.6Z"
            strokeWidth={1.5}
            fill="currentColor"
          />
        )}
      </svg>
    </span>
  );
}
function ActionIcon({
  name,
}: {
  name: "download" | "play" | "pause" | "replay";
}) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {name === "download" && (
        <path d="M12 3v12m0 0 4-4m-4 4-4-4M4 17v3h16v-3" />
      )}
      {name === "replay" && (
        <>
          <path d="M3 11a9 9 0 1 1 2.6 6.36" />
          <path d="M3 4v7h7" />
        </>
      )}
      {name === "play" && (
        <path d="m8 5 11 7-11 7V5Z" fill="currentColor" stroke="none" />
      )}
      {name === "pause" && <path d="M8 5v14M16 5v14" strokeWidth="3" />}
    </svg>
  );
}
function toCSV(rows: SupportDay[]) {
  const cell = (s: string | number) => `"${String(s).replace(/"/g, '""')}"`;
  return [
    "Date,Human,AI",
    ...rows.map((d) => [d.date, d.human, d.ai].map(cell).join(",")),
  ].join("\r\n");
}

export default function SupportOverview({
  channels,
  title = "Support overview",
  className = "",
  onDaySelect,
}: SupportOverviewProps) {
  const available = channels?.length ? channels : sampleSupportChannels;
  const [channelId, setChannelId] = useState(available[0].id);
  const [range, setRange] = useState<7 | 14 | 30>(30);
  const [visible, setVisible] = useState({ human: true, ai: true });
  const [hovered, setHovered] = useState<number | null>(null);
  const [pinned, setPinned] = useState<number | null>(null);
  const [playing, setPlaying] = useState(false);
  const [donutFocus, setDonutFocus] = useState(0);
  const [info, setInfo] = useState<string | null>(null);
  const [replay, setReplay] = useState(0);
  const dashboardRef = useRef<HTMLElement>(null);
  const plotRef = useRef<SVGSVGElement>(null);
  const entered = useEntered(dashboardRef);
  const uid = useId().replace(/:/g, "");
  const channel = available.find((c) => c.id === channelId) ?? available[0];
  const points = useMemo(
    () =>
      [...channel.data]
        .sort((a, b) => a.date.localeCompare(b.date))
        .slice(-range),
    [channel, range],
  );
  const chartMax = useMemo(
    () => Math.max(100, ...points.map((p) => Math.max(p.human, p.ai))),
    [points],
  );
  const xy = useMemo(
    () => ({
      human: points.map((d, i) => ({
        x: xAt(i, points.length),
        y: yAt(d.human, chartMax),
      })),
      ai: points.map((d, i) => ({
        x: xAt(i, points.length),
        y: yAt(d.ai, chartMax),
      })),
    }),
    [points, chartMax],
  );
  const active = hovered ?? pinned;
  const current = active === null ? null : (points[active] ?? null);
  const runKey = `${channel.id}-${replay}`;
  const drawKey = `${channel.id}-${range}-${replay}`;
  const mix = channel.metrics.resolutionMix;

  useEffect(() => {
    if (!playing || !points.length) return;
    const timer = window.setInterval(() => {
      setPinned((current) =>
        current === null ? 0 : Math.min(points.length - 1, current + 1),
      );
    }, 290);
    return () => window.clearInterval(timer);
  }, [playing, points.length]);

  useEffect(() => {
    if (playing && pinned !== null && pinned >= points.length - 1)
      setPlaying(false);
  }, [playing, pinned, points.length]);

  const selectDay = (i: number) => {
    if (!points.length) return;
    setPlaying(false);
    const next = Math.max(0, Math.min(points.length - 1, i));
    setPinned(next);
    onDaySelect?.(points[next], channel);
  };
  const changeRange = (n: 7 | 14 | 30) => {
    setRange(n);
    setPlaying(false);
    setHovered(null);
    setPinned(null);
  };
  const changeChannel = (id: string) => {
    setChannelId(id);
    setPlaying(false);
    setHovered(null);
    setPinned(null);
    setDonutFocus(0);
  };
  const toggleSeries = (key: Series) =>
    setVisible((previous) => {
      if (previous[key] && !previous[key === "human" ? "ai" : "human"])
        return previous;
      return { ...previous, [key]: !previous[key] };
    });
  const onPlotMove = (event: React.PointerEvent<SVGSVGElement>) => {
    if (!points.length || !plotRef.current) return;
    const b = plotRef.current.getBoundingClientRect();
    const x = ((event.clientX - b.left) / b.width) * CHART.width;
    const index = Math.round(
      ((x - CHART.x0) / (CHART.x1 - CHART.x0)) * (points.length - 1),
    );
    setHovered(Math.max(0, Math.min(points.length - 1, index)));
  };
  const onPlotKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {
    if (!points.length) return;
    if (
      ["ArrowLeft", "ArrowRight", "Home", "End", "Escape"].includes(event.key)
    )
      event.preventDefault();
    if (event.key === "ArrowLeft")
      selectDay((pinned ?? hovered ?? points.length) - 1);
    if (event.key === "ArrowRight") selectDay((pinned ?? hovered ?? -1) + 1);
    if (event.key === "Home") selectDay(0);
    if (event.key === "End") selectDay(points.length - 1);
    if (event.key === "Escape") {
      setPlaying(false);
      setPinned(null);
      setHovered(null);
    }
  };
  const exportCSV = () => {
    const url = URL.createObjectURL(
      new Blob([toCSV(points)], { type: "text/csv;charset=utf-8" }),
    );
    const a = document.createElement("a");
    a.href = url;
    a.download = `support-overview-${channel.id}-${range}d.csv`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.setTimeout(() => URL.revokeObjectURL(url), 1000);
  };
  const metrics = [
    {
      key: "conversations" as const,
      label: "Conversations",
      num: channel.metrics.conversations,
      suffix: "",
      hint: "Total conversations for this channel.",
      delay: 90,
    },
    {
      key: "response" as const,
      label: "First response",
      num: channel.metrics.firstResponseSeconds,
      suffix: "s",
      hint: "Average time until the first response.",
      delay: 190,
    },
    {
      key: "resolved" as const,
      label: "AI resolved",
      num: channel.metrics.aiResolvedPercent,
      suffix: "%",
      hint: "Percentage of conversations resolved by AI.",
      delay: 290,
    },
    {
      key: "satisfaction" as const,
      label: "Satisfaction",
      num: channel.metrics.satisfactionPercent,
      suffix: "%",
      hint: "Customer satisfaction rate.",
      delay: 390,
    },
  ];
  const ticks = points.length <= 7 ? 1 : points.length <= 14 ? 2 : 5;
  const selectedPointX = active === null ? null : xAt(active, points.length);
  return (
    <section
      ref={dashboardRef}
      className={`so-dashboard ${entered ? "so-entered" : ""} ${className}`}
      aria-label={title}
    >
      <header className="so-heading-row">
        <div className="so-heading-left">
          <h2 className="so-main-title">{title}</h2>
          <div className="so-heading-sub">
            Track conversations, people and AI performance
          </div>
        </div>
        <div className="so-heading-actions">
          <span className="so-live-note">
            <span className="so-live-dot" /> Overview
          </span>
          <button
            className="so-replay"
            type="button"
            onClick={() => {
              setReplay((v) => v + 1);
              setPinned(null);
              setHovered(null);
              setPlaying(false);
              setInfo(null);
            }}
            title="Replay all dashboard animations"
          >
            <ActionIcon name="replay" />
            <span>Replay</span>
          </button>
        </div>
      </header>
      <div className="so-stats">
        {metrics.map((m, i) => (
          <article
            key={`${m.key}-${replay}`}
            className="so-stat"
            style={{ "--so-order": i } as React.CSSProperties}
          >
            <div className="so-stat-shine" aria-hidden="true" />
            <div className="so-stat-text">
              <div className="so-stat-label">{m.label}</div>
              <div className="so-stat-value">
                <Count
                  key={runKey}
                  value={m.num}
                  active={entered}
                  delay={m.delay}
                  suffix={m.suffix}
                  formatted={m.key === "conversations"}
                />
              </div>
            </div>
            <button
              type="button"
              className="so-stat-icon-button"
              aria-label={`About ${m.label}`}
              title={`About ${m.label}`}
              aria-expanded={info === m.key}
              onClick={() => setInfo(info === m.key ? null : m.key)}
            >
              <Icon name={m.key} />
            </button>
            {info === m.key && (
              <output className="so-info-popover">{m.hint}</output>
            )}
          </article>
        ))}
      </div>
      <div className="so-chart-grid">
        <section
          className="so-panel so-volume-panel"
          aria-label="Conversation volume chart"
        >
          <header className="so-panel-header">
            <div className="so-panel-heading">
              <h3>Conversation volume</h3>
              <span>Human vs AI · Daily activity</span>
            </div>
            <div className="so-chart-actions">
              <fieldset
                className="so-range-control"
                aria-label="Chart date range"
              >
                {([7, 14, 30] as const).map((n) => (
                  <button
                    type="button"
                    key={n}
                    aria-pressed={range === n}
                    className={range === n ? "so-range-active" : ""}
                    onClick={() => changeRange(n)}
                  >
                    {n}D
                  </button>
                ))}
              </fieldset>
              <button
                type="button"
                className={`so-icon-action ${playing ? "so-is-playing" : ""}`}
                title={playing ? "Pause timeline" : "Play chart timeline"}
                aria-label={playing ? "Pause timeline" : "Play chart timeline"}
                onClick={() => {
                  if (!playing) setPinned(null);
                  setHovered(null);
                  setPlaying((v) => !v);
                }}
              >
                <ActionIcon name={playing ? "pause" : "play"} />
              </button>
              <button
                className="so-icon-action"
                type="button"
                onClick={exportCSV}
                title="Export visible data as CSV"
                aria-label="Download CSV"
              >
                <ActionIcon name="download" />
              </button>
            </div>
          </header>
          {points.length ? (
            <section
              className="so-chart-scroll"
              aria-label="Scrollable chart area"
            >
              <div
                className="so-plot-wrap"
                role="slider"
                tabIndex={0}
                aria-valuemin={0}
                aria-valuemax={Math.max(0, points.length - 1)}
                aria-valuenow={active ?? Math.max(0, points.length - 1)}
                aria-valuetext={
                  current
                    ? `${current.date}: human ${current.human}, AI ${current.ai}`
                    : undefined
                }
                aria-label="Conversation volume by day. Hover, click, or use arrow keys to inspect dates."
                onKeyDown={onPlotKeyDown}
                onClick={() => {
                  if (hovered !== null) {
                    if (pinned === hovered) {
                      setPinned(null);
                    } else selectDay(hovered);
                  }
                }}
              >
                <svg
                  ref={plotRef}
                  className="so-plot"
                  viewBox={`0 0 ${CHART.width} ${CHART.height}`}
                  aria-hidden="true"
                  onPointerMove={onPlotMove}
                  onPointerLeave={() => setHovered(null)}
                >
                  <defs>
                    <linearGradient
                      id={`${uid}-human-gradient`}
                      x1="0"
                      y1="0"
                      x2="0"
                      y2="1"
                    >
                      <stop offset="0%" stopColor={PURPLE} stopOpacity=".19" />
                      <stop offset="100%" stopColor={PURPLE} stopOpacity="0" />
                    </linearGradient>
                    <linearGradient
                      id={`${uid}-ai-gradient`}
                      x1="0"
                      y1="0"
                      x2="0"
                      y2="1"
                    >
                      <stop offset="0%" stopColor={CORAL} stopOpacity=".11" />
                      <stop offset="100%" stopColor={CORAL} stopOpacity="0" />
                    </linearGradient>
                  </defs>
                  {Array.from({ length: 6 }, (_, i) => {
                    const val = chartMax - (chartMax / 5) * i,
                      y = yAt(val, chartMax);
                    return (
                      <g key={`grid-${Math.round(val)}`}>
                        <line
                          x1={CHART.x0}
                          x2={CHART.x1}
                          y1={y}
                          y2={y}
                          className="so-grid-line"
                        />
                        <text
                          x={CHART.x0 - 9}
                          y={y + 4}
                          className="so-axis-number"
                          textAnchor="end"
                        >
                          {Math.round(val)}
                        </text>
                      </g>
                    );
                  })}
                  {points.map(
                    (p, i) =>
                      (i % ticks === 0 || i === points.length - 1) && (
                        <line
                          key={p.date}
                          x1={xAt(i, points.length)}
                          x2={xAt(i, points.length)}
                          y1={CHART.y0}
                          y2={CHART.y1}
                          className="so-grid-line so-vertical-line"
                        />
                      ),
                  )}
                  <g key={`${drawKey}-areas`} className="so-chart-reveal">
                    {visible.human && (
                      <path
                        d={areaPath(xy.human)}
                        fill={`url(#${uid}-human-gradient)`}
                      />
                    )}
                    {visible.ai && (
                      <path
                        d={areaPath(xy.ai)}
                        fill={`url(#${uid}-ai-gradient)`}
                      />
                    )}
                  </g>
                  {(["human", "ai"] as const).map(
                    (type) =>
                      visible[type] && (
                        <g key={`${drawKey}-${type}`} className="so-series">
                          <path
                            d={smoothLine(xy[type])}
                            pathLength="1"
                            className={`so-series-line so-${type}-line`}
                            fill="none"
                            stroke={type === "human" ? PURPLE : CORAL}
                            strokeWidth="2.35"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                          {xy[type].map((p, i) => (
                            <circle
                              key={points[i].date}
                              className="so-chart-marker"
                              cx={p.x}
                              cy={p.y}
                              r={active === i ? 4.6 : 2.9}
                              fill="#fff"
                              stroke={type === "human" ? PURPLE : CORAL}
                              strokeWidth={active === i ? 2 : 1.6}
                              style={
                                {
                                  "--so-point-delay": `${260 + (i / Math.max(1, points.length - 1)) * 1050}ms`,
                                } as React.CSSProperties
                              }
                            />
                          ))}
                        </g>
                      ),
                  )}
                  {selectedPointX !== null && active !== null && (
                    <g className="so-cursor">
                      <line
                        x1={selectedPointX}
                        x2={selectedPointX}
                        y1={CHART.y0}
                        y2={CHART.y1}
                        stroke="#8c80ee"
                        strokeWidth="1.25"
                        strokeDasharray="4 4"
                      />
                      <circle
                        cx={selectedPointX}
                        cy={CHART.y1}
                        r="3"
                        fill={PURPLE}
                      />
                      {(["human", "ai"] as const)
                        .filter((t) => visible[t])
                        .map((t) => (
                          <circle
                            key={t}
                            cx={selectedPointX}
                            cy={xy[t][active].y}
                            r="7"
                            className="so-active-halo"
                            fill={t === "human" ? PURPLE : CORAL}
                            fillOpacity=".14"
                          />
                        ))}
                    </g>
                  )}
                  <line
                    x1={CHART.x0}
                    x2={CHART.x1}
                    y1={CHART.y1}
                    y2={CHART.y1}
                    stroke="#dddce7"
                    strokeWidth="1"
                  />
                  {points.map(
                    (p, i) =>
                      (i % ticks === 0 || i === points.length - 1) && (
                        <text
                          key={`axis-${p.date}`}
                          x={xAt(i, points.length)}
                          y={CHART.y1 + 23}
                          className="so-date-label"
                          textAnchor="middle"
                        >
                          {dateInfo(p.date).short}
                        </text>
                      ),
                  )}
                </svg>
                {current && selectedPointX !== null && (
                  <output
                    className="so-tooltip"
                    style={{
                      left: `${Math.max(12, Math.min(88, (selectedPointX / CHART.width) * 100))}%`,
                    }}
                  >
                    <strong>{dateInfo(current.date).full}</strong>
                    {visible.human && (
                      <span>
                        <i style={{ background: PURPLE }} />
                        Human <b>{current.human}</b>
                      </span>
                    )}
                    {visible.ai && (
                      <span>
                        <i style={{ background: CORAL }} />
                        AI <b>{current.ai}</b>
                      </span>
                    )}
                    <small>
                      {playing
                        ? "Playing trend"
                        : pinned !== null
                          ? "Click elsewhere to select"
                          : "Click to pin this day"}
                    </small>
                  </output>
                )}
              </div>
            </section>
          ) : (
            <div className="so-empty">No conversation data available.</div>
          )}
          <fieldset className="so-legend" aria-label="Toggle chart series">
            <button
              type="button"
              className={!visible.human ? "so-legend-off" : ""}
              aria-pressed={visible.human}
              onClick={() => toggleSeries("human")}
            >
              <span className="so-legend-key so-human-key" /> Human
            </button>
            <button
              type="button"
              className={!visible.ai ? "so-legend-off" : ""}
              aria-pressed={visible.ai}
              onClick={() => toggleSeries("ai")}
            >
              <span className="so-legend-key so-ai-key" /> AI
            </button>
            <span className="so-legend-help">Hover to explore</span>
          </fieldset>
        </section>
        <section
          className="so-panel so-resolution-panel"
          aria-label="Resolution mix"
        >
          <header className="so-panel-header">
            <div className="so-panel-heading">
              <h3>Resolution mix</h3>
              <span>Where conversations end up</span>
            </div>
            <label className="so-select-wrap">
              <span className="so-sr-only">Select support channel</span>
              <select
                value={channel.id}
                onChange={(event) => changeChannel(event.target.value)}
              >
                {available.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                  </option>
                ))}
              </select>
              <svg
                viewBox="0 0 12 12"
                width="12"
                height="12"
                aria-hidden="true"
              >
                <path
                  d="m2 4 4 4 4-4"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.3"
                  strokeLinecap="round"
                />
              </svg>
            </label>
          </header>
          <div className="so-donut-wrap">
            <div className="so-donut">
              <svg
                viewBox="0 0 240 240"
                role="img"
                aria-label={`AI resolved ${mix[0]}%, human resolved ${mix[1]}%, escalated ${mix[2]}%`}
              >
                <defs>
                  <mask id={`${uid}-donut-mask`}>
                    <circle
                      key={`${drawKey}-mask`}
                      className="so-donut-reveal"
                      cx="120"
                      cy="120"
                      r="90"
                      fill="none"
                      stroke="white"
                      strokeWidth="45"
                      pathLength="100"
                      strokeDasharray="100"
                      strokeDashoffset="100"
                      transform="rotate(-90 120 120)"
                    />
                  </mask>
                </defs>
                <circle
                  cx="120"
                  cy="120"
                  r="90"
                  fill="none"
                  stroke="#f0edff"
                  strokeWidth="32"
                />
                <g mask={`url(#${uid}-donut-mask)`}>
                  {mix.map((pct, index) => {
                    const start = mix
                      .slice(0, index)
                      .reduce((a, b) => a + b, 0);
                    const name = SEGMENTS[index];
                    return (
                      // Donut slices are SVG strokes; a native <button> can't draw the arc.
                      // biome-ignore lint/a11y/useSemanticElements: SVG geometry requires role="button"
                      <circle
                        key={`${channel.id}-${name}`}
                        cx="120"
                        cy="120"
                        r="90"
                        pathLength="100"
                        fill="none"
                        stroke={COLORS[index]}
                        strokeWidth={donutFocus === index ? 36 : 32}
                        strokeDasharray={`${pct} ${100 - pct}`}
                        strokeDashoffset={-start}
                        transform="rotate(-90 120 120)"
                        className={`so-donut-segment ${donutFocus === index ? "so-donut-selected" : ""}`}
                        role="button"
                        tabIndex={0}
                        aria-label={`${name}: ${pct}%`}
                        aria-pressed={donutFocus === index}
                        onClick={() => setDonutFocus(index)}
                        onKeyDown={(event) => {
                          if (event.key === "Enter" || event.key === " ") {
                            event.preventDefault();
                            setDonutFocus(index);
                          }
                        }}
                      >
                        <title>
                          {name}: {pct}%
                        </title>
                      </circle>
                    );
                  })}
                </g>
              </svg>
              <div className="so-donut-center" aria-live="polite">
                <strong style={{ color: COLORS[donutFocus] }}>
                  <Count
                    key={`${runKey}-${donutFocus}`}
                    value={mix[donutFocus]}
                    active={entered}
                    suffix="%"
                    delay={230}
                  />
                </strong>
                <span>{SEGMENTS[donutFocus]}</span>
              </div>
            </div>
          </div>
          <fieldset
            className="so-donut-legend"
            aria-label="Resolution categories"
          >
            {SEGMENTS.map((name, i) => (
              <button
                type="button"
                key={name}
                className={donutFocus === i ? "so-donut-legend-active" : ""}
                aria-pressed={donutFocus === i}
                onClick={() => setDonutFocus(i)}
              >
                <i style={{ background: COLORS[i] }} />
                <span>{name}</span>
              </button>
            ))}
          </fieldset>
        </section>
      </div>
    </section>
  );
}
