'use client';

import { Fragment, type MouseEvent, useCallback, useEffect, useMemo, useState } from 'react';

import { geoMercator, interpolateRgb, quantile, scaleSqrt } from 'd3';

import { Text } from '@/components/ui/typography';

import counties from './_data/hu-counties.json';
import { PeoplePopup, PersonName, formatNumber } from './charts';
import type { Ranked } from './types';

const INK = '#151720';
const ACCENT = '#dfcf6f';

// The Carpathian Basin around the cities beyond the border; the creations' dots draw the country inside.

// A rough width of one letter of the labels, for keeping them apart.

/**
 * The big awards on one age ruler: each as a band from the younger to the older quarter of its
 * laureates, with its typical age.
 */
export function CareerRuler({ awards }: { awards: { award: string; ages: number[] }[] }) {
  const width = 960;
  const left = 330;
  // The typical age and the number of laureates stand in their own column on the right.
  const right = width - 170;
  const minAge = 10;
  const maxAge = 100;
  const x = (age: number) => left + ((age - minAge) / (maxAge - minAge)) * (right - left);
  const rows = awards
    .map((entry) => {
      const ages = [...entry.ages].sort((a, b) => a - b);
      return {
        award: entry.award,
        low: quantile(ages, 0.25) ?? 0,
        median: quantile(ages, 0.5) ?? 0,
        high: quantile(ages, 0.75) ?? 0,
        count: ages.length,
      };
    })
    .sort((a, b) => a.median - b.median);
  const rowTop = 40;
  const rowHeight = 29;
  const height = rowTop + rows.length * rowHeight + 24;
  const share = (age: number) => `${((age - minAge) / (maxAge - minAge)) * 100}%`;
  // The server sends both views and CSS shows the right one; the browser then keeps only that one.
  const [wide, setWide] = useState<boolean | null>(null);
  useEffect(() => {
    const query = window.matchMedia('(min-width: 1024px)');
    const update = () => setWide(query.matches);
    update();
    query.addEventListener('change', update);
    return () => query.removeEventListener('change', update);
  }, []);
  return (
    <>
      {/* Phones and tablets: the same ruler as rows of text and bars, large enough to read. */}
      {wide === true ? null : (
        <div className="lg:hidden">
          <ul className="flex flex-col gap-2.5">
            {rows.map((row) => (
              <li key={row.award}>
                <div className="flex items-baseline justify-between gap-3 text-sm">
                  <span className="font-semibold">{row.award}</span>
                  <span className="shrink-0 tabular-nums text-[#151720]/70">
                    {formatNumber(row.median)} év · {formatNumber(row.count)} fő
                  </span>
                </div>
                <span className="relative mt-1 block h-2 bg-[#151720]/[0.06]">
                  <span
                    className="absolute inset-y-0 rounded-full bg-[#151720]/20"
                    style={{ left: share(row.low), right: `calc(100% - ${share(row.high)})` }}
                  />
                  <span
                    className="absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border border-[#151720]"
                    style={{ left: share(row.median), background: ACCENT }}
                  />
                </span>
              </li>
            ))}
          </ul>
        </div>
      )}
      {wide === false ? null : (
        <svg
          viewBox={`0 0 ${width} ${height}`}
          className="hidden h-auto w-full lg:block"
          role="img"
          aria-label="A kiválasztott állami elismerések díjazottjainak életkora"
        >
          <text x={0} y={rowTop - 18} fontSize={13} fontWeight={700} fill={INK}>
            Állami elismerések
          </text>
          {rows.map((row, index) => {
            const y = rowTop + index * rowHeight;
            return (
              <g key={row.award}>
                <text x={0} y={y + 4} fontSize={13} fill={INK}>
                  {row.award}
                </text>
                <line x1={left} x2={right} y1={y} y2={y} stroke={INK} strokeOpacity={0.06} />
                <rect
                  x={x(row.low)}
                  y={y - 6}
                  width={Math.max(3, x(row.high) - x(row.low))}
                  height={12}
                  rx={6}
                  fill={INK}
                  fillOpacity={0.18}
                />
                <circle
                  cx={x(row.median)}
                  cy={y}
                  r={6}
                  fill={ACCENT}
                  stroke={INK}
                  strokeWidth={1}
                />
                <text
                  x={width}
                  y={y + 4}
                  fontSize={13}
                  fill={INK}
                  fillOpacity={0.7}
                  textAnchor="end"
                >
                  {`${formatNumber(row.median)} év · ${formatNumber(row.count)} díjazott`}
                </text>
              </g>
            );
          })}
          {[rowTop - 18, height - 6].map((y) => (
            <g key={y}>
              {[20, 30, 40, 50, 60, 70, 80, 90, 100].map((age) => (
                <text
                  key={age}
                  x={x(age)}
                  y={y}
                  fontSize={11}
                  fill={INK}
                  fillOpacity={0.5}
                  textAnchor={age === maxAge ? 'end' : 'middle'}
                >
                  {age}
                </text>
              ))}
            </g>
          ))}
        </svg>
      )}
    </>
  );
}

