"use client";

import { useEffect, useRef, useState } from "react";
import { ensureGsap, motionEnabled } from "@/lib/motion";

type Key = "competence" | "character";
type Props = { competence: string; character: string; label: string };

const R = 120;
const C = 2 * Math.PI * R;
const GAP = 6;
const LEN = { competence: C * 0.3 - GAP, character: C * 0.7 - GAP };
const OFFSET = { competence: -GAP / 2, character: -(C * 0.3 + GAP / 2) };
const VALUE = { competence: 30, character: 70 };

/**
 * 30% Competence / 70% Character (PDF p.6).
 * Scroll (scrubbed, so it runs forwards on the way down and reverses on the way up):
 * frame rings → competence arc draws while its figure counts to 30 → character arc draws
 * while counting to 70 → labels settle.
 * Interaction: hover / focus previews a segment, click (or Enter/Space) pins it. The emphasis
 * only changes opacity / stroke width / glow on wrapper groups, never the scroll-driven
 * dash lengths or numbers, so the two systems cannot fight.
 * Proportions are exact: arcs are 30% and 70% of the circumference minus equal gaps.
 */
export default function RatioRing({ competence, character, label }: Props) {
  const root = useRef<HTMLDivElement>(null);
  const [pinned, setPinned] = useState<Key | null>(null);
  const [hover, setHover] = useState<Key | null>(null);
  const active = hover ?? pinned;
  const names = { competence, character };

  useEffect(() => {
    const el = root.current;
    if (!el || !motionEnabled()) return;
    const { gsap } = ensureGsap();
    const ctx = gsap.context(() => {
      const q = (s: string) => el.querySelectorAll<SVGElement | HTMLElement>(s);
      const setCount = (key: Key, v: number) =>
        el.querySelectorAll<HTMLElement>(`[data-count='${key}']`).forEach((n) => (n.textContent = String(Math.round(v))));
      const counts = { competence: 0, character: 0 };

      const tl = gsap.timeline({
        defaults: { ease: "power2.inOut" },
        scrollTrigger: { trigger: el, start: "top 82%", end: "center 48%", scrub: 1 },
      });
      tl.fromTo(q(".ring-frame"), { strokeDashoffset: 1, opacity: 0 }, { strokeDashoffset: 0, opacity: 1, duration: 1, stagger: 0.15 })
        .fromTo(q(".ring-ticks"), { rotate: -40, opacity: 0, svgOrigin: "140 140" }, { rotate: 0, opacity: 1, duration: 1.4 }, 0)
        .fromTo(q(".arc-competence"), { strokeDasharray: `0 ${C}` }, { strokeDasharray: `${LEN.competence} ${C}`, duration: 1.2 }, 0.5)
        .fromTo(counts, { competence: 0 }, { competence: 30, duration: 1.2, onUpdate: () => setCount("competence", counts.competence) }, 0.5)
        .fromTo(q("[data-ring-item='competence']"), { opacity: 0, x: 24 }, { opacity: 1, x: 0, duration: 0.8 }, 0.7)
        .fromTo(q(".arc-character"), { strokeDasharray: `0 ${C}` }, { strokeDasharray: `${LEN.character} ${C}`, duration: 1.8 }, 1.3)
        .fromTo(counts, { character: 0 }, { character: 70, duration: 1.8, onUpdate: () => setCount("character", counts.character) }, 1.3)
        .fromTo(q("[data-ring-item='character']"), { opacity: 0, x: 24 }, { opacity: 1, x: 0, duration: 0.8 }, 1.7)
        .fromTo(q(".ring-center"), { opacity: 0, scale: 0.85 }, { opacity: 1, scale: 1, duration: 1 }, 1.4);
    }, el);
    return () => ctx.revert();
  }, []);

  const toggle = (k: Key) => setPinned((p) => (p === k ? null : k));
  const center: Key = active ?? "character";

  const arc = (k: Key, color: string) => (
    <g className="ring-seg" data-seg={k}>
      {/* glow copy */}
      <circle
        className={`arc-${k} ring-glow`}
        cx="140"
        cy="140"
        r={R}
        fill="none"
        stroke={color}
        strokeWidth="14"
        strokeDasharray={`${LEN[k]} ${C}`}
        strokeDashoffset={OFFSET[k]}
        filter="url(#ring-blur)"
      />
      <circle
        className={`arc-${k} ring-arc`}
        cx="140"
        cy="140"
        r={R}
        fill="none"
        stroke={color}
        strokeDasharray={`${LEN[k]} ${C}`}
        strokeDashoffset={OFFSET[k]}
      />
    </g>
  );

  return (
    <div ref={root} className="ratio-ring grid items-center gap-10 sm:grid-cols-[minmax(0,340px)_1fr]" data-active={active ?? "none"}>
      <figure className="relative mx-auto aspect-square w-full max-w-[340px]" role="img" aria-label={label}>
        <svg viewBox="0 0 280 280" className="h-full w-full -rotate-90 overflow-visible" aria-hidden="true">
          <defs>
            <filter id="ring-blur" x="-20%" y="-20%" width="140%" height="140%">
              <feGaussianBlur stdDeviation="6" />
            </filter>
          </defs>
          {/* outer tick ring */}
          <g className="ring-ticks">
            {Array.from({ length: 60 }, (_, i) => {
              const a = (i / 60) * Math.PI * 2;
              const r1 = 136;
              const r2 = i % 5 === 0 ? 131 : 133.5;
              return (
                <line
                  key={i}
                  x1={140 + Math.cos(a) * r1}
                  y1={140 + Math.sin(a) * r1}
                  x2={140 + Math.cos(a) * r2}
                  y2={140 + Math.sin(a) * r2}
                  stroke="rgb(216 194 140 / 0.35)"
                  strokeWidth={i % 5 === 0 ? 1 : 0.6}
                />
              );
            })}
          </g>
          {/* frame + track */}
          <circle className="ring-frame" cx="140" cy="140" r="102" fill="none" stroke="rgb(255 255 255 / 0.12)" strokeWidth="0.75" pathLength={1} strokeDasharray="1" />
          <circle className="ring-frame" cx="140" cy="140" r={R} fill="none" stroke="rgb(255 255 255 / 0.07)" strokeWidth="14" pathLength={1} strokeDasharray="1" />
          {arc("competence", "var(--color-ivory)")}
          {arc("character", "var(--color-gold)")}
        </svg>

        {/* centre read-out: follows the active segment, defaults to 70% Character */}
        <div className="ring-center absolute inset-0 flex items-center justify-center text-center" aria-hidden="true">
          {(["competence", "character"] as const).map((k) => (
            <div key={k} className={`ring-readout absolute flex flex-col items-center ${center === k ? "is-on" : ""}`}>
              <span className={`display text-6xl sm:text-7xl ${k === "competence" ? "text-ivory" : "text-white"}`}>
                <span data-count={k}>{VALUE[k]}</span>%
              </span>
              <span className="mt-1 text-[0.7rem] font-semibold uppercase tracking-[0.28em] text-gold-light">{names[k]}</span>
            </div>
          ))}
        </div>
      </figure>

      <div className="grid grid-cols-2 gap-4 sm:grid-cols-1" role="group" aria-label={label}>
        {(["competence", "character"] as const).map((k) => (
          <button
            key={k}
            type="button"
            data-ring-item={k}
            aria-pressed={pinned === k}
            onClick={() => toggle(k)}
            onPointerEnter={(e) => e.pointerType === "mouse" && setHover(k)}
            onPointerLeave={() => setHover(null)}
            onFocus={(e) => e.currentTarget.matches(":focus-visible") && setHover(k)}
            onBlur={() => setHover(null)}
            className={`ring-item ring-item-${k} group relative border-l-2 py-3 pl-5 pr-4 text-left`}
          >
            <span className="block text-[0.72rem] font-semibold uppercase tracking-[0.24em] text-white/70 transition-colors duration-500 group-hover:text-white">
              {names[k]}
            </span>
            <span className={`ring-value display mt-1 block text-5xl ${k === "competence" ? "text-ivory" : "text-gold"}`}>
              <span data-count={k}>{VALUE[k]}</span>%
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}
