'use client';

import { useEffect, useRef, useState } from 'react';

/** Step type colours of the Analyze charts (design: Automated email, Manual email task, …). */
export const STEP_TYPE_COLORS = {
  automated_email: '#2e7bdb',
  manual_email: '#ec6a35',
  call_task: '#1fb07b',
  task: '#efa30c',
} as const;
export const LINE_COLOR = '#ec6a35';

/** Width of an element, kept up to date (charts draw in real pixels so text stays crisp). */
function useWidth<T extends HTMLElement>(fallback = 640) {
  const ref = useRef<T>(null);
  const [width, setWidth] = useState(fallback);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    setWidth(el.clientWidth || fallback);
    const observer = new ResizeObserver(([entry]) => {
      if (entry) setWidth(Math.max(240, Math.floor(entry.contentRect.width)));
    });
    observer.observe(el);
    return () => observer.disconnect();
  }, [fallback]);
  return [ref, width] as const;
}

/** A round axis top (4, 10, 20, 50, …) and its three ticks: 0, half, top. */
export function niceTicks(max: number): number[] {
  if (max <= 4) return [0, 2, 4];
  const magnitude = 10 ** Math.floor(Math.log10(max));
  const top = [1, 2, 5, 10].map((m) => m * magnitude).find((v) => v >= max) ?? 10 * magnitude;
  return [0, top / 2, top];
}

export interface LinePoint {
  label: string;
  /** Tooltip heading, e.g. the week. */
  title: string;
  value: number;
}

/** One series over time, hollow points (design: Performance over time). */
export function TimeLineChart({
  points,
  seriesLabel,
  xTitle,
  height = 380,
}: {
  points: LinePoint[];
  seriesLabel: string;
  xTitle: string;
  height?: number;
}) {
  const [ref, width] = useWidth<HTMLDivElement>();
  const pad = { top: 16, right: 24, bottom: 64, left: 52 };
  const innerW = width - pad.left - pad.right;
  const innerH = height - pad.top - pad.bottom;
  const ticks = niceTicks(Math.max(0, ...points.map((p) => p.value)));
  const top = ticks[ticks.length - 1]!;
  const last = Math.max(1, points.length - 1);
  const xAt = (i: number) => pad.left + (points.length <= 1 ? innerW / 2 : (i / last) * innerW);
  const yAt = (v: number) => pad.top + innerH - (v / top) * innerH;
  const labelEvery = Math.max(1, Math.ceil(points.length / Math.max(2, Math.floor(innerW / 110))));
  const r = points.length > 120 ? 2.5 : 5;

  return (
    <div ref={ref} className="seqa-chart" role="img" aria-label={`${seriesLabel} by ${xTitle}`}>
      <svg width={width} height={height}>
        {ticks.map((t) => (
          <g key={t}>
            <line
              x1={pad.left}
              x2={width - pad.right}
              y1={yAt(t)}
              y2={yAt(t)}
              className="seqa-chart__grid"
            />
            <text x={pad.left - 14} y={yAt(t) + 5} textAnchor="end" className="seqa-chart__tick">
              {t.toLocaleString()}
            </text>
          </g>
        ))}
        <polyline
          fill="none"
          stroke={LINE_COLOR}
          strokeWidth={2.5}
          strokeLinejoin="round"
          points={points.map((p, i) => `${xAt(i)},${yAt(p.value)}`).join(' ')}
        />
        {points.map((p, i) => (
          <circle
            key={i}
            cx={xAt(i)}
            cy={yAt(p.value)}
            r={r}
            fill="var(--surface)"
            stroke={LINE_COLOR}
            strokeWidth={2.5}
          >
            <title>{`${p.title}\n${seriesLabel}: ${p.value.toLocaleString()}`}</title>
          </circle>
        ))}
        {points.map((p, i) =>
          i % labelEvery === 0 ? (
            <text
              key={`l${i}`}
              x={xAt(i)}
              y={pad.top + innerH + 28}
              // Sequences QA manage BUG-06: the last label ends at its point, so a long one
              // ("Q4 2026") stays inside the chart instead of being cut at the right edge.
              textAnchor={i === points.length - 1 && points.length > 1 ? 'end' : 'middle'}
              className="seqa-chart__tick"
            >
              {p.label}
            </text>
          ) : null,
        )}
        <text
          x={pad.left + innerW / 2}
          y={height - 8}
          textAnchor="middle"
          className="seqa-chart__axis-title"
        >
          {xTitle}
        </text>
      </svg>
    </div>
  );
}

export interface ColumnDatum {
  key: string;
  label: string;
  value: number;
  /** Tooltip lines under the label. */
  hint: string[];
}

