/* eslint-disable @next/next/no-img-element */
'use client';

import {
  type MouseEvent,
  type ReactNode,
  type RefObject,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';

import { area, curveMonotoneX, interpolateRgb, scaleLinear } from 'd3';
import { X } from 'lucide-react';

import CreatorCard from '@/components/creators/CreatorCard';
import { Button } from '@/components/ui/button';
import { Text } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
import { buildMediaUrl } from '@/utils/images';

import { Link } from '@/i18n/navigation';

import type { Ranked } from './types';

const INK = '#151720';
const SLATE = '#3b3f58';
const ACCENT = '#dfcf6f';
const TRACK = 'rgba(21, 23, 32, 0.07)';
// Sequential ramp: one hue, light to dark.
const ramp = interpolateRgb('#eef0f5', SLATE);
// Validated categorical slots (dataviz reference palette, first five, light mode).
export const SERIES = ['#2a78d6', '#eb6834', '#1baf7a', '#eda100', '#e87ba4'];

export const formatNumber = (value: number) => value.toLocaleString('hu-HU');
export const formatPercent = (share: number) =>
  `${(share * 100).toLocaleString('hu-HU', { maximumFractionDigits: share < 0.1 ? 1 : 0 })}%`;

/** The width the element is drawn at, in CSS px; null until it is measured in the browser. */
export function useElementWidth(ref: RefObject<Element | null>) {
  const [width, setWidth] = useState<number | null>(null);
  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry.contentRect.width)));
    observer.observe(element);
    return () => observer.disconnect();
  }, [ref]);
  return width;
}

// Charts drawn narrower than this switch to their compact layout, at their real size: one viewBox
// unit a CSS px, so their text keeps its size on a phone instead of shrinking with the chart.
const COMPACT_BELOW = 560;

/** The chart's drawn width in CSS px when it is narrow enough for its compact layout, else null. */
export function useCompactWidth(ref: RefObject<Element | null>) {
  const width = useElementWidth(ref);
  return width !== null && width < COMPACT_BELOW ? width : null;
}

// "1980-as", "1990-es": the suffix follows the last two digits as read out loud.
const DECADE_SUFFIX: Record<string, string> = {
  '00': 'es',
  '10': 'es',
  '20': 'as',
  '30': 'as',
  '40': 'es',
  '50': 'es',
  '60': 'as',
  '70': 'es',
  '80': 'as',
  '90': 'es',
};
export const decadeLabel = (decade: number | string) =>
  `${decade}-${DECADE_SUFFIX[String(decade).slice(-2)] ?? 'es'}`;

/**
 * A decade column's label in two lines, as in the decades block: "1990–" over "2000". The
 * decade still under way has no end yet: "2020–". Phones get the short years ("'90–" over "'00"),
 * as the full ones would not fit under a column.
 */
export function decadeRangeTick(decade: number | string) {
  const start = Number(decade);
  const end = start + 10;
  const open = end > new Date().getFullYear();
  const short = (year: number) => `'${String(year).slice(2)}`;
  return (
    <>
      <span className="block sm:hidden">{short(start)}–</span>
      <span className="block sm:hidden">{open ? ' ' : short(end)}</span>
      <span className="hidden sm:block">{start}–</span>
      <span className="hidden sm:block">{open ? ' ' : end}</span>
    </>
  );
}

/**
 * `count` items of `list` at random, and a function that draws again, preferring the ones not
 * shown yet. The server can't draw (the browser would draw differently), so the first render
 * shows the start of the list, and the first draw comes right after it, in the browser.
 */
export function useRandomSample<T>(list: T[], count: number) {
  const [picked, setPicked] = useState(() => list.slice(0, count));
  const seen = useRef(new Set<number>());
  const draw = useCallback(() => {
    if (seen.current.size + count > list.length) seen.current.clear();
    const fresh = list.map((_, index) => index).filter((index) => !seen.current.has(index));
    for (let i = fresh.length - 1; i > 0; i -= 1) {
      const j = Math.floor(Math.random() * (i + 1));
      [fresh[i], fresh[j]] = [fresh[j], fresh[i]];
    }
    const next = fresh.slice(0, count);
    next.forEach((index) => seen.current.add(index));
    setPicked(next.map((index) => list[index]));
  }, [list, count]);
  useEffect(() => draw(), [draw]);
  return [picked, draw] as const;
}

