"use client";

import { useEffect, useRef, useState, type ReactNode } from "react";
import { fmt } from "@/app/(admin)/_lib/data";
import { useStore } from "@/app/(admin)/_lib/store";
import { Icon } from "./Icon";

/* ------------------------------------------------------------------ */
/* Animated node network drawn on a canvas                             */
/* ------------------------------------------------------------------ */

export function NetworkCanvas({ count = 70, className }: { count?: number; className?: string }) {
  const ref = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = ref.current;
    const ctx = canvas?.getContext("2d");
    if (!canvas || !ctx) return;
    if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    type P = { x: number; y: number; vx: number; vy: number; r: number };
    let pts: P[] = [];
    let w = 0;
    let h = 0;
    let raf = 0;
    const dpr = devicePixelRatio || 1;

    const size = () => {
      const r = canvas.getBoundingClientRect();
      w = canvas.width = r.width * dpr;
      h = canvas.height = r.height * dpr;
      pts = Array.from({ length: count }, () => ({
        x: Math.random() * w,
        y: Math.random() * h,
        vx: (Math.random() - 0.5) * 0.25 * dpr,
        vy: (Math.random() - 0.5) * 0.25 * dpr,
        r: (Math.random() * 1.6 + 0.6) * dpr,
      }));
    };

    const tick = () => {
      ctx.clearRect(0, 0, w, h);
      const L = 130 * dpr;
      for (const p of pts) {
        p.x += p.vx;
        p.y += p.vy;
        if (p.x < 0 || p.x > w) p.vx *= -1;
        if (p.y < 0 || p.y > h) p.vy *= -1;
      }
      ctx.lineWidth = dpr * 0.7;
      for (let i = 0; i < pts.length; i++)
        for (let j = i + 1; j < pts.length; j++) {
          const a = pts[i];
          const b = pts[j];
          const d = Math.hypot(a.x - b.x, a.y - b.y);
          if (d < L) {
            ctx.strokeStyle = `rgba(140,190,255,${(1 - d / L) * 0.35})`;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y);
            ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      ctx.fillStyle = "rgba(200,225,255,.9)";
      for (const p of pts) {
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
        ctx.fill();
      }
      raf = requestAnimationFrame(tick);
    };

    const ro = new ResizeObserver(size);
    ro.observe(canvas);
    size();
    tick();
    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
    };
  }, [count]);

  return <canvas ref={ref} className={className} />;
}

/* ------------------------------------------------------------------ */
/* Number that counts up from 0                                        */
/* ------------------------------------------------------------------ */

export function CountUp({ value, prefix = "", decimals = 0, replay = 0 }: { value: number; prefix?: string; decimals?: number; replay?: number }) {
  const [shown, setShown] = useState(0);

  useEffect(() => {
    let raf = 0;
    const t0 = performance.now();
    const D = 1200;
    const step = (t: number) => {
      const p = Math.min(1, (t - t0) / D);
      setShown(value * (1 - Math.pow(1 - p, 3)));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value, replay]);

  return (
    <>
      {prefix}
      {shown.toLocaleString("en", { minimumFractionDigits: decimals, maximumFractionDigits: decimals })}
    </>
  );
}

/* ------------------------------------------------------------------ */
/* Progress bar that grows in                                          */
/* ------------------------------------------------------------------ */

export function Fill({ pct, tone = "" }: { pct: number; tone?: "" | "g" | "a" }) {
  const [w, setW] = useState(0);
  useEffect(() => {
    const t = setTimeout(() => setW(pct), 120);
    return () => clearTimeout(t);
  }, [pct]);
  return (
    <div className="track">
      <div className={`fill ${tone}`} style={{ width: `${w}%` }} />
    </div>
  );
}

/** Adds a class shortly after mount so CSS transitions play. */
function useDrawn(delay = 60) {
  const [on, setOn] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setOn(true), delay);
    return () => {
      clearTimeout(t);
      setOn(false);
    };
  }, [delay]);
  return on;
}

/* ------------------------------------------------------------------ */
/* Area chart                                                          */
/* ------------------------------------------------------------------ */

