"use client";

import { useTheme } from "next-themes";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/shared/lib/utils";

/**
 * Sun↔Moon morphing toggle.
 *
 * One single SVG. On click it immediately spins 360°, and mid-spin
 * the sun circle morphs into a crescent (via sliding SVG mask) while
 * the rays retract with staggered timing. Everything is one fluid motion.
 *
 * Inverted logic: dark → shows sun, light → shows moon.
 */
export function ThemeToggle() {
  const { resolvedTheme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const svgRef = useRef<SVGSVGElement>(null);

  useEffect(() => setMounted(true), []);

  if (!mounted) {
    return <div className="h-9 w-9 rounded-xl bg-muted" />;
  }

  const isDark = resolvedTheme === "dark";
  // Inverted: dark → sun (action: go light), light → moon (action: go dark)
  const showSun = isDark;

  const handleClick = () => {
    // Trigger spin via Web Animations API — instant, no state re-render needed
    svgRef.current?.animate(
      [
        { transform: "rotate(0deg) scale(1)" },
        { transform: "rotate(180deg) scale(1.12)", offset: 0.5 },
        { transform: "rotate(360deg) scale(1)" },
      ],
      { duration: 550, easing: "cubic-bezier(0.4, 0, 0.2, 1)" },
    );
    setTheme(isDark ? "light" : "dark");
  };

  // Ray endpoints — 8 rays at 45° intervals
  const rays = [0, 45, 90, 135, 180, 225, 270, 315].map((deg) => {
    const r = (deg * Math.PI) / 180;
    return {
      x1: 12 + 6.5 * Math.cos(r),
      y1: 12 + 6.5 * Math.sin(r),
      x2: 12 + 9 * Math.cos(r),
      y2: 12 + 9 * Math.sin(r),
    };
  });

  const ease = "cubic-bezier(0.4, 0, 0.2, 1)";
  const dur = "500ms";

  return (
    <button
      type="button"
      aria-label={isDark ? "Treci la modul luminos" : "Treci la modul intunecat"}
      onClick={handleClick}
      className={cn(
        "relative flex h-9 w-9 items-center justify-center rounded-xl",
        "transition-colors duration-200 hover:bg-accent/60",
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
      )}
    >
      <svg
        ref={svgRef}
        viewBox="0 0 24 24"
        fill="none"
        className="h-[22px] w-[22px]"
      >
        <defs>
          <mask id="theme-mask">
            <rect width="24" height="24" fill="white" />
            {/* Slides in to carve the crescent; slides out to reveal full circle */}
            <circle
              r="6.5"
              fill="black"
              cx={showSun ? 28 : 16}
              cy={showSun ? 2 : 6}
              style={{ transition: `cx ${dur} ${ease}, cy ${dur} ${ease}` }}
            />
          </mask>
        </defs>

        {/* Main body — full sun circle that morphs into crescent moon */}
        <circle
          cx="12"
          cy="12"
          r={showSun ? 4.5 : 5.5}
          fill="currentColor"
          mask="url(#theme-mask)"
          className={showSun ? "text-amber-400" : "text-slate-400 dark:text-indigo-300"}
          style={{ transition: `r ${dur} ${ease}, color ${dur}` }}
        />

        {/* Sun rays — retract into center when moon */}
        <g
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          className={showSun ? "text-amber-400" : "text-slate-400 dark:text-indigo-300"}
          style={{
            transition: `opacity 300ms ${ease}, color ${dur}`,
            opacity: showSun ? 1 : 0,
          }}
        >
          {rays.map((ray, i) => (
            <line
              key={i}
              x1={showSun ? ray.x1 : 12}
              y1={showSun ? ray.y1 : 12}
              x2={showSun ? ray.x2 : 12}
              y2={showSun ? ray.y2 : 12}
              style={{
                transition: [
                  `x1 ${dur} ${ease} ${i * 20}ms`,
                  `y1 ${dur} ${ease} ${i * 20}ms`,
                  `x2 ${dur} ${ease} ${i * 20}ms`,
                  `y2 ${dur} ${ease} ${i * 20}ms`,
                ].join(", "),
              }}
            />
          ))}
        </g>
      </svg>
    </button>
  );
}