/** A one-line readout above a chart: what the pointer is on, or the default text. */
function Readout({ children }: { children: React.ReactNode }) {
  return (
    <div className="mb-3 min-h-[20px] text-sm font-semibold tabular-nums text-[#151720]">
      {children}
    </div>
  );
}

/** Horizontal bars, longest first, with the value at the end of each row. */
export function BarList({
  items,
  highlight,
  format = formatNumber,
  wrapLabels = false,
  unit = '',
  large = false,
}: {
  items: Ranked[];
  highlight?: string;
  format?: (value: number) => string;
  unit?: string;
  wrapLabels?: boolean;
  /** A few rows with short labels (e.g. "< 25"): tall bars, the label column only as wide as needed. */
  large?: boolean;
}) {
  const max = Math.max(...items.map((item) => item.value), 1);
  return (
    <ul className={cn('flex flex-col', large ? 'gap-3' : 'gap-1.5')}>
      {items.map((item) => (
        <li
          key={item.label}
          className={cn(
            'grid items-center gap-3',
            large
              ? 'grid-cols-[3.5rem_minmax(0,1fr)_auto] text-base'
              : 'grid-cols-[minmax(0,9rem)_minmax(0,1fr)_auto] text-sm sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]'
          )}
          title={`${item.label}: ${format(item.value)}${unit}`}
        >
          <span className={cn('text-[#151720]/80', wrapLabels ? 'break-words' : 'truncate')}>
            {item.label}
          </span>
          <span
            className={cn('overflow-hidden', large ? 'h-8' : 'h-3')}
            style={{ background: TRACK }}
          >
            <span
              className="block h-full rounded-r"
              style={{
                width: `${(item.value / max) * 100}%`,
                background: item.label === highlight ? ACCENT : SLATE,
              }}
            />
          </span>
          <span className="w-16 text-right font-semibold tabular-nums text-[#151720]">
            {format(item.value)}
          </span>
        </li>
      ))}
    </ul>
  );
}

/** Vertical bars, e.g. per decade. */
export function Columns({
  items,
  unit,
  readout = (label) => `${decadeLabel(label)} évek`,
  tick = (label) => label,
}: {
  items: Ranked[];
  unit: string;
  /** What a column is called in the readout; decades by default ("1990-es évek"). */
  readout?: (label: string) => string;
  /** The label under a column. */
  tick?: (label: string) => ReactNode;
}) {
  const [active, setActive] = useState<Ranked | null>(null);
  const max = Math.max(...items.map((item) => item.value), 1);
  const total = items.reduce((sum, item) => sum + item.value, 0);
  return (
    <div>
      <Readout>
        {active
          ? `${readout(active.label)}: ${formatNumber(active.value)} ${unit}`
          : `Összesen ${formatNumber(total)} ${unit}`}
      </Readout>
      <div className="flex h-56 items-end gap-1.5 sm:gap-2" onMouseLeave={() => setActive(null)}>
        {items.map((item) => (
          <div
            key={item.label}
            className="group flex h-full min-w-0 flex-1 flex-col justify-end"
            onMouseEnter={() => setActive(item)}
          >
            <div
              className="rounded-t transition-colors"
              style={{
                height: `${(item.value / max) * 100}%`,
                background: active?.label === item.label ? ACCENT : SLATE,
              }}
            />
          </div>
        ))}
      </div>
      <div className="mt-2 flex gap-1.5 sm:gap-2">
        {items.map((item) => (
          <span
            key={item.label}
            className="min-w-0 flex-1 truncate text-center text-[11px] text-[#151720]/55"
          >
            {tick(item.label)}
          </span>
        ))}
      </div>
    </div>
  );
}

export const CITIES: { name: string; lng: number; lat: number }[] = [
  { name: 'Budapest', lng: 19.04, lat: 47.5 },
  { name: 'Győr', lng: 17.63, lat: 47.69 },
  { name: 'Pécs', lng: 18.23, lat: 46.07 },
  { name: 'Szeged', lng: 20.15, lat: 46.25 },
  { name: 'Debrecen', lng: 21.63, lat: 47.53 },
  { name: 'Miskolc', lng: 20.78, lat: 48.1 },
  { name: 'Kolozsvár', lng: 23.59, lat: 46.77 },
];

/* ---- Sample-data charts: shapes for views whose data is not available yet ---- */

/* ---- Snapshot charts: creators, careers and awards ---- */

const LIGHT_SLATE = '#b9bdcc';

