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

import { type ReactNode, useEffect, useMemo, useRef, useState } from 'react';

import { geoMercator } from 'd3';
import { motion } from 'framer-motion';
import { Minus, Plus } from 'lucide-react';
import { Range, getTrackBackground } from 'react-range';

import { useSectionTone } from '@/components/common/Section';
import CreationVideoCard from '@/components/creations/CreationVideoCard';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Text } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
import { buildMediaUrl } from '@/utils/images';

import type { CreationListItem } from '@/types/Creation';

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

import {
  BirthdayCalendar,
  CITIES,
  SERIES,
  formatNumber,
  formatPercent,
  useCompactWidth,
  useElementWidth,
  useRandomSample,
} from './charts';
import { MONTHS, capitalize, dayWithSuffix, yearIn } from './hungarian';
import { type Picture, Pictures, PlayPanel, StoryBlock, useInView } from './story';
import type { Ranked } from './types';

const INK = '#151720';
const ACCENT = '#dfcf6f';
// The bar colour of every other chart on the page (charts.tsx SLATE).
const SLATE = '#3b3f58';
const FADED = '#d8d5cc';
// The decades' branch step: the reference categorical palette's eight hues (charts.tsx SERIES and
// slots 6–8, in this order), then ink for the ninth branch (művészetelmélet) and grey for what is
// left (fotóművészet): more hues would not stay apart.
const BRANCH_COLOURS = [...SERIES, '#008300', '#6250d6', '#e34948', INK];
const OTHER = '#a9acb8';

/**
 * Each branch's share within every decade column, per creator: the branch's creations of the
 * decade divided by its number of creators, then as a share of the column. Branches with many
 * creators don't fill the columns just by their size.
 */
export function perCreatorShares(
  rows: { branch: string; counts: number[] }[],
  creators: { label: string; value: number }[]
) {
  const rates = rows.map((row) => {
    const people = creators.find((entry) => entry.label === row.branch)?.value || 1;
    return row.counts.map((count) => count / people);
  });
  return rows.map((_, index) =>
    rates[index].map((rate, column) => {
      const total = rates.reduce((sum, branch) => sum + branch[column], 0);
      return total ? rate / total : 0;
    })
  );
}
// Every mark changes its colour and opacity smoothly between the scroll steps.
const EASE = { transition: 'fill 500ms ease, opacity 500ms ease' };

/** The year that splits the decades in the "Idő és tér" question and story. */
export const SPLIT_YEAR = 1990;

type DecadeRow = { branch: string; counts: number[] };

/**
 * The layers of the decades' branch step: the branches by their number of creations, largest at
 * the bottom, with their per-creator shares; past the palette's hues, the smallest together in grey
 * on top.
 */
export function branchLayers(
  decades: number[],
  rows: DecadeRow[],
  creators: { label: string; value: number }[]
) {
  const shares = perCreatorShares(rows, creators);
  const order = rows
    .map((row, index) => ({ row, index, total: row.counts.reduce((sum, value) => sum + value, 0) }))
    .sort((a, b) => b.total - a.total);
  const coloured = Math.min(order.length, BRANCH_COLOURS.length);
  const rest = order.slice(coloured);
  return [
    ...order.slice(0, coloured).map(({ row, index }, rank) => ({
      label: row.branch,
      colour: BRANCH_COLOURS[rank],
      shares: shares[index],
    })),
    ...(rest.length
      ? [
          {
            label: rest
              .map(({ row }, rank) => (rank ? row.branch.toLowerCase() : row.branch))
              .join(', ')
              .replace(/, ([^,]*)$/, ' és $1'),
            colour: OTHER,
            shares: decades.map((_, column) =>
              rest.reduce((sum, { index }) => sum + shares[index][column], 0)
            ),
          },
        ]
      : []),
  ];
}

/** The legend of the decades' branch step, as text: on a phone, beside the step's words. */
export function BranchLegend({
  decades,
  rows,
  creators,
  className,
}: {
  decades: number[];
  rows: DecadeRow[];
  creators: { label: string; value: number }[];
  className?: string;
}) {
  return (
    <ul className={cn('grid grid-cols-2 gap-x-3 gap-y-1 text-xs text-[#151720]', className)}>
      {branchLayers(decades, rows, creators).map((layer) => (
        <li key={layer.label} className="flex items-center gap-1.5">
          <span className="size-2.5 shrink-0" style={{ background: layer.colour }} />
          {layer.label}
        </li>
      ))}
    </ul>
  );
}

/**
 * The decades, told in five steps: all creations, before and after SPLIT_YEAR, the columns split
 * into the branches per creator (see perCreatorShares; the column keeps its height), then every
 * branch on its own scale with its own peak. "openEnded": the last column runs from its decade to today; only
 * its axis label says so ("2010–", left open). Branch peaks include this combined period.
 */