/** A ranking with big type: the first one large, the rest in a numbered column. */
export function TopList({ title, items, unit }: { title: string; items: Ranked[]; unit: string }) {
  const [first, ...rest] = items;
  if (!first) return null;
  return (
    <div>
      <Text variant="meta" tone="muted">
        {title}
      </Text>
      <p className="mt-3 font-slab text-4xl font-bold leading-none text-[#151720] sm:text-5xl">
        {first.label}
      </p>
      <Text variant="bodySm" tone="muted" className="mt-1">
        {formatNumber(first.value)} {unit}
      </Text>
      <ol className="mt-5 flex flex-col divide-y divide-[#151720]/10">
        {rest.map((item, index) => (
          <li key={item.label} className="flex items-baseline gap-3 py-2 text-sm">
            <span className="w-5 tabular-nums text-[#151720]/45">{index + 2}.</span>
            <span className="min-w-0 flex-1 truncate font-semibold">{item.label}</span>
            <span className="tabular-nums text-[#151720]/60">{formatNumber(item.value)}</span>
          </li>
        ))}
      </ol>
    </div>
  );
}

type BirthPlace = {
  city: string;
  country: string | null;
  lng: number;
  lat: number;
  people: { id: string; name: string; profession: string | null }[];
};
// Named on the birth places map, if anyone was born there, in three sizes: Budapest and Kolozsvár,
// the big towns of the country, then the rest. Szabadka's name goes under its dot, clear of Szeged's.
const BIRTH_LABELS: Record<string, 'large' | 'medium' | 'small'> = {
  Budapest: 'large',
  Kolozsvár: 'large',
  Szeged: 'medium',
  Pécs: 'medium',
  Miskolc: 'medium',
  Debrecen: 'medium',
  Szombathely: 'medium',
  Szabadka: 'small',
  Beregszász: 'small',
  Pozsony: 'small',
  Bécs: 'small',
};
// The size on the map's own scale. On a phone, where the map is narrow, the names a little larger,
// and the small ones left out (Szabadka's would run into Pécs).
const LABEL_SIZE = {
  large: { fontSize: 13, className: 'max-sm:text-[26px]' },
  medium: { fontSize: 10, className: 'max-sm:text-[24px]' },
  small: { fontSize: 9, className: 'max-sm:hidden' },
};
const LABEL_BELOW = new Set(['Szabadka']);
const BIRTH_RAMP = interpolateRgb('#f1f2f6', '#8a8ea3');

// The frame of the wide map, which the county paths are moved into.
const BIRTH_MAP = { width: 800, height: 480 };
const birthProjection = () =>
  geoMercator().fitExtent(
    [
      [16, 16],
      [BIRTH_MAP.width - 16, BIRTH_MAP.height - 16],
    ],
    {
      type: 'MultiPoint',
      coordinates: [
        [16, 44.6],
        [27.2, 49.4],
      ],
    }
  );
const inBasin = (point: { x: number; y: number } | [number, number]) => {
  const [x, y] = Array.isArray(point) ? point : [point.x, point.y];
  return x > 0 && x < BIRTH_MAP.width && y > 0 && y < BIRTH_MAP.height;
};

/**
 * The creators' birth places on one map: Hungary's counties shaded by how many were born there
 * (square root, as on the county map), and a dot for every town, yellow beyond today's border.
 * A click (or tap) on a town opens a small closable box beside it with everyone born there;
 * on a county, its count.
 */