/** Birth decades, split into living and deceased creators. */
export function Generations({
  items,
}: {
  items: { decade: number; alive: number; deceased: number }[];
}) {
  const [active, setActive] = useState<(typeof items)[number] | null>(null);
  const max = Math.max(...items.map((item) => item.alive + item.deceased), 1);
  return (
    <div>
      <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
        <div className="min-h-[20px] text-sm font-semibold tabular-nums text-[#151720]">
          {active
            ? `${decadeLabel(active.decade)} években született: ${formatNumber(active.alive + active.deceased)} alkotó (${formatNumber(active.deceased)} elhunyt)`
            : 'Születési évtized szerint'}
        </div>
        <ul className="flex gap-4 text-xs text-[#151720]/70">
          <li className="flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded-sm" style={{ background: SLATE }} />
            élő
          </li>
          <li className="flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded-sm" style={{ background: LIGHT_SLATE }} />
            elhunyt
          </li>
        </ul>
      </div>
      <div className="flex h-56 items-end gap-1.5" onMouseLeave={() => setActive(null)}>
        {items.map((item) => (
          <div
            key={item.decade}
            className="flex h-full min-w-0 flex-1 flex-col justify-end gap-[2px]"
            onMouseEnter={() => setActive(item)}
          >
            <div
              className="rounded-t"
              style={{
                height: `${(item.deceased / max) * 100}%`,
                background: active?.decade === item.decade ? ACCENT : LIGHT_SLATE,
              }}
            />
            <div
              style={{
                height: `${(item.alive / max) * 100}%`,
                background: active?.decade === item.decade ? ACCENT : SLATE,
              }}
            />
          </div>
        ))}
      </div>
      <div className="mt-2 flex gap-1.5">
        {items.map((item) => (
          <span
            key={item.decade}
            className="min-w-0 flex-1 truncate text-center text-[11px] text-[#151720]/55"
          >
            {`'${String(item.decade).slice(2)}`}
          </span>
        ))}
      </div>
    </div>
  );
}

const MONTH_NAMES = [
  'január',
  'február',
  'március',
  'április',
  'május',
  'június',
  'július',
  'augusztus',
  'szeptember',
  'október',
  'november',
  'december',
];
const DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

/** A creator's name as a link to their page (in a new tab, see openDetailsInNewTab). */
export function PersonName({ person }: { person: { id: string; name: string } }) {
  return (
    <Link
      href={{ pathname: '/alkoto/[id]', params: { id: person.id } }}
      className="font-semibold underline decoration-[#151720]/25 underline-offset-2 hover:decoration-[#151720]"
    >
      {person.name}
    </Link>
  );
}

/**
 * A small closable box beside a point of a map or calendar, with the people who belong to it. It
 * opens towards the middle of the view; on a phone, under it. Escape closes it, as the X does.
 */
export function PeoplePopup({
  title,
  summary,
  people,
  left,
  top,
  label,
  onClose,
}: {
  title: string;
  summary: string;
  people?: { id: string; name: string; profession: string | null }[];
  /** The point, in percent of the positioned parent. */
  left: number;
  top: number;
  label: string;
  onClose: () => void;
}) {
  useEffect(() => {
    const close = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', close);
    return () => window.removeEventListener('keydown', close);
  }, [onClose]);
  return (
    <div
      role="dialog"
      aria-label={label}
      className="absolute z-10 w-80 border border-[#151720]/15 bg-white p-4 text-sm shadow-lg max-sm:!static max-sm:mt-3 max-sm:w-full max-sm:!transform-none"
      style={{
        left: `${left}%`,
        top: `${top}%`,
        transform: `translate(${left < 60 ? '14px' : 'calc(-100% - 14px)'}, ${top < 45 ? '-12px' : 'calc(-100% + 12px)'})`,
      }}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0">
          <p className="font-slab text-base font-bold leading-tight text-[#151720]">{title}</p>
          <p className="mt-0.5 tabular-nums text-[#151720]/65">{summary}</p>
        </div>
        <Button
          variant="ghost"
          size="icon"
          className="-mr-2 -mt-2 size-8 shrink-0"
          aria-label="Bezárás"
          title="Bezárás"
          onClick={onClose}
        >
          <X />
        </Button>
      </div>
      {people ? (
        <ul className="mt-3 max-h-56 overflow-y-auto border-t border-[#151720]/10 pt-2 leading-snug text-[#151720]">
          {[...people]
            .sort((a, b) => a.name.localeCompare(b.name, 'hu'))
            .map((person) => (
              <li key={person.id} className="py-0.5">
                <PersonName person={person} />
                {person.profession ? (
                  <span className="text-[#151720]/70"> – {person.profession}</span>
                ) : null}
              </li>
            ))}
        </ul>
      ) : null}
    </div>
  );
}