export function DecadeStory({
  decades,
  rows,
  active,
  creators,
  openEnded = false,
}: {
  decades: number[];
  rows: { branch: string; counts: number[] }[];
  active: number;
  /** Creators per branch, for the per-creator shares of the branch step. */
  creators: { label: string; value: number }[];
  openEnded?: boolean;
}) {
  const svg = useRef<SVGSVGElement>(null);
  // Compact: drawn at its real size; in the branch rows each name stands above its bars.
  const compactWidth = useCompactWidth(svg);
  const compact = compactWidth !== null;
  const width = compactWidth ?? 640;
  const height = compact ? 340 : 400;
  const left = 8;
  // Room under the columns for the two-line period labels.
  const bottom = height - 40;
  const totals = decades.map((_, column) => rows.reduce((sum, row) => sum + row.counts[column], 0));
  const max = Math.max(...totals, 1);
  const all = totals.reduce((sum, value) => sum + value, 0) || 1;
  const after = totals.reduce(
    (sum, value, column) => sum + (decades[column] >= SPLIT_YEAR ? value : 0),
    0
  );
  const full = openEnded ? decades.length - 1 : decades.length;
  const open = (column: number) => column >= full;
  const step = (width - left) / decades.length;
  // "1920–" over "1930"; the open column only "2010–", its end left open.
  const tick = (column: number, x: number) => (
    <>
      <tspan x={x}>{decades[column]}–</tspan>
      <tspan x={x} dy="1.15em">
        {open(column) ? '' : decades[column] + 10}
      </tspan>
    </>
  );
  const columnFill = (column: number) => {
    if (active === 1) return decades[column] < SPLIT_YEAR ? INK : FADED;
    if (active === 2) return decades[column] >= SPLIT_YEAR ? INK : FADED;
    return INK;
  };
  const firstAfter = decades.findIndex((decade) => decade >= SPLIT_YEAR);
  const notes = [
    {
      step: 1,
      x: left + (firstAfter * step) / 2,
      text: `${SPLIT_YEAR} előtt: ${formatPercent(1 - after / all)}`,
    },
    {
      step: 2,
      x: left + firstAfter * step + ((decades.length - firstAfter) * step) / 2,
      text: `${SPLIT_YEAR} után: ${formatPercent(after / all)}`,
    },
  ];
  const rowHeight = (height - 36) / rows.length;
  // Where the branch rows' bars start: after the names, or (compact) at the left edge.
  const barsLeft = compact ? 0 : 200;
  const columnWidth = (width - barsLeft) / decades.length;
  const layers = branchLayers(decades, rows, creators);
  const scale = (value: number) => (value / max) * (bottom - 60);
  return (
    <svg
      ref={svg}
      viewBox={`0 0 ${width} ${height}`}
      className="h-auto max-h-[46vh] w-full lg:max-h-none"
      role="img"
      aria-label={
        openEnded
          ? `Az alkotások évtizedenként; az utolsó oszlop ${decades.at(-1)}-től máig`
          : 'Az alkotások évtizedenként'
      }
    >
      <g style={{ ...EASE, opacity: active < 4 ? 1 : 0 }}>
        {totals.map((total, column) => {
          // One bar in the first steps, built from the branch layers; they take their colours in the
          // branches step. The bar keeps its height: the layers split it by the per-creator shares.
          let below = 0;
          return (
            <g key={decades[column]}>
              {layers.map((layer) => {
                const y = bottom - scale(total * (below + layer.shares[column]));
                const layerHeight = scale(total * layer.shares[column]);
                below += layer.shares[column];
                return (
                  <rect
                    key={layer.label}
                    x={left + column * step + 3}
                    y={y}
                    width={step - 6}
                    height={layerHeight}
                    shapeRendering="crispEdges"
                    style={{ ...EASE, fill: active === 3 ? layer.colour : columnFill(column) }}
                  />
                );
              })}
              <text
                y={height - 24}
                fontSize={compact ? 10.5 : 12}
                className={compact ? undefined : 'max-sm:text-[17px]'}
                fill={INK}
                fillOpacity={0.6}
                textAnchor="middle"
              >
                {tick(column, left + column * step + step / 2)}
              </text>
            </g>
          );
        })}
        {notes.map((note) => (
          <text
            key={note.step}
            x={note.x}
            y={compact ? 24 : 32}
            fontSize={compact ? 16 : 22}
            fontWeight={700}
            textAnchor="middle"
            fill={INK}
            stroke="white"
            strokeWidth={4}
            paintOrder="stroke"
            style={{ ...EASE, opacity: active === note.step ? 1 : 0 }}
          >
            {note.text}
          </text>
        ))}
        {/* The legend of the branches step, over the low early columns; on a phone it is in the
            step text instead (BranchLegend). */}
        <g className="max-sm:hidden" style={{ ...EASE, opacity: active === 3 ? 1 : 0 }}>
          {layers.map((layer, index) => (
            <g
              key={layer.label}
              transform={`translate(${left + (index % 2) * 250} ${12 + Math.floor(index / 2) * 20})`}
            >
              <rect width={12} height={12} fill={layer.colour} />
              <text x={18} y={11} fontSize={13} fill={INK}>
                {layer.label}
              </text>
            </g>
          ))}
        </g>
      </g>
      <g style={{ ...EASE, opacity: active >= 4 ? 1 : 0 }}>
        {rows.map((row, index) => {
          const rowMax = Math.max(...row.counts, 1);
          const top = index * rowHeight;
          const branchPeak = row.counts.indexOf(Math.max(...row.counts));
          return (
            <g key={row.branch}>
              {compact ? (
                <text x={0} y={top + 10} fontSize={11} fill={INK}>
                  {row.branch}
                </text>
              ) : (
                <text x={0} y={top + rowHeight - 8} fontSize={12} fill={INK}>
                  {row.branch.length > 26 ? `${row.branch.slice(0, 25)}…` : row.branch}
                </text>
              )}
              {row.counts.map((count, column) => {
                const barHeight = (count / rowMax) * (rowHeight - (compact ? 16 : 8));
                return (
                  <rect
                    key={decades[column]}
                    x={barsLeft + column * columnWidth + 1}
                    y={top + rowHeight - 4 - barHeight}
                    width={columnWidth - 2}
                    height={barHeight}
                    fill={column === branchPeak ? ACCENT : INK}
                    fillOpacity={column === branchPeak ? 1 : 0.55}
                  />
                );
              })}
            </g>
          );
        })}
        {decades.map((decade, column) => (
          <text
            key={decade}
            y={height - 18}
            fontSize={10}
            className={compact ? undefined : 'max-sm:text-[13px]'}
            fill={INK}
            fillOpacity={0.6}
            textAnchor="middle"
          >
            {tick(column, barsLeft + column * columnWidth + columnWidth / 2)}
          </text>
        ))}
      </g>
    </svg>
  );
}

/**
 * The road to the Kossuth Prize as a staircase: every earlier award one step, as many years
 * before the prize as its laureates' median. A moving window keeps at most five steps visible.
 */