export function BirthPlaceMap({ places, counts }: { places: BirthPlace[]; counts: Ranked[] }) {
  const { width, height } = BIRTH_MAP;
  const [selected, setSelected] = useState<
    | { kind: 'place'; place: BirthPlace; x: number; y: number }
    | { kind: 'county'; name: string; x: number; y: number }
    | null
  >(null);
  const [hovered, setHovered] = useState<BirthPlace | null>(null);
  const countOf = (name: string) => counts.find((entry) => entry.label === name)?.value ?? 0;
  // Budapest is a dot here, not an area: the shading is spread over the counties alone.
  const max = Math.sqrt(
    Math.max(...counts.filter((entry) => entry.label !== 'Budapest').map((entry) => entry.value), 1)
  );
  const fill = (name: string) => BIRTH_RAMP(Math.sqrt(countOf(name)) / max);
  const [k, tx, ty] = counties.wideTransform;
  const projection = useMemo(() => birthProjection(), []);
  const projected = useMemo(() => {
    const radius = scaleSqrt().domain([1, 16]).range([2.5, 7]).clamp(true);
    return places
      .map((place) => {
        const position = projection([place.lng, place.lat]);
        if (!position) return null;
        // Rounded, so the server and the browser draw the very same numbers.
        const [x, y] = position.map((value) => Math.round(value * 10) / 10);
        return { place, x, y, r: Math.round(radius(place.people.length) * 10) / 10 };
      })
      .filter((dot) => dot !== null)
      .map((dot) => dot!)
      .sort((a, b) => b.r - a.r);
  }, [places, projection]);
  const dots = projected.filter(inBasin);
  const labels = dots.filter((dot) => dot.place.city in BIRTH_LABELS);
  // Only the area the dots cover (with room for the names), so the map fills the width without
  // empty margins; the frame itself stays the wide dot map's, which the county paths are moved into.
  const frame = useMemo(() => {
    // Hungary's own extent too (west of Szentgotthárd no creator was born).
    const country = [projection([16.1, 45.73]), projection([22.91, 48.59])].filter(
      (point) => point !== null
    );
    const xs = [
      ...dots.flatMap((dot) => [dot.x - dot.r, dot.x + dot.r]),
      ...country.map((point) => point[0]),
    ];
    const ys = [
      ...dots.flatMap((dot) => [dot.y - dot.r, dot.y + dot.r]),
      ...country.map((point) => point[1]),
    ];
    const left = Math.max(0, Math.floor(Math.min(...xs) - 12));
    const top = Math.max(0, Math.floor(Math.min(...ys) - 12));
    const right = Math.min(width, Math.ceil(Math.max(...xs) + 24));
    const bottom = Math.min(height, Math.ceil(Math.max(...ys) + 20));
    return { left, top, width: right - left, height: bottom - top };
  }, [dots, projection, width, height]);
  // Born beyond the basin (western Europe, the Baltic): not drawn at all, as a dot at the edge would
  // read as a place there; BirthPlacesOutside lists them.

  const closeSelected = useCallback(() => setSelected(null), []);

  // A click (or tap) near a dot picks the nearest one, as on a phone the dots are smaller than a
  // finger; elsewhere on a county it shows the county, and outside the country it closes the box.
  const pick = (event: MouseEvent<SVGSVGElement>) => {
    const box = event.currentTarget.getBoundingClientRect();
    const scale = frame.width / box.width;
    const x = frame.left + (event.clientX - box.left) * scale;
    const y = frame.top + (event.clientY - box.top) * scale;
    let nearest: (typeof dots)[number] | null = null;
    // A finger needs more room than a mouse pointer.
    let best = (box.width < 640 ? 16 : 8) * scale;
    for (const dot of dots) {
      const distance = Math.hypot(dot.x - x, dot.y - y) - dot.r;
      if (distance < best) {
        best = distance;
        nearest = dot;
      }
    }
    const county = (event.target as Element).getAttribute?.('data-county');
    if (nearest) setSelected({ kind: 'place', place: nearest.place, x: nearest.x, y: nearest.y });
    else if (county) setSelected({ kind: 'county', name: county, x, y });
    else setSelected(null);
  };
  // A place with no country given (one record) counts as Hungarian: its town is in Hungary.
  const abroad = (place: BirthPlace) => Boolean(place.country) && place.country !== 'Magyarország';
  const selectedPlace = selected?.kind === 'place' ? selected.place : null;
  const selectedCounty = selected?.kind === 'county' ? selected.name : '';

  return (
    <div>
      <Text className="mb-4 font-semibold">
        Kattintson egy településre: megmutatjuk, kik születtek ott.
      </Text>
      <div className="relative">
        <svg
          viewBox={`${frame.left} ${frame.top} ${frame.width} ${frame.height}`}
          className="h-auto w-full"
          role="img"
          aria-label={`Az alkotók születési helyei, ${formatNumber(dots.length)} település. Megyénként: ${counts.map((entry) => `${entry.label} ${entry.value}`).join(', ')}`}
          onClick={pick}
          onMouseLeave={() => setHovered(null)}
        >
          <g transform={`matrix(${k} 0 0 ${k} ${tx} ${ty})`}>
            {counties.counties.map((county) => (
              <path
                key={county.name}
                data-county={county.name}
                d={county.d}
                fill={fill(county.name)}
                stroke="white"
                strokeWidth={selected?.kind === 'county' && selected.name === county.name ? 2.5 : 1}
                vectorEffect="non-scaling-stroke"
              >
                <title>{`${county.name}: ${formatNumber(countOf(county.name))}`}</title>
              </path>
            ))}
          </g>
          {dots.map((dot) => {
            const marked = selectedPlace === dot.place || hovered === dot.place;
            return (
              <circle
                key={`${dot.place.city}-${dot.place.country}`}
                cx={dot.x}
                cy={dot.y}
                r={dot.r}
                fill={abroad(dot.place) ? ACCENT : INK}
                fillOpacity={abroad(dot.place) ? 1 : 0.7}
                stroke={marked ? INK : 'white'}
                strokeWidth={marked ? 2 : 0.8}
                className="cursor-pointer"
                onMouseEnter={() => setHovered(dot.place)}
              >
                <title>{`${dot.place.city}: ${formatNumber(dot.place.people.length)} alkotó`}</title>
              </circle>
            );
          })}
          {labels.map((dot) => (
            <text
              key={dot.place.city}
              x={LABEL_BELOW.has(dot.place.city) ? dot.x : dot.x + dot.r + 4}
              y={LABEL_BELOW.has(dot.place.city) ? dot.y + dot.r + 12 : dot.y + 4}
              textAnchor={LABEL_BELOW.has(dot.place.city) ? 'middle' : 'start'}
              fontSize={LABEL_SIZE[BIRTH_LABELS[dot.place.city]].fontSize}
              className={LABEL_SIZE[BIRTH_LABELS[dot.place.city]].className}
              fontWeight={600}
              fill={INK}
              stroke="white"
              strokeWidth={3}
              paintOrder="stroke"
              pointerEvents="none"
            >
              {dot.place.city}
            </text>
          ))}
        </svg>

        {selected ? (
          <PeoplePopup
            title={selectedPlace ? selectedPlace.city : `${selectedCounty} megye`}
            summary={`${selectedPlace && abroad(selectedPlace) ? `${selectedPlace.country} · ` : ''}${formatNumber(
              selectedPlace ? selectedPlace.people.length : countOf(selectedCounty)
            )} alkotó született itt`}
            people={selectedPlace?.people}
            left={((selected.x - frame.left) / frame.width) * 100}
            top={((selected.y - frame.top) / frame.height) * 100}
            label={selectedPlace ? `${selectedPlace.city}: itt született alkotók` : selectedCounty}
            onClose={closeSelected}
          />
        ) : null}
      </div>
      <div className="mt-3 flex flex-wrap gap-x-6 gap-y-1 text-xs text-[#151720]/70">
        <span className="flex items-center gap-1.5">
          <span className="size-2.5 rounded-full" style={{ background: INK, opacity: 0.7 }} />
          Magyarországon
        </span>
        <span className="flex items-center gap-1.5">
          <span
            className="size-2.5 rounded-full border border-[#151720]/40"
            style={{ background: ACCENT }}
          />
          A mai határokon túl
        </span>
        <span>A nagyobb pont több alkotót jelöl; a sötétebb megyében többen születtek.</span>
      </div>
    </div>
  );
}