// A finger needs more room than a mouse pointer: a tap this near a day (in px) still picks it.
const CALENDAR_TOUCH_REACH = 16;

/**
 * Birthdays as a month × day grid; darker means more creators born that day. A click (or tap) on a
 * day opens the box with everyone born on it, or, with `onSelect`, chooses that day instead.
 */
export function BirthdayCalendar({
  calendar,
  people,
  chosen,
  onSelect,
}: {
  calendar: number[][];
  people: Record<string, { id: string; name: string; profession: string | null }[]>;
  /** The day chosen outside the calendar, marked on it. */
  chosen?: { month: number; day: number };
  onSelect?: (month: number, day: number) => void;
}) {
  const [active, setActive] = useState<{ month: number; day: number } | null>(null);
  const [selected, setSelected] = useState<{
    month: number;
    day: number;
    left: number;
    top: number;
  } | null>(null);
  const closeSelected = useCallback(() => setSelected(null), []);
  const frame = useRef<HTMLDivElement>(null);
  const max = Math.max(...calendar.flat(), 1);
  const activeCount = active ? (calendar[active.month - 1][active.day - 1] ?? 0) : 0;

  const pick = (event: MouseEvent<HTMLDivElement>) => {
    let cell = (event.target as Element).closest<HTMLElement>('[data-day]');
    // A tap beside the small cells: the nearest day with a birthday, within a finger's reach.
    // (From the keyboard, event.detail is 0 and the focused cell is the target.)
    if (!cell && event.detail > 0 && window.matchMedia('(pointer: coarse)').matches) {
      let best = CALENDAR_TOUCH_REACH;
      event.currentTarget.querySelectorAll<HTMLElement>('[data-day]').forEach((candidate) => {
        const box = candidate.getBoundingClientRect();
        const distance = Math.hypot(
          event.clientX - (box.left + box.width / 2),
          event.clientY - (box.top + box.height / 2)
        );
        if (distance < best) {
          best = distance;
          cell = candidate;
        }
      });
    }
    const outer = frame.current?.getBoundingClientRect();
    if (!cell || !outer) {
      setSelected(null);
      return;
    }
    const [month, day] = (cell.dataset.day ?? '').split('-').map(Number);
    if (onSelect) {
      onSelect(month, day);
      // Side by side, the list beside the calendar shows the day; on a phone it is above, out of
      // sight, so the box opens here too.
      if (window.matchMedia('(min-width: 1024px)').matches) return;
    }
    const box = cell.getBoundingClientRect();
    setSelected({
      month,
      day,
      left: ((box.left + box.width / 2 - outer.left) / outer.width) * 100,
      top: ((box.top + box.height / 2 - outer.top) / outer.height) * 100,
    });
  };

  return (
    <div ref={frame} className="relative">
      <Readout>
        {active
          ? `${MONTH_NAMES[active.month - 1]} ${active.day}.: ${
              activeCount ? `${formatNumber(activeCount)} alkotó` : 'nincs születésnap'
            }`
          : onSelect
            ? 'Kattintson egy napra, és megnézzük, ki született aznap'
            : 'Kattintson egy napra'}
      </Readout>
      <div className="overflow-x-auto">
        <div
          className="grid min-w-[560px] gap-[2px]"
          style={{ gridTemplateColumns: '5.5rem repeat(31, minmax(0, 1fr))' }}
          onMouseLeave={() => setActive(null)}
          onClick={pick}
        >
          {calendar.map((days, monthIndex) => (
            <div key={MONTH_NAMES[monthIndex]} className="contents">
              <span className="truncate pr-2 text-[11px] leading-[14px] text-[#151720]/70">
                {MONTH_NAMES[monthIndex]}
              </span>
              {days.map((value, dayIndex) => {
                const month = monthIndex + 1;
                const day = dayIndex + 1;
                const exists = dayIndex < DAYS_IN_MONTH[monthIndex];
                const isActive =
                  (active?.month === month && active.day === day) ||
                  (selected?.month === month && selected.day === day) ||
                  (chosen?.month === month && chosen.day === day);
                const className = cn('h-[14px] rounded-[2px]', isActive && 'ring-2 ring-[#151720]');
                const onMouseEnter = exists ? () => setActive({ month, day }) : undefined;
                const background = !exists
                  ? 'transparent'
                  : value
                    ? ramp(0.2 + (value / max) * 0.8)
                    : TRACK;
                return exists && value ? (
                  <button
                    key={dayIndex}
                    type="button"
                    data-day={`${month}-${day}`}
                    aria-label={`${MONTH_NAMES[monthIndex]} ${day}.: ${formatNumber(value)} alkotó`}
                    onMouseEnter={onMouseEnter}
                    className={cn(
                      className,
                      'cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-[#151720]'
                    )}
                    style={{ background }}
                  />
                ) : (
                  <span
                    key={dayIndex}
                    onMouseEnter={onMouseEnter}
                    className={className}
                    style={{ background }}
                  />
                );
              })}
            </div>
          ))}
        </div>
      </div>
      {selected ? (
        <PeoplePopup
          title={`${MONTH_NAMES[selected.month - 1]} ${selected.day}.`}
          summary={`${formatNumber(calendar[selected.month - 1][selected.day - 1] ?? 0)} alkotó született ezen a napon`}
          people={people[`${selected.month}-${selected.day}`] ?? []}
          left={selected.left}
          top={selected.top}
          label={`${MONTH_NAMES[selected.month - 1]} ${selected.day}.: itt született alkotók`}
          onClose={closeSelected}
        />
      ) : null}
    </div>
  );
}