export function KossuthStairs({
  items,
  active,
}: {
  items: { label: string; value: number; years: number }[];
  active: number;
}) {
  const svg = useRef<SVGSVGElement>(null);
  // Compact: each label on its own line above its row.
  const compactWidth = useCompactWidth(svg);
  const compact = compactWidth !== null;
  const width = compactWidth ?? 640;
  const layout = compact
    ? {
        rowHeight: 66,
        label: 14,
        detail: 30,
        line: 48,
        top: 4,
        axis: 40,
        edge: 6,
        right: width - 64,
      }
    : {
        rowHeight: 84,
        label: 34,
        detail: 52,
        line: 76,
        top: 10,
        axis: 60,
        edge: 12,
        right: width - 90,
      };
  const visibleRows = 5;
  const height = Math.min(items.length, visibleRows) * layout.rowHeight + layout.axis;
  const revealedCount = Math.min(items.length, Math.max(0, active));
  const windowStart = Math.max(0, revealedCount - visibleRows);
  const windowItems = items.slice(windowStart, windowStart + visibleRows);
  const { right, edge } = layout;
  const maxYears = Math.max(...items.map((item) => item.years), 1);
  const x = (years: number) => edge + (1 - years / maxYears) * (right - edge);
  const maxValue = Math.max(...items.map((item) => item.value), 1);
  return (
    <svg
      ref={svg}
      viewBox={`0 0 ${width} ${height}`}
      className={cn(
        'h-auto w-full',
        !compact && 'max-h-[46vh] lg:max-h-[calc(100vh-var(--header-h)-2rem)]'
      )}
      role="img"
      aria-label={`Az út a Kossuth-díjig: ${items.length} elismerés, egyszerre legfeljebb öt látható`}
    >
      <line
        x1={right}
        x2={right}
        y1={layout.top}
        y2={height - 34}
        stroke={ACCENT}
        strokeWidth={4}
      />
      <text
        x={right + 10}
        y={layout.top + 16}
        fontSize={compact ? 12 : 14}
        fontWeight={700}
        fill={INK}
      >
        Kossuth-
      </text>
      <text
        x={right + 10}
        y={layout.top + 34}
        fontSize={compact ? 12 : 14}
        fontWeight={700}
        fill={INK}
      >
        díj
      </text>
      {windowItems.map((item, index) => {
        const itemIndex = windowStart + index;
        const shown = itemIndex < revealedCount;
        const current = itemIndex === active - 1 || active > items.length;
        const labelX = compact
          ? 0
          : Math.min(x(item.years), right - Math.max(300, item.label.length * 8));
        return (
          <g
            key={item.label}
            aria-hidden={!shown}
            style={{
              opacity: shown ? 1 : 0,
              transform: `translateY(${index * layout.rowHeight}px)`,
              transition: 'transform 500ms ease, opacity 500ms ease',
            }}
          >
            <line
              x1={x(item.years)}
              x2={right}
              y1={layout.line}
              y2={layout.line}
              stroke={INK}
              strokeOpacity={current ? 0.6 : 0.2}
              strokeWidth={2}
              strokeDasharray="4 4"
            />
            <circle
              cx={x(item.years)}
              cy={layout.line}
              r={(compact ? 4 : 5) + (item.value / maxValue) * (compact ? 5 : 7)}
              style={{ ...EASE, fill: current ? INK : FADED }}
            />
            <text
              x={labelX}
              y={layout.label}
              fontSize={compact ? 13 : 14}
              fontWeight={current ? 700 : 400}
              fill={INK}
            >
              {item.label}
            </text>
            <text
              x={labelX}
              y={layout.detail}
              fontSize={compact ? 11.5 : 12}
              fill={INK}
              fillOpacity={0.6}
            >
              {`${formatNumber(item.years)} évvel előtte · ${formatNumber(item.value)} díjazott`}
            </text>
          </g>
        );
      })}
      {[maxYears, Math.round(maxYears / 2), 0].map((years) => (
        <text
          key={years}
          x={x(years)}
          y={height - 12}
          fontSize={11}
          fill={INK}
          fillOpacity={0.55}
          textAnchor={years === maxYears ? 'start' : years ? 'middle' : 'end'}
        >
          {years ? `${formatNumber(years)} évvel előtte` : 'a díj éve'}
        </text>
      ))}
    </svg>
  );
}

/** Three of a branch's pictures, drawn in the browser from the day's list. */
function BranchPictures({ pictures }: { pictures: Picture[] }) {
  const [picked] = useRandomSample(pictures, 3);
  return (
    <ul className="flex gap-1">
      {picked.map((picture) => (
        <li key={picture.id}>
          <Link
            href={{ pathname: '/alkotas/[id]', params: { id: picture.id } }}
            title={`${picture.title}${picture.creator ? ` – ${picture.creator}` : ''}`}
            className="block"
          >
            <img
              src={buildMediaUrl(picture.image, 'w256')}
              alt={picture.title}
              loading="lazy"
              className="size-10 object-cover transition-opacity hover:opacity-80 sm:size-11"
            />
          </Link>
        </li>
      ))}
    </ul>
  );
}

/** One row per branch: its count (and its creators), a bar, and three of its creations. */
export function BranchStrips({
  branches,
  creators = [],
  pictures,
}: {
  branches: Ranked[];
  creators?: Ranked[];
  pictures: Record<string, Picture[]>;
}) {
  const creatorCount = new Map(creators.map((item) => [item.label, item.value]));
  const max = Math.max(...branches.map((branch) => branch.value), 1);
  return (
    <ul className="flex flex-col divide-y divide-[#151720]/10">
      {branches.map((branch, index) => (
        <li
          key={branch.label}
          className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-1 py-1.5 sm:grid-cols-[14rem_minmax(0,1fr)_auto]"
        >
          <div className="min-w-0">
            <Text variant="label" className="leading-tight">
              {branch.label}
            </Text>
            <Text variant="caption" tone="muted" className="tabular-nums">
              {formatNumber(branch.value)} alkotás
              {creatorCount.has(branch.label)
                ? ` ${formatNumber(creatorCount.get(branch.label) ?? 0)} alkotótól`
                : null}
            </Text>
          </div>
          <span className="col-span-2 row-start-2 h-8 bg-[#151720]/[0.07] sm:col-span-1 sm:row-start-auto">
            <span
              className="block h-full"
              style={{
                width: `${(branch.value / max) * 100}%`,
                background: index === 0 ? ACCENT : SLATE,
              }}
            />
          </span>
          {pictures[branch.label]?.length ? (
            <BranchPictures pictures={pictures[branch.label]} />
          ) : null}
        </li>
      ))}
    </ul>
  );
}

const DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

type BirthdayPerson = {
  id: string;
  name: string;
  profession: string | null;
  image: number | null;
  died: string | null;
};

/** The creators born on the chosen day: portraits in a short list, the names leading to them. */
function BirthdayPeople({ people }: { people: BirthdayPerson[] }) {
  return (
    <ul className="max-h-[22rem] space-y-3 overflow-y-auto pr-1">
      {people.map((person) => (
        <li key={person.id}>
          <Link
            href={{ pathname: '/alkoto/[id]', params: { id: person.id } }}
            className="group flex items-center gap-3"
          >
            {person.image ? (
              <img
                src={buildMediaUrl(person.image, 'w256')}
                alt=""
                loading="lazy"
                className="size-12 shrink-0 rounded-full object-cover grayscale"
              />
            ) : (
              <span className="size-12 shrink-0 rounded-full bg-[#151720]/10" />
            )}
            <span className="min-w-0">
              <span className="block font-semibold text-[#151720] group-hover:underline">
                {person.died ? '† ' : ''}
                {person.name}
              </span>
              {person.profession ? (
                <span className="block text-sm text-[#151720]/60">{person.profession}</span>
              ) : null}
            </span>
          </Link>
        </li>
      ))}
    </ul>
  );
}

const NO_BIRTHDAYS: Record<string, BirthdayPerson[]> = {};

/**
 * "Ön kivel született egy napon?": a month and a day with the creators born on it, beside the
 * year's calendar, where a click chooses the day too. The names come with the block: they are
 * needed at the very end of the page, not in its first load. The calendar counts them.
 */