/** Vertical columns with their value on top (design: Meetings booked by step type). */
export function ValueColumnChart({
  rows,
  xTitle,
  ariaLabel,
  height = 340,
}: {
  rows: ColumnDatum[];
  xTitle: string;
  ariaLabel: string;
  height?: number;
}) {
  const [ref, width] = useWidth<HTMLDivElement>();
  const pad = { top: 28, right: 16, bottom: 72, left: 44 };
  const innerW = width - pad.left - pad.right;
  const innerH = height - pad.top - pad.bottom;
  const ticks = niceTicks(Math.max(0, ...rows.map((r) => r.value)));
  const top = ticks[ticks.length - 1]!;
  const slot = innerW / Math.max(1, rows.length);
  const barW = Math.min(60, slot * 0.55);
  const yAt = (v: number) => pad.top + innerH - (v / top) * innerH;

  return (
    <div ref={ref} className="seqa-chart" role="img" aria-label={ariaLabel}>
      <svg width={width} height={height}>
        {ticks.map((t) => (
          <g key={t}>
            <line
              x1={pad.left}
              x2={width - pad.right}
              y1={yAt(t)}
              y2={yAt(t)}
              className="seqa-chart__grid"
            />
            <text x={pad.left - 12} y={yAt(t) + 5} textAnchor="end" className="seqa-chart__tick">
              {t.toLocaleString()}
            </text>
          </g>
        ))}
        {rows.map((row, i) => {
          const cx = pad.left + slot * i + slot / 2;
          // Empty columns keep a sliver so every type stays visible.
          const h = Math.max(row.value > 0 ? 2 : 4, (row.value / top) * innerH);
          return (
            <g key={row.key}>
              <rect
                x={cx - barW / 2}
                y={pad.top + innerH - h}
                width={barW}
                height={h}
                rx={3}
                fill={STEP_TYPE_COLORS.automated_email}
                opacity={row.value > 0 ? 1 : 0.6}
              >
                <title>{[row.label, ...row.hint].join('\n')}</title>
              </rect>
              {row.value > 0 ? (
                <text
                  x={cx}
                  y={pad.top + innerH - h - 8}
                  textAnchor="middle"
                  className="seqa-chart__value"
                >
                  {row.value.toLocaleString()}
                </text>
              ) : null}
              <text
                x={cx}
                y={pad.top + innerH + 22}
                textAnchor="middle"
                className="seqa-chart__tick"
              >
                {row.label}
              </text>
            </g>
          );
        })}
        <text
          x={pad.left + innerW / 2}
          y={height - 10}
          textAnchor="middle"
          className="seqa-chart__axis-title"
        >
          {xTitle}
        </text>
      </svg>
    </div>
  );
}

export interface StackSegment {
  key: string;
  label: string;
  color: string;
  value: number;
}

/** Horizontal stacked bars with the total at the end (design: by number of touches). */
export function StackedBarChart({
  rows,
  legend,
  xTitle,
  yTitle,
  ariaLabel,
}: {
  rows: Array<{ key: string; label: string; segments: StackSegment[] }>;
  legend: Array<{ key: string; label: string; color: string }>;
  xTitle: string;
  yTitle: string;
  ariaLabel: string;
}) {
  const [ref, width] = useWidth<HTMLDivElement>();
  const rowH = 46;
  const pad = { top: 8, right: 56, bottom: 64, left: 64 };
  const height = pad.top + pad.bottom + Math.max(1, rows.length) * rowH;
  const innerW = width - pad.left - pad.right;
  const innerH = height - pad.top - pad.bottom;
  const totals = rows.map((r) => r.segments.reduce((s, x) => s + x.value, 0));
  const ticks = niceTicks(Math.max(0, ...totals));
  const top = ticks[ticks.length - 1]!;
  const xAt = (v: number) => pad.left + (v / top) * innerW;
  const gap = 3;

  return (
    <div ref={ref} className="seqa-chart" role="img" aria-label={ariaLabel}>
      <ul className="seqa-legend">
        {legend.map((l) => (
          <li key={l.key}>
            <span className="seqa-legend__dot" style={{ background: l.color }} />
            {l.label}
          </li>
        ))}
      </ul>
      <svg width={width} height={height}>
        {ticks.map((t) => (
          <g key={t}>
            <line
              x1={xAt(t)}
              x2={xAt(t)}
              y1={pad.top}
              y2={pad.top + innerH}
              className="seqa-chart__grid"
            />
            <text
              x={xAt(t)}
              y={pad.top + innerH + 24}
              textAnchor="middle"
              className="seqa-chart__tick"
            >
              {t.toLocaleString()}
            </text>
          </g>
        ))}
        {rows.map((row, i) => {
          const y = pad.top + i * rowH + 8;
          const h = rowH - 16;
          let x = pad.left;
          return (
            <g key={row.key}>
              <text
                x={pad.left - 14}
                y={y + h / 2 + 5}
                textAnchor="end"
                className="seqa-chart__tick"
              >
                {row.label}
              </text>
              {row.segments
                .filter((s) => s.value > 0)
                .map((s) => {
                  const w = Math.max(2, (s.value / top) * innerW - gap);
                  const rect = (
                    <rect key={s.key} x={x} y={y} width={w} height={h} rx={3} fill={s.color}>
                      <title>{`${row.label} ${yTitle.toLowerCase()}\n${s.label}: ${s.value}`}</title>
                    </rect>
                  );
                  x += w + gap;
                  return rect;
                })}
              <text x={x + 8} y={y + h / 2 + 5} className="seqa-chart__value">
                {totals[i]!.toLocaleString()}
              </text>
            </g>
          );
        })}
        <text
          x={pad.left + innerW / 2}
          y={height - 10}
          textAnchor="middle"
          className="seqa-chart__axis-title"
        >
          {xTitle}
        </text>
        <text
          x={18}
          y={pad.top + innerH / 2}
          textAnchor="middle"
          transform={`rotate(-90 18 ${pad.top + innerH / 2})`}
          className="seqa-chart__axis-title"
        >
          {yTitle}
        </text>
      </svg>
    </div>
  );
}