/** A label in one line, or in two at its last space that keeps the first line within `max`. */
function splitLabel(text: string, max: number) {
  if (text.length <= max) return [text];
  const cut = text.lastIndexOf(' ', max);
  return cut > 0 ? [text.slice(0, cut), text.slice(cut + 1)] : [text];
}

/**
 * Age at creation per branch: one filled curve per row, each scaled to its own peak. The curves stay
 * inside their rows (no overlap), the axis has its own band, and the curve passes through the data,
 * so the peak dot sits on its top.
 */
export function AgeRidges({
  bins,
  rows,
}: {
  bins: number[];
  rows: { branch: string; counts: number[]; total: number; peak: number }[];
}) {
  const svg = useRef<SVGSVGElement>(null);
  // Compact: the branch names stand above their ridges, which take the whole width.
  const compactWidth = useCompactWidth(svg);
  const compact = compactWidth !== null;
  const width = compactWidth ?? 640;
  const rowHeight = compact ? 56 : 44;
  const amplitude = compact ? 30 : 36;
  const top = 4;
  const left = compact ? 6 : 170;
  const x = scaleLinear()
    .domain([bins[0], bins[bins.length - 1] + 5])
    .range([left, width - 10]);
  const lastBaseline = top + rows.length * rowHeight;
  const height = lastBaseline + 30;
  const ticks = [20, 30, 40, 50, 60, 70, 80, 90];
  return (
    <svg
      ref={svg}
      viewBox={`0 0 ${width} ${height}`}
      className="h-auto w-full"
      role="img"
      aria-label={`Életkor az alkotás évében, művészeti áganként: ${rows.map((row) => `${row.branch} ${row.peak}–${row.peak + 4} év`).join(', ')}`}
    >
      {ticks.map((age) => (
        <line
          key={age}
          x1={x(age)}
          x2={x(age)}
          y1={top}
          y2={lastBaseline}
          stroke={INK}
          strokeOpacity={0.07}
        />
      ))}
      {rows.map((row, index) => {
        const baseline = top + (index + 1) * rowHeight;
        const max = Math.max(...row.counts, 1);
        const shape = area<number>()
          .x((_, bin) => x(bins[bin] + 2.5))
          .y0(baseline)
          .y1((value) => baseline - (value / max) * amplitude)
          .curve(curveMonotoneX);
        // Beside the ridge, a long name goes on two lines, ending on the row's baseline.
        const label = splitLabel(row.branch, 22);
        return (
          <g key={row.branch}>
            <line
              x1={left}
              x2={width - 10}
              y1={baseline}
              y2={baseline}
              stroke={INK}
              strokeOpacity={0.15}
            />
            <path d={shape(row.counts) ?? ''} fill={SLATE} fillOpacity={0.85} />
            <circle
              cx={x(row.peak + 2.5)}
              cy={baseline - amplitude}
              r={4}
              fill={ACCENT}
              stroke="white"
              strokeWidth={1.5}
            >
              <title>{`${row.branch}: a legtöbb alkotás ${row.peak}–${row.peak + 4} évesen`}</title>
            </circle>
            {compact ? (
              <text x={0} y={baseline - rowHeight + 14} fontSize={12} fill={INK}>
                {row.branch}
              </text>
            ) : (
              <text x={0} y={baseline - 6} fontSize={12} fill={INK}>
                {label.map((line, lineIndex) => (
                  <tspan
                    key={line}
                    x={0}
                    dy={lineIndex ? '1.2em' : `${-1.2 * (label.length - 1)}em`}
                  >
                    {line}
                  </tspan>
                ))}
              </text>
            )}
          </g>
        );
      })}
      <line
        x1={left}
        x2={width - 10}
        y1={lastBaseline}
        y2={lastBaseline}
        stroke={INK}
        strokeOpacity={0.35}
      />
      {ticks.map((age) => (
        <text
          key={age}
          x={x(age)}
          y={lastBaseline + 18}
          fontSize={11}
          fill={INK}
          fillOpacity={0.55}
          textAnchor="middle"
        >
          {age}
        </text>
      ))}
      <text
        x={width - 10}
        y={lastBaseline + 18}
        fontSize={11}
        fill={INK}
        fillOpacity={0.55}
        textAnchor="end"
      >
        év
      </text>
    </svg>
  );
}