export function AreaChart({ series, labels }: { series: number[][]; labels: string[] }) {
  const drawn = useDrawn();
  const W = 760;
  const H = 260;
  const P = { l: 44, r: 14, t: 16, b: 30 };
  const max = Math.max(...series.flat()) * 1.15 || 1;
  const x = (i: number) => P.l + (i * (W - P.l - P.r)) / (labels.length - 1);
  const y = (v: number) => H - P.b - (v / max) * (H - P.t - P.b);
  const path = (s: number[]) =>
    s
      .map((v, i) => {
        if (!i) return `M${x(i)},${y(v)}`;
        const cx = (x(i - 1) + x(i)) / 2;
        return `C${cx},${y(s[i - 1])} ${cx},${y(v)} ${x(i)},${y(v)}`;
      })
      .join(" ");
  const cols = ["#0B57D0", "#0F8A5F"];

  return (
    <svg className={`chart${drawn ? " drawn" : ""}`} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" role="img" aria-label="Monthly donations chart">
      <defs>
        {cols.map((c, i) => (
          <linearGradient key={c} id={`area-g${i}`} x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor={c} stopOpacity=".22" />
            <stop offset="1" stopColor={c} stopOpacity="0" />
          </linearGradient>
        ))}
      </defs>
      {[0, 0.25, 0.5, 0.75, 1].map((f) => {
        const yy = y(max * f);
        return (
          <g key={f}>
            <line x1={P.l} x2={W - P.r} y1={yy} y2={yy} stroke="#EEF1F6" />
            <text x={P.l - 8} y={yy + 4} textAnchor="end" fontSize="11" fill="#94a3b8">
              €{fmt(max * f)}
            </text>
          </g>
        );
      })}
      {labels.map((l, i) => (
        <text key={l} x={x(i)} y={H - 8} textAnchor="middle" fontSize="11" fill="#94a3b8">
          {l}
        </text>
      ))}
      {series.map((s, k) => (
        <g key={k}>
          <path className="area" d={`${path(s)} L${x(s.length - 1)},${H - P.b} L${x(0)},${H - P.b}Z`} fill={`url(#area-g${k})`} />
          <path className="ln" d={path(s)} fill="none" stroke={cols[k]} strokeWidth="2.5" />
        </g>
      ))}
      {series[0].map((v, i) => (
        <circle key={i} className="pt" cx={x(i)} cy={y(v)} r="3.5" fill="#fff" stroke="#0B57D0" strokeWidth="2" />
      ))}
    </svg>
  );
}

/* ------------------------------------------------------------------ */
/* Donut                                                               */
/* ------------------------------------------------------------------ */

export function Donut({ parts, label, caption }: { parts: { v: number; c: string }[]; label: string; caption: string }) {
  const drawn = useDrawn(100);
  const C = 2 * Math.PI * 52;
  // Each slice starts where the previous ones end.
  const segs = parts.map((p, i) => ({
    ...p,
    len: (C * p.v) / 100,
    off: parts.slice(0, i).reduce((sum, q) => sum + (C * q.v) / 100, 0),
  }));
  return (
    <svg className="donut" width="140" height="140" viewBox="0 0 140 140" role="img" aria-label={`${label} ${caption}`}>
      <circle cx="70" cy="70" r="52" fill="none" stroke="#F1F4F8" strokeWidth="16" />
      {segs.map((p) => (
        <circle
          key={p.c}
          cx="70"
          cy="70"
          r="52"
          fill="none"
          stroke={p.c}
          strokeWidth="16"
          strokeDasharray={drawn ? `${p.len} ${C - p.len}` : `0 ${C}`}
          strokeDashoffset={-p.off}
          transform="rotate(-90 70 70)"
        />
      ))}
      <text x="70" y="66" textAnchor="middle" fontWeight="700" fontSize="20" fill="#0F172A" style={{ fontFamily: "var(--ff-head)" }}>
        {label}
      </text>
      <text x="70" y="84" textAnchor="middle" fontSize="11" fill="#64748B">
        {caption}
      </text>
    </svg>
  );
}

/* ------------------------------------------------------------------ */
/* Toast + page wrapper                                                */
/* ------------------------------------------------------------------ */

export function Toast() {
  const { toastMsg, toastOn } = useStore();
  return (
    <div id="toast" className={toastOn ? "on" : ""} role="status" aria-live="polite">
      <span className="ok">
        <Icon name="check" size={13} style={{ strokeWidth: 3 }} />
      </span>
      <span>{toastMsg}</span>
    </div>
  );
}

export function PageHeader({ crumb, title, desc, children }: { crumb: ReactNode; title: string; desc: ReactNode; children?: ReactNode }) {
  return (
    <div className="ph">
      <div>
        <div className="crumb">{crumb}</div>
        <h1>{title}</h1>
        <p>{desc}</p>
      </div>
      {children && <div className="ph-actions">{children}</div>}
    </div>
  );
}

export function Seg<T extends string>({ options, value, onChange, label }: { options: readonly T[]; value: T; onChange: (v: T) => void; label: string }) {
  return (
    <div className="seg" role="group" aria-label={label}>
      {options.map((o) => (
        <button key={o} type="button" className={o === value ? "on" : ""} aria-pressed={o === value} onClick={() => onChange(o)}>
          {o}
        </button>
      ))}
    </div>
  );
}
