"use client";

/**
 * Dot-matrix Türkiye silüeti — hero arka planı için dekoratif SVG.
 * Izgara, gerçek sınır poligonlarından 64×28 hücreye rasterize edildi;
 * Marmara Denizi boşluğu bilinçli olarak açık.
 *
 * Performans kurgusu: ~1000 piksel, React elemanı olarak DEĞİL, modül
 * yüklenirken tek sefer üretilen statik bir SVG string'i olarak basılır
 * (dangerouslySetInnerHTML). Böylece her sayfa yenilemesinde React bu
 * elemanları yeniden kurmaz/hydrate etmez; sunucudan gelen HTML olduğu
 * gibi kullanılır. Deterministik üretim sayesinde server ve client aynı
 * çıktıyı verir (hydration uyumsuzluğu olmaz).
 *
 * Cursor etkileşimi: imleç yaklaşınca pikseller anında turuncuya ısınır,
 * imleç uzaklaşınca yavaşça kendi mavi tonuna soğur (asimetrik zamanlama).
 * Fırça mantığı usePixelHeat hook'unda ortaklaştırıldı; DOM'a
 * querySelectorAll ile bağlandığı için statik markup'la sorunsuz çalışır.
 */

import { useRef } from "react";
import { usePixelHeat } from "@/components/use-pixel-heat";

const GRID = [
  "..######..............##########................................",
  "..#######...........##############..............................",
  "..#######.........#################................#####........",
  ".########...###########################...........########......",
  ".######.....###############################################.....",
  ".###........###############################################.....",
  ".##.......##################################################....",
  ".###########################################################....",
  ".#############################################################..",
  "..#############################################################.",
  "...############################################################.",
  "...##########################################################...",
  "...##########################################################...",
  "...###########################################################..",
  "..############################################################..",
  "..############################################################..",
  "...###########################################################..",
  "....##########################################################..",
  "....##########################################################..",
  ".....#########################################################..",
  ".....###################################################..##....",
  ".....############################################...............",
  "......##########..######################...###..................",
  "...........#####....#########....#####..........................",
  "............###.......#####......####...........................",
  ".................................###............................",
];

// Vurgu pikselleri: öğrenci yoğunluğu yüksek şehirler (col, row)
const CITIES = [
  { name: "İstanbul", x: 8, y: 4 },
  { name: "Ankara", x: 23, y: 9 },
  { name: "İzmir", x: 4, y: 16 },
  { name: "Antalya", x: 16, y: 22 },
  { name: "Kayseri", x: 32, y: 14 },
  { name: "Trabzon", x: 46, y: 5 },
  { name: "Diyarbakır", x: 47, y: 18 },
  { name: "Van", x: 58, y: 15 },
];

const CELL = 10;
const DOT = 7.4;
const INSET = (CELL - DOT) / 2;
const COLS = GRID[0].length;
const ROWS = GRID.length;
// Güney kıyının altına doğru seyrelerek dağılan serpinti derinliği (hücre)
const SCATTER_DEPTH = 9;
const VIEW_W = COLS * CELL;
const VIEW_H = (ROWS + SCATTER_DEPTH) * CELL;

// Deterministik doku: hücreye göre sabit opaklık (hydration güvenli)
const OPACITIES = [0.3, 0.16, 0.24, 0.12, 0.27, 0.19];
const opacityFor = (x: number, y: number) =>
  OPACITIES[(x * 7 + y * 11) % OPACITIES.length];

const cityCells = new Set(CITIES.map((c) => `${c.x},${c.y}`));

// Deterministik sözde-rastgele (pixel-decor ile aynı): server ve client
// aynı serpinti desenini üretir
const hash = (x: number, y: number, seed = 0) => {
  const n = Math.sin(x * 127.1 + y * 311.7 + seed * 74.7) * 43758.5453;
  return n - Math.floor(n);
};

/* ------------------------------------------------------------------ */
/* Statik markup: modül yüklenirken TEK SEFER üretilir                  */
/* ------------------------------------------------------------------ */

const rectAttrs = (x: number, y: number) =>
  `x="${x * CELL + INSET}" y="${y * CELL + INSET}" width="${DOT}" height="${DOT}" rx="2"`;

const MAP_MARKUP = (() => {
  const parts: string[] = [];
  GRID.forEach((row, y) => {
    for (let x = 0; x < row.length; x++) {
      if (row[x] !== "#" || cityCells.has(`${x},${y}`)) continue;
      const op = opacityFor(x, y);
      parts.push(
        `<rect data-px data-cx="${x * CELL + CELL / 2}" data-cy="${y * CELL + CELL / 2}" data-op="${op}" ${rectAttrs(x, y)} fill="currentColor" fill-opacity="${op}"/>`,
      );
    }
  });
  // Silüetin altına serpinti: her kolonun en alttaki kara hücresinden
  // aşağı doğru, kıyı hattını izleyerek seyrelen pikseller. Hover
  // fırçasına da katılırlar (data-px).
  const lastLand: number[] = Array(COLS).fill(-1);
  GRID.forEach((row, y) => {
    for (let x = 0; x < row.length; x++) {
      if (row[x] === "#") lastLand[x] = y;
    }
  });
  let scatterAccent = 0;
  for (let x = 0; x < COLS; x++) {
    if (lastLand[x] < 0) continue;
    for (let d = 1; d <= SCATTER_DEPTH; d++) {
      const y = lastLand[x] + d;
      if (y >= ROWS + SCATTER_DEPTH) break;
      // Kıyıdan uzaklaştıkça seyrelen doluluk; küçük taban sayesinde
      // en derin sıralarda da tek tük piksel kalır
      const density = 0.05 + 0.4 * (1 - (d - 1) / SCATTER_DEPTH) ** 2;
      if (hash(x, y) > density) continue;
      if (hash(x, y, 99) > 0.96) {
        // Nadir turuncu vurgu: şehir pikselleriyle aynı nabız dili
        parts.push(
          `<rect ${rectAttrs(x, y)} class="animate-pulse fill-orange-500/70 motion-reduce:animate-none" style="animation-duration:3.6s;animation-delay:${(scatterAccent++ % 8) * 0.45}s"/>`,
        );
        continue;
      }
      // Derinlikle sönen opaklık
      const op =
        Math.round(opacityFor(x, y) * (1 - d / (SCATTER_DEPTH + 1)) * 100) /
        100;
      parts.push(
        `<rect data-px data-cx="${x * CELL + CELL / 2}" data-cy="${y * CELL + CELL / 2}" data-op="${op}" ${rectAttrs(x, y)} fill="currentColor" fill-opacity="${op}"/>`,
      );
    }
  }
  // Şehir pikselleri: turuncu, hafif nabız; hover fırçasına katılmazlar
  CITIES.forEach((city, i) => {
    parts.push(
      `<rect ${rectAttrs(city.x, city.y)} class="animate-pulse fill-orange-500/70 motion-reduce:animate-none" style="animation-duration:3.6s;animation-delay:${i * 0.45}s"/>`,
    );
  });
  return parts.join("");
})();

export function TurkeyPixelMap({ className }: { className?: string }) {
  const svgRef = useRef<SVGSVGElement>(null);
  usePixelHeat(svgRef);

  return (
    <svg
      ref={svgRef}
      viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}
      className={className}
      aria-hidden="true"
      focusable="false"
      // Statik, deterministik markup — her render'da yeniden kurulmaz
      dangerouslySetInnerHTML={{ __html: MAP_MARKUP }}
    />
  );
}