type PairPerson = {
  id: string;
  name: string;
  branch: string;
  profession?: string | null;
  imageId: number | null;
};

// The pairs come from the life events, so a name opens the creator's life events, where the
// school and its years can be checked.
function PairPersonLink({ person }: { person: PairPerson }) {
  return (
    <Link
      href={{ pathname: '/alkoto/[id]/eletut-esemenyek', params: { id: person.id } }}
      className="flex min-w-0 items-center gap-2"
    >
      {person.imageId ? (
        <img
          src={buildMediaUrl(person.imageId, 'w256')}
          alt=""
          loading="lazy"
          className="h-10 w-10 shrink-0 rounded-full object-cover grayscale"
        />
      ) : (
        <span className="h-10 w-10 shrink-0 rounded-full bg-[#151720]/10" />
      )}
      <span className="min-w-0">
        <span className="block truncate text-sm font-semibold text-[#151720]">{person.name}</span>
        <span className="line-clamp-2 text-[11px] leading-snug text-[#151720]/55">
          {person.profession || person.branch}
        </span>
      </span>
    </Link>
  );
}

/** Two creators from different branches who studied at the same place at the same time. */
export function PairCards({
  pairs,
  sample,
  total = pairs.length,
}: {
  pairs: (
    | { institution: string; from: number; to: number; a: PairPerson; b: PairPerson }
    | { caption: string; a: PairPerson; b: PairPerson }
  )[];
  /** Shows this many at random, with a button for another draw (as the mentor pairs do). */
  sample?: number;
  /** How many pairs there are in all, when `pairs` is only a part of them. */
  total?: number;
}) {
  const [picked, redraw] = useRandomSample(pairs, sample ?? pairs.length);
  const list = (
    <ul className="grid gap-3 sm:grid-cols-2">
      {(sample ? picked : pairs).map((pair) => (
        <li key={`${pair.a.id}-${pair.b.id}`} className="border border-[#151720]/10 p-3">
          <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[#151720]/50">
            {'caption' in pair ? pair.caption : `${pair.institution} · ${pair.from}–${pair.to}`}
          </div>
          <div className="mt-2 flex flex-col gap-2">
            <PairPersonLink person={pair.a} />
            <PairPersonLink person={pair.b} />
          </div>
        </li>
      ))}
    </ul>
  );
  if (!sample) return list;
  return (
    <div>
      {list}
      <div className="mt-4 flex flex-wrap items-center gap-4">
        <Button onClick={redraw}>Mutasson másokat</Button>
        <Text variant="meta" tone="muted" className="tabular-nums">
          Véletlenszerű válogatás a {formatNumber(total)} párból
        </Text>
      </div>
    </div>
  );
}

/* ---- Database charts ---- */

/** Every work as a rectangle drawn from one shared corner, with a person for scale. */
export function SizeCollage({
  medianWidth,
  medianHeight,
}: {
  medianWidth: number | null;
  medianHeight: number | null;
}) {
  const svg = useRef<SVGSVGElement>(null);
  const drawnWidth = useElementWidth(svg);
  const size = 420;
  // The labels keep their size when the collage is drawn smaller than its 420 units.
  const grow = drawnWidth ? Math.max(1, size / drawnWidth) : 1;
  const maxCm = 300;
  const scale = (cm: number) => (Math.min(cm, maxCm) / maxCm) * (size - 30);
  const origin = { x: 26, y: size - 4 };
  return (
    <div className="relative mx-auto w-full max-w-[460px]">
      {/* The frames, as one image (src/app/[locale]/felfedezes/_scripts/generate-size-collage.mjs, on this same scale). */}
      <img
        src="/assets/images/felfedezes-meretek.webp"
        alt=""
        loading="lazy"
        className="absolute inset-0 h-full w-full"
      />
      <svg
        ref={svg}
        viewBox={`0 0 ${size} ${size}`}
        className="relative block h-auto w-full"
        role="img"
        aria-label="A művek mérete, közös sarokból rajzolva"
      >
        {medianWidth && medianHeight ? (
          <rect
            x={origin.x}
            y={origin.y - scale(medianHeight)}
            width={scale(medianWidth)}
            height={scale(medianHeight)}
            fill="none"
            stroke={ACCENT}
            strokeWidth={3}
          />
        ) : null}
        <line
          x1={12}
          x2={12}
          y1={origin.y}
          y2={origin.y - scale(170)}
          stroke={INK}
          strokeWidth={2}
        />
        <circle cx={12} cy={origin.y - scale(170) - 6} r={5} fill={INK} />
        <text x={20} y={origin.y - scale(170) - 2} fontSize={11 * grow} fill={INK}>
          170 cm
        </text>
        {[100, 200, 300].map((cm) => (
          <text
            key={cm}
            x={origin.x + scale(cm)}
            y={origin.y - 6}
            fontSize={10 * grow}
            fill={INK}
            fillOpacity={0.5}
            textAnchor="end"
          >
            {cm} cm
          </text>
        ))}
      </svg>
    </div>
  );
}

/** Built against only planned, as two-part horizontal bars. */
export function BuiltPlanned({
  rows,
}: {
  rows: { label: string; built: number; planned: number }[];
}) {
  const max = Math.max(...rows.map((row) => row.built + row.planned), 1);
  return (
    <div>
      <ul className="mb-3 flex gap-4 text-xs text-[#151720]/70">
        <li className="flex items-center gap-1.5">
          <span className="h-2.5 w-2.5 rounded-sm" style={{ background: SLATE }} />
          megépült
        </li>
        <li className="flex items-center gap-1.5">
          <span className="h-2.5 w-2.5 rounded-sm" style={{ background: ACCENT }} />
          terv maradt
        </li>
      </ul>
      <ul className="flex flex-col gap-1.5">
        {rows.map((row) => {
          const total = row.built + row.planned;
          return (
            <li
              key={row.label}
              className="grid grid-cols-[minmax(0,9rem)_minmax(0,1fr)_auto] items-center gap-3 text-sm"
              title={`${row.label}: ${row.built} megépült, ${row.planned} terv`}
            >
              <span className="truncate text-[#151720]/80">{row.label}</span>
              <span className="flex h-3 gap-[2px]" style={{ width: `${(total / max) * 100}%` }}>
                <span className="h-full rounded-l" style={{ flex: row.built, background: SLATE }} />
                <span
                  className="h-full rounded-r"
                  style={{ flex: row.planned, background: ACCENT }}
                />
              </span>
              <span className="w-12 text-right text-xs tabular-nums text-[#151720]/60">
                {formatPercent(row.built / Math.max(1, total))}
              </span>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

/** Colour words in titles: each bar is painted in its own colour. */
export function ColourBars({
  items,
}: {
  items: { label: string; colour: string; value: number }[];
}) {
  const max = Math.max(...items.map((item) => item.value), 1);
  return (
    <ul className="flex flex-col gap-1.5">
      {items.map((item) => (
        <li
          key={item.label}
          className="grid grid-cols-[minmax(0,6rem)_minmax(0,1fr)_auto] items-center gap-3 text-sm"
        >
          <span className="truncate text-[#151720]/80">{item.label}</span>
          <span className="h-4">
            <span
              className="block h-full rounded-r border border-[#151720]/15"
              style={{ width: `${(item.value / max) * 100}%`, background: item.colour }}
            />
          </span>
          <span className="w-12 text-right font-semibold tabular-nums text-[#151720]">
            {formatNumber(item.value)}
          </span>
        </li>
      ))}
    </ul>
  );
}

const capitalizeFirst = (text: string) => `${text[0]?.toUpperCase() ?? ''}${text.slice(1)}`;

/**
 * Weekday × hour grid of program starts. The decade heatmap names its columns as decades,
 * so the week gets its own small grid in the same colours.
 */
export function WeekHourGrid({
  hours,
  rows,
}: {
  hours: number[];
  rows: { label: string; counts: number[] }[];
}) {
  const [active, setActive] = useState<{ row: number; column: number } | null>(null);
  const max = Math.max(1, ...rows.flatMap((row) => row.counts));
  return (
    <div>
      <Readout>
        {active
          ? `${capitalizeFirst(rows[active.row].label)}, ${hours[active.column]} óra: ${formatNumber(rows[active.row].counts[active.column])} program`
          : 'Sötétebb: több program kezdődik ekkor'}
      </Readout>
      <div className="overflow-x-auto">
        <div
          className="grid min-w-[520px] gap-[2px]"
          style={{ gridTemplateColumns: `5.5rem repeat(${hours.length}, minmax(0, 1fr))` }}
          onMouseLeave={() => setActive(null)}
        >
          <span />
          {hours.map((hour) => (
            <span key={hour} className="pb-1 text-center text-[11px] text-[#151720]/55">
              {hour}
            </span>
          ))}
          {rows.map((row, rowIndex) => (
            <div key={row.label} className="contents">
              <span className="truncate pr-2 text-xs leading-7 text-[#151720]/80">{row.label}</span>
              {row.counts.map((value, column) => (
                <span
                  key={hours[column]}
                  className="h-7"
                  style={{
                    background: value ? ramp(value / max) : TRACK,
                    outline:
                      active?.row === rowIndex && active.column === column
                        ? `2px solid ${ACCENT}`
                        : undefined,
                  }}
                  onMouseEnter={() => setActive({ row: rowIndex, column })}
                />
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/** The project's creator cards, with a count under each one. */
export function CreatorCountCards({
  people,
  unit,
  columns = 6,
  compact = false,
  pathname,
}: {
  people: {
    id: string;
    name: string;
    profession: string | null;
    image: number | null;
    died: string | null;
    value?: number;
  }[];
  /** The count under each card; without it, the cards alone. */
  unit?: string;
  /** Cards in a row on wide screens. */
  columns?: 4 | 5 | 6 | 10;
  /** Smaller portraits for longer lists. */
  compact?: boolean;
  /** Where a card leads; the creator's main page by default. */
  pathname?: '/alkoto/[id]' | '/alkoto/[id]/eletut-esemenyek';
}) {
  return (
    <ul
      className={cn(
        'grid gap-2',
        compact && 'gap-y-5',
        compact && columns !== 10 && 'max-w-4xl',
        columns === 10
          ? 'grid-cols-2 sm:grid-cols-5 lg:grid-cols-10'
          : columns === 4
            ? 'grid-cols-2 sm:grid-cols-3 lg:grid-cols-4'
            : columns === 5
              ? 'grid-cols-3 sm:grid-cols-5 max-sm:[&>li:nth-child(n+10)]:hidden'
              : compact
                ? 'grid-cols-3 sm:grid-cols-4 lg:grid-cols-6'
                : 'grid-cols-3 sm:grid-cols-4 xl:grid-cols-6'
      )}
    >
      {people.map((person) => (
        <li key={person.id} className="flex min-w-0 flex-col gap-1">
          <CreatorCard
            className={compact ? 'mx-auto max-w-[9rem]' : undefined}
            pathname={pathname}
            creator={{
              alkotoAzonosito: person.id,
              nev: person.name,
              szakma: person.profession,
              elhalalozasIdeje: person.died,
              profilkep: person.image ? { id: person.image } : null,
            }}
          />
          {unit && person.value !== undefined ? (
            <span className="text-center text-xs font-semibold tabular-nums text-[#151720]/70">
              {formatNumber(person.value)} {unit}
            </span>
          ) : null}
        </li>
      ))}
    </ul>
  );
}

// The neutral part of a picture (grey, beige, black) in the colour strips.