export function BirthdayBlock({ title, lead }: { title: ReactNode; lead?: ReactNode }) {
  const [ref, near] = useInView<HTMLDivElement>('600px');
  const [byDay, setByDay] = useState<Record<string, BirthdayPerson[]> | null>(null);
  const [failed, setFailed] = useState(false);
  const [attempt, setAttempt] = useState(0);
  const [month, setMonth] = useState(1);
  const [day, setDay] = useState(1);
  // Today, once in the browser (the server does not know the reader's date).
  useEffect(() => {
    const today = new Date();
    setMonth(today.getMonth() + 1);
    setDay(today.getDate());
  }, []);
  useEffect(() => {
    if (!near) return;
    setFailed(false);
    const controller = new AbortController();
    (async () => {
      try {
        const response = await fetch('/api/creator-birthdays', {
          signal: controller.signal,
          headers: { 'Accept-Language': 'hu' },
        });
        if (!response.ok) throw new Error(`Creator birthdays: ${response.status}`);
        const body = (await response.json()) as { people: Record<string, BirthdayPerson[]> };
        setByDay(body.people);
      } catch {
        if (!controller.signal.aborted) setFailed(true);
      }
    })();
    return () => controller.abort();
  }, [near, attempt]);
  const calendar = useMemo(
    () =>
      DAYS_IN_MONTH.map((_, month) =>
        Array.from({ length: 31 }, (_, day) => byDay?.[`${month + 1}-${day + 1}`]?.length ?? 0)
      ),
    [byDay]
  );
  const people = byDay?.[`${month}-${day}`] ?? [];

  const controls = (
    <>
      <div className="flex flex-wrap gap-3">
        <div className="w-44">
          <Select
            value={String(month)}
            onValueChange={(value) => {
              setMonth(Number(value));
              setDay((current) => Math.min(current, DAYS_IN_MONTH[Number(value) - 1]));
            }}
          >
            <SelectTrigger aria-label="Hónap" className="bg-white">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {MONTHS.map((name, index) => (
                <SelectItem key={name} value={String(index + 1)}>
                  {name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="w-28">
          <Select value={String(day)} onValueChange={(value) => setDay(Number(value))}>
            <SelectTrigger aria-label="Nap" className="bg-white">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {Array.from({ length: DAYS_IN_MONTH[month - 1] }, (_, index) => (
                <SelectItem key={index + 1} value={String(index + 1)}>
                  {index + 1}.
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>
      <div aria-live="polite" className="mt-8">
        {failed ? (
          <Text tone="muted">
            Most nem sikerült betölteni a születésnapokat.{' '}
            <Button
              variant="link"
              className="align-baseline"
              onClick={() => setAttempt((value) => value + 1)}
            >
              Újra
            </Button>
          </Text>
        ) : (
          <p className="font-slab text-xl font-bold leading-snug">
            {!byDay
              ? 'Egy pillanat…'
              : people.length
                ? `${capitalize(MONTHS[month - 1])} ${dayWithSuffix(day)} ${people.length === 1 ? 'született' : `${people.length} alkotó született`}:`
                : `${capitalize(MONTHS[month - 1])} ${dayWithSuffix(day)} egyik alkotónk sem született. Próbáljon egy másik napot!`}
          </p>
        )}
        {people.length ? (
          <div className="mt-4">
            <BirthdayPeople people={people} />
          </div>
        ) : null}
      </div>
    </>
  );

  return (
    <div ref={ref}>
      <PlayPanel
        title={title}
        lead={lead}
        controls={controls}
        view={
          <BirthdayCalendar
            calendar={calendar}
            people={byDay ?? NO_BIRTHDAYS}
            chosen={{ month, day }}
            onSelect={(chosenMonth, chosenDay) => {
              setMonth(chosenMonth);
              setDay(chosenDay);
            }}
          />
        }
      />
    </div>
  );
}

const FIRST_BIRTH_YEAR = 1930;
// Quick clicks on the year buttons: only the year they stop at is asked for.
const BIRTH_YEAR_DELAY_MS = 300;

// The year the picker opens on, so the block shows pictures from the start.
const DEFAULT_BIRTH_YEAR = 1970;

/** "Az Ön születési évében": the reader's year, and a few creations made that year. */
export function BornInYourYear({ title, lead }: { title: ReactNode; lead?: ReactNode }) {
  const [ref, near] = useInView<HTMLDivElement>('600px');
  // The year on the slider, and the one asked for: that follows only when the slider is let go.
  const [year, setYear] = useState(DEFAULT_BIRTH_YEAR);
  const [chosenYear, setChosenYear] = useState(DEFAULT_BIRTH_YEAR);
  // The years asked for so far stay here, so going back to one needs no new request.
  const [byYear, setByYear] = useState<Record<number, Picture[]>>({});
  const [failedYear, setFailedYear] = useState<number | null>(null);
  const [attempt, setAttempt] = useState(0);
  const items = byYear[chosenYear];
  // The pictures on screen stay until the next year's arrive, and a year without pictures keeps
  // them too, so the page under the slider never collapses and jumps.
  const [shownYear, setShownYear] = useState<number | null>(null);
  if (items?.length && shownYear !== chosenYear) setShownYear(chosenYear);
  const shownItems = shownYear === null ? null : byYear[shownYear];
  const settled = year === chosenYear && Boolean(items);
  // The tallest the pictures have been at this width holds the height for the shorter years.
  const picturesBox = useRef<HTMLDivElement>(null);
  const boxWidth = useElementWidth(picturesBox);
  const [minHeight, setMinHeight] = useState(0);
  useEffect(() => setMinHeight(0), [boxWidth]);
  useEffect(() => {
    const height = picturesBox.current?.offsetHeight ?? 0;
    setMinHeight((current) => Math.max(current, height));
  }, [shownYear, boxWidth]);
  useEffect(() => {
    if (!near || items) return;
    setFailedYear(null);
    const year = chosenYear;
    const controller = new AbortController();
    const timer = window.setTimeout(async () => {
      try {
        const response = await fetch(`/api/birth-year-creations?year=${year}`, {
          signal: controller.signal,
          headers: { 'Accept-Language': 'hu' },
        });
        if (!response.ok) throw new Error(`Birth year creations: ${response.status}`);
        const { items: pictures } = (await response.json()) as { items: Picture[] };
        setByYear((current) => ({ ...current, [year]: pictures }));
      } catch {
        if (!controller.signal.aborted) setFailedYear(year);
      }
    }, BIRTH_YEAR_DELAY_MS);
    return () => {
      window.clearTimeout(timer);
      controller.abort();
    };
  }, [near, items, chosenYear, attempt]);
  const chooseYear = (value: number) => {
    setYear(value);
    setChosenYear(value);
  };
  const first = FIRST_BIRTH_YEAR;
  const last = new Date().getFullYear();
  const clamp = (value: number) => Math.min(last, Math.max(first, value));
  const ticks = [first, ...[1950, 1970, 1990, 2010].filter((tick) => tick > first + 5), last];
  // The year on top, its pictures under it across the panel.
  return (
    <div ref={ref}>
      <PlayPanel
        layout="stack"
        title={title}
        lead={lead}
        controls={
          <>
            <Text variant="meta" tone="muted">
              Az Ön születési éve
            </Text>
            <div className="mt-3 flex items-center justify-between gap-3">
              <Button
                size="icon"
                variant="quiet"
                aria-label="Egy évvel korábban"
                disabled={year <= first}
                onClick={() => chooseYear(clamp(year - 1))}
              >
                <Minus />
              </Button>
              <span className="font-slab text-5xl font-bold leading-none tabular-nums">{year}</span>
              <Button
                size="icon"
                variant="quiet"
                aria-label="Egy évvel később"
                disabled={year >= last}
                onClick={() => chooseYear(clamp(year + 1))}
              >
                <Plus />
              </Button>
            </div>
            <div className="mt-5 px-2 py-2">
              <Range
                values={[year]}
                min={first}
                max={last}
                step={1}
                onChange={(values) => setYear(values[0])}
                onFinalChange={(values) => setChosenYear(values[0])}
                renderTrack={({ props, children }) => (
                  <div
                    {...props}
                    className="h-1.5 w-full"
                    style={{
                      ...props.style,
                      background: getTrackBackground({
                        values: [year],
                        colors: ['#151720', 'rgba(21,23,32,0.16)'],
                        min: first,
                        max: last,
                      }),
                    }}
                  >
                    {children}
                  </div>
                )}
                renderThumb={({ props }) => {
                  const { key, ...rest } = props;
                  return (
                    <div
                      key={key}
                      {...rest}
                      aria-label="Születési év"
                      className="size-6 rounded-full border-2 border-white bg-mma-yellow shadow focus:outline-none focus-visible:ring-2 focus-visible:ring-mma-blue"
                    />
                  );
                }}
              />
            </div>
            <div className="relative mx-2 h-4" aria-hidden>
              {ticks.map((tick) => (
                <Text
                  key={tick}
                  as="span"
                  variant="caption"
                  tone="muted"
                  className="absolute -translate-x-1/2 tabular-nums"
                  style={{ left: `${((tick - first) / Math.max(1, last - first)) * 100}%` }}
                >
                  {tick}
                </Text>
              ))}
            </div>
            <div aria-live="polite" className="mt-8 min-h-8">
              {failedYear === chosenYear ? (
                <Text tone="muted">
                  Most nem sikerült betölteni az alkotásokat.{' '}
                  <Button
                    variant="link"
                    className="align-baseline"
                    onClick={() => setAttempt((value) => value + 1)}
                  >
                    Újra
                  </Button>
                </Text>
              ) : settled && !items?.length ? (
                <Text tone="muted">
                  Erre az évre ({chosenYear}) még nincs képes alkotás az adatbázisban.
                  {shownYear !== null ? ` Alább: ${shownYear}.` : ''}
                </Text>
              ) : shownYear !== null ? (
                <p className="font-slab text-xl font-bold">
                  {yearIn(shownYear)} készült többek között:
                </p>
              ) : (
                <Text tone="muted">Egy pillanat…</Text>
              )}
            </div>
          </>
        }
        view={
          <>
            {/* Keyed by the year: the pictures of a new year fade in. Dimmed while they are not the
            slider's year yet. */}
            <div
              ref={picturesBox}
              style={{ minHeight }}
              className={cn('transition-opacity duration-200', !settled && 'opacity-50')}
            >
              {shownItems ? (
                <motion.div
                  key={shownYear}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ duration: 0.35 }}
                >
                  {/* Two rows of eight on wide screens, four of four on tablets; on phones three in a row, two rows (six cards). */}
                  <Pictures
                    items={shownItems}
                    className="grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-8 max-sm:[&>li:nth-child(n+7)]:hidden"
                  />
                </motion.div>
              ) : null}
            </div>
          </>
        }
      />
    </div>
  );
}

type Channel = {
  videos: number;
  minutes: number;
  playlists: number;
  series: { id: string; name: string }[];
  recommended: VideoCardData[];
};

/**
 * The YouTube channel at a glance: its size, the creators' series and recommended videos.
 */
export function YouTubeChannel({ channel }: { channel: Channel }) {
  // On a dark part it stands straight on the background, in light text.
  const dark = useSectionTone() === 'dark';
  const muted = dark ? 'inverseMuted' : 'muted';
  // Every series in one list, by the creator's name.
  const series = [...channel.series].sort((a, b) => a.name.localeCompare(b.name, 'hu'));

  return (
    <div>
      <dl
        className={cn(
          'grid grid-cols-3 gap-4 border-b pb-6',
          dark ? 'border-white/15' : 'border-[#151720]/10'
        )}
      >
        {[
          { label: 'videó', value: formatNumber(channel.videos) },
          { label: 'perc', value: formatNumber(channel.minutes) },
          { label: 'lejátszási lista', value: formatNumber(channel.playlists) },
        ].map((item) => (
          <div key={item.label} className="flex flex-col-reverse justify-end">
            <dt
              className={cn(
                'mt-1 text-xs font-semibold uppercase tracking-[0.15em]',
                dark ? 'text-white/60' : 'text-[#151720]/55'
              )}
            >
              {item.label}
            </dt>
            <dd className="font-slab text-3xl font-bold leading-none tabular-nums sm:text-4xl">
              {item.value}
            </dd>
          </div>
        ))}
      </dl>

      <div className="mt-10 grid gap-8 lg:grid-cols-[minmax(0,2fr)_minmax(0,3fr)]">
        <div>
          <Text variant="meta" tone={muted}>
            Sorozatok alkotónként
          </Text>
          <ul className="mt-4 flex flex-wrap gap-1.5">
            {series.map((item) => (
              <li key={item.name}>
                <Badge
                  asChild
                  variant="outline"
                  size="sm"
                  className={cn(dark && 'border-white/30 text-white/80 hover:bg-white/10')}
                >
                  <Link href={{ pathname: '/alkoto/[id]/alkotas-videok', params: { id: item.id } }}>
                    {item.name}
                  </Link>
                </Badge>
              </li>
            ))}
          </ul>
        </div>
        <div>
          <Text variant="meta" tone={muted}>
            Videóajánló
          </Text>
          <VideoCards videos={channel.recommended} className="mt-4 sm:grid-cols-3 lg:grid-cols-3" />
        </div>
      </div>
    </div>
  );
}

const DROP = { width: 800, height: 480 };
// The first part of the scroll (this share of it) only starts the rain: a few dots, then more and
// more, then a steady pace to the end. Smooth at the joint: the slope is the same on both sides.
const DROP_START = 0.4;
const dropShare = (progress: number) =>
  progress < DROP_START
    ? (progress * progress) / (2 * DROP_START) / (1 - DROP_START / 2)
    : (progress - DROP_START / 2) / (1 - DROP_START / 2);

/** The same shuffle on the server and in the browser, so both draw the dots in one order. */
const seededOrder = (length: number) => {
  const order = Array.from({ length }, (_, index) => index);
  let seed = 20261028;
  for (let index = length - 1; index > 0; index -= 1) {
    seed = (seed * 1664525 + 1013904223) % 4294967296;
    const other = seed % (index + 1);
    [order[index], order[other]] = [order[other], order[index]];
  }
  return order;
};

// A dot's entrance, as the CSS transition the SVG dots had: half a second, dropping a little and
// fading in, with an overshoot at the end; leaving runs the same way back.
const DOT = { ms: 500, radius: 1.9, opacity: 0.6, lift: 12 };
// On a narrow screen the map shrinks to well under its 800 units; the dots and the city names keep
// at least this size on the screen, in CSS px.
const MIN_ON_SCREEN = { dot: 1.4, city: 11 };
/** cubic-bezier(0.3, 1.6, 0.5, 1), sampled once: the progress at each hundredth of the time. */
const DOT_EASE = Array.from({ length: 101 }, (_, step) => {
  const bezier = (a: number, b: number, t: number) =>
    3 * a * t * (1 - t) ** 2 + 3 * b * t ** 2 * (1 - t) + t ** 3;
  let low = 0;
  let high = 1;
  for (let round = 0; round < 24; round += 1) {
    const middle = (low + high) / 2;
    if (bezier(0.3, 0.5, middle) < step / 100) low = middle;
    else high = middle;
  }
  return bezier(1.6, 1, (low + high) / 2);
});
const dotEase = (time: number) => DOT_EASE[Math.round(Math.min(1, Math.max(0, time)) * 100)];

/**
 * "A pontokból kirajzolódik az alkotások földrajzi helye", told by scrolling: the view stands still while the
 * reader scrolls, and the creations drop onto an empty view one by one, in a fixed random
 * order, until they draw the country. The city names come last. With reduced motion every
 * dot is there at once.
 */
export function DotDrop({
  label,
  title,
  lead,
}: {
  label: string;
  title: ReactNode;
  lead?: ReactNode;
}) {
  const box = useRef<HTMLDivElement>(null);
  // The dots come when the view comes near: no need for them in the page's first load.
  const [stage, near] = useInView<HTMLDivElement>('1000px');
  const [points, setPoints] = useState<[number, number][]>([]);
  const [failed, setFailed] = useState(false);
  const [loading, setLoading] = useState(true);
  const [attempt, setAttempt] = useState(0);
  useEffect(() => {
    if (!near) return;
    setFailed(false);
    setLoading(true);
    const controller = new AbortController();
    (async () => {
      try {
        const response = await fetch('/api/creation-points', { signal: controller.signal });
        if (!response.ok) throw new Error(`Creation points: ${response.status}`);
        const body = (await response.json()) as { points: [number, number][] };
        if (
          !Array.isArray(body.points) ||
          !body.points.every(
            (point) => Array.isArray(point) && point.length === 2 && point.every(Number.isFinite)
          )
        )
          throw new Error('Invalid creation points');
        if (!controller.signal.aborted) setPoints(body.points);
      } catch (error) {
        if (!controller.signal.aborted) {
          console.error(error);
          setFailed(true);
        }
      } finally {
        if (!controller.signal.aborted) setLoading(false);
      }
    })();
    return () => controller.abort();
  }, [near, attempt]);
  const svg = useRef<SVGSVGElement>(null);
  const canvas = useRef<HTMLCanvasElement>(null);
  const cities = useRef<SVGGElement>(null);
  const drawnWidth = useElementWidth(svg);
  // Map units per CSS px once the map is drawn smaller than its own size, otherwise 1.
  const grow = drawnWidth ? Math.max(1, DROP.width / drawnWidth) : 1;
  const cityFont = Math.max(13, MIN_ON_SCREEN.city * grow);
  const projected = useMemo(() => {
    const projection = geoMercator().fitExtent(
      [
        [16, 16],
        [DROP.width - 16, DROP.height - 16],
      ],
      {
        type: 'MultiPoint',
        coordinates: [
          [16, 45.3],
          [24.2, 48.7],
        ],
      }
    );
    // Rounded, so the server and the browser draw the very same numbers.
    const project = (point: [number, number]) => {
      const position = projection(point);
      return position
        ? ([Math.round(position[0] * 10) / 10, Math.round(position[1] * 10) / 10] as const)
        : null;
    };
    return {
      dots: seededOrder(points.length)
        .map((index) => project(points[index]))
        .filter((position) => position !== null),
      cities: CITIES.map((city) => ({ ...city, position: project([city.lng, city.lat]) })),
    };
  }, [points]);
  const total = projected.dots.length;

  // Thousands of dots on one canvas instead of as many SVG elements: the server sends no dots,
  // and the browser keeps one element. Each dot keeps its own transition, from wherever it was.
  useEffect(() => {
    const element = box.current;
    const picture = canvas.current;
    const frame = svg.current;
    const context = picture?.getContext('2d');
    if (!element || !picture || !frame || !context) return;
    const still = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const dotsCount = projected.dots.length;
    const from = new Float32Array(dotsCount);
    const target = new Uint8Array(dotsCount);
    const since = new Float64Array(dotsCount);
    const view = { ratio: 1, scale: 1, x: 0, y: 0, radius: DOT.radius };
    let shown = 0;
    let request = 0;

    const valueAt = (index: number, now: number) =>
      from[index] +
      (target[index] - from[index]) * (still ? 1 : dotEase((now - since[index]) / DOT.ms));

    // Returns whether a dot is still moving, so the next frame is needed.
    const draw = (now: number) => {
      context.setTransform(1, 0, 0, 1, 0, 0);
      context.clearRect(0, 0, picture.width, picture.height);
      const scale = view.ratio * view.scale;
      context.setTransform(scale, 0, 0, scale, view.ratio * view.x, view.ratio * view.y);
      context.fillStyle = ACCENT;
      // The dots at rest share one path; the moving ones are drawn one by one.
      context.globalAlpha = DOT.opacity;
      context.beginPath();
      let moving = false;
      for (let index = 0; index < dotsCount; index += 1) {
        if (!target[index] && !from[index]) continue;
        const [x, y] = projected.dots[index];
        if (still || now - since[index] >= DOT.ms) {
          from[index] = target[index];
          if (!target[index]) continue;
          context.moveTo(x + view.radius, y);
          context.arc(x, y, view.radius, 0, 2 * Math.PI);
          continue;
        }
        moving = true;
      }
      context.fill();
      if (moving) {
        for (let index = 0; index < dotsCount; index += 1) {
          if (now - since[index] >= DOT.ms || (!target[index] && !from[index])) continue;
          const value = valueAt(index, now);
          if (value <= 0) continue;
          const [x, y] = projected.dots[index];
          context.globalAlpha = Math.min(1, value * DOT.opacity);
          context.beginPath();
          context.arc(x, y - DOT.lift * (1 - value), view.radius, 0, 2 * Math.PI);
          context.fill();
        }
      }
      return moving;
    };

    const update = () => {
      request = 0;
      const now = performance.now();
      const rect = element.getBoundingClientRect();
      // Every dot is down a little before the end, so the full map stays for a moment.
      const travel = Math.max(1, (rect.height - window.innerHeight) * 0.8);
      const progress = still ? 1 : Math.min(1, Math.max(0, -rect.top / travel));
      const next = Math.round(dropShare(progress) * total);
      const turn = (index: number, on: number) => {
        from[index] = valueAt(index, now);
        target[index] = on;
        since[index] = now;
      };
      for (let index = shown; index < next; index += 1) turn(index, 1);
      for (let index = next; index < shown; index += 1) turn(index, 0);
      shown = next;
      if (cities.current) {
        if (next === total) cities.current.dataset.on = '';
        else delete cities.current.dataset.on;
      }
      if (draw(now)) schedule();
    };
    const schedule = () => {
      if (!request) request = requestAnimationFrame(update);
    };

    // The canvas lies exactly over the SVG and draws in its viewBox units, scaled as the SVG
    // scales them (meet: the whole view fits, centred).
    const measure = () => {
      const outer = frame.getBoundingClientRect();
      const parent = picture.parentElement?.getBoundingClientRect() ?? outer;
      view.ratio = window.devicePixelRatio || 1;
      view.scale = Math.min(outer.width / DROP.width, outer.height / DROP.height);
      view.radius = Math.max(DOT.radius, MIN_ON_SCREEN.dot / view.scale);
      view.x = (outer.width - DROP.width * view.scale) / 2;
      view.y = (outer.height - DROP.height * view.scale) / 2;
      Object.assign(picture.style, {
        left: `${outer.left - parent.left}px`,
        top: `${outer.top - parent.top}px`,
        width: `${outer.width}px`,
        height: `${outer.height}px`,
      });
      picture.width = Math.round(outer.width * view.ratio);
      picture.height = Math.round(outer.height * view.ratio);
      draw(performance.now());
      schedule();
    };

    const observer = new ResizeObserver(measure);
    observer.observe(frame);
    measure();
    window.addEventListener('scroll', schedule, { passive: true });
    return () => {
      observer.disconnect();
      window.removeEventListener('scroll', schedule);
      cancelAnimationFrame(request);
    };
  }, [projected, total]);

  return (
    <div ref={box} className={cn('relative', failed ? 'min-h-[60vh]' : 'h-[340vh]')}>
      <div
        ref={stage}
        className="sticky top-[var(--header-h)] flex h-[calc(100svh-var(--header-h))] items-center"
      >
        <div className="w-full">
          <StoryBlock layout="stack" title={title} lead={lead} framed={false}>
            <div role="status" aria-live="polite">
              {failed ? (
                <Text tone="inverseMuted" className="py-6">
                  Most nem sikerült betölteni a térkép pontjait.{' '}
                  <Button variant="link" inverted onClick={() => setAttempt((value) => value + 1)}>
                    Újrapróbálás
                  </Button>
                </Text>
              ) : loading ? (
                <Text tone="inverseMuted">A térkép pontjainak betöltése…</Text>
              ) : null}
            </div>
            <div className={cn('relative', (failed || loading) && 'invisible')}>
              <canvas ref={canvas} aria-hidden className="pointer-events-none absolute" />
              <svg
                ref={svg}
                viewBox={`0 0 ${DROP.width} ${DROP.height}`}
                // The title and the lead stand above the map: it takes the height that is left.
                className="relative mx-auto block h-auto max-h-[calc(100svh-var(--header-h)-22rem)] w-full lg:max-h-[calc(100svh-var(--header-h)-15rem)]"
                role="img"
                aria-label={`${label}: ${formatNumber(total)} alkotás`}
              >
                <g
                  ref={cities}
                  className="opacity-0 transition-opacity duration-700 data-[on]:opacity-100"
                >
                  {projected.cities.map((city) =>
                    city.position ? (
                      <g key={city.name}>
                        <circle
                          cx={city.position[0]}
                          cy={city.position[1]}
                          r={3 * grow}
                          fill="white"
                        />
                        <text
                          // Near the right edge the name reads to the left of its city.
                          {...(city.position[0] > DROP.width * 0.8
                            ? { x: city.position[0] - 6 * grow, textAnchor: 'end' }
                            : { x: city.position[0] + 6 * grow })}
                          y={city.position[1] - 6 * grow}
                          fontSize={cityFont}
                          fontWeight={600}
                          fill="white"
                          stroke={INK}
                          strokeWidth={3 * grow}
                          paintOrder="stroke"
                        >
                          {city.name}
                        </text>
                      </g>
                    ) : null
                  )}
                </g>
              </svg>
            </div>
          </StoryBlock>
        </div>
      </div>
    </div>
  );
}

// A video card's data: the featured videos, and the channel's recommended ones (no branch).
type VideoCardData = Omit<(typeof import('./_data/videos.json'))['featured'][number], 'branch'>;

/** A featured video in the shape the project's video card reads (as on the Videók page). */
const toVideoCard = (video: VideoCardData, index: number): CreationListItem => ({
  id: index,
  alkotasAzonosito: video.id,
  cardType: 'creation',
  nev: video.title,
  fokep: video.image ? { id: video.image } : null,
  hivatkozas: null,
  hivatkozasLista: [
    {
      cim: null,
      hivatkozas: video.youtube,
      link: null,
      forrasa: null,
      sorozat: null,
      sorozatPozicio: null,
      leiras: null,
      tipus: 'alkotas_video',
      status: 'public',
    },
  ],
  koordinatak: null,
  label: video.year ? String(video.year) : null,
  labelYear: video.year,
  telepules: null,
  alkoto: [
    {
      alkotoAzonosito: video.creator.id,
      megjelenitendoNev: video.creator.name,
      szakma: video.creator.profession ?? null,
    },
  ],
});

/** YouTube video cards: the video plays in the site's player, the title leads to the creation. */
export function VideoCards({ videos, className }: { videos: VideoCardData[]; className?: string }) {
  const dark = useSectionTone() === 'dark';
  return (
    <ul className={cn('grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2 lg:grid-cols-4', className)}>
      {videos.map((video, index) => (
        <li key={video.id} className="min-w-0">
          <CreationVideoCard data={toVideoCard(video, index)} vertical inverted={dark} />
        </li>
      ))}
    </ul>
  );
}