/** The creators born beyond the birth place map's frame (western Europe, the Baltic), by town. */
export function BirthPlacesOutside({ places }: { places: BirthPlace[] }) {
  const outside = useMemo(() => {
    const projection = birthProjection();
    return places
      .filter((place) => {
        const position = projection([place.lng, place.lat]);
        return position !== null && !inBasin(position);
      })
      .sort((a, b) => a.city.localeCompare(b.city, 'hu'));
  }, [places]);
  if (!outside.length) return null;
  return (
    <div className="border border-[#151720]/15 bg-white p-4 text-sm">
      <p className="font-semibold text-[#151720]">A térképen megjelenítetteken kívül:</p>
      <ul className="mt-2 space-y-1.5 text-[#151720]/75">
        {outside.map((place) => (
          <li key={`${place.city}-${place.country}`}>
            <span className="font-semibold text-[#151720]">
              {place.city}
              {place.country ? `, ${place.country}` : ''}:
            </span>{' '}
            {[...place.people]
              .sort((a, b) => a.name.localeCompare(b.name, 'hu'))
              .map((person, index) => (
                <Fragment key={person.id}>
                  {index > 0 ? '; ' : ''}
                  <PersonName person={person} />
                  {person.profession ? ` – ${person.profession}` : ''}
                </Fragment>
              ))}
          </li>
        ))}
      </ul>
    </div>
  );
}
