/* ============================================================
   <ThemeTogglerButton /> — animated light↔dark toggle.

   Uses View Transitions API where available for a circular sweep
   from the click point. Falls back to an instant switch otherwise.
   ============================================================ */

function ThemeTogglerButton({ size = "default", modes = ["light", "dark"] }) {
  const [theme, setTheme] = React.useState(() => {
    if (typeof document === "undefined") return "light";
    return document.documentElement.getAttribute("data-theme") || "light";
  });

  // Sync attribute on first mount.
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("innoveev:theme", theme); } catch {}
  }, [theme]);

  const cycle = (e) => {
    const idx = modes.indexOf(theme);
    const next = modes[(idx + 1) % modes.length];

    const apply = () => setTheme(next);

    // No View Transitions support → instant switch.
    if (!document.startViewTransition) {
      apply();
      return;
    }

    const rect = e.currentTarget.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top  + rect.height / 2;
    const radius = Math.hypot(
      Math.max(cx, window.innerWidth - cx),
      Math.max(cy, window.innerHeight - cy)
    );

    const transition = document.startViewTransition(apply);

    transition.ready.then(() => {
      document.documentElement.animate(
        {
          clipPath: [
            `circle(0px at ${cx}px ${cy}px)`,
            `circle(${radius}px at ${cx}px ${cy}px)`,
          ],
        },
        {
          duration: 700,
          easing: "cubic-bezier(0.22, 1, 0.36, 1)",
          pseudoElement: "::view-transition-new(root)",
        }
      );
    });
  };

  const isDark = theme === "dark";

  return (
    <button
      type="button"
      className={`theme-toggle theme-toggle--${size} ${isDark ? "is-dark" : "is-light"}`}
      onClick={cycle}
      aria-label={`Switch to ${isDark ? "light" : "dark"} mode`}
      data-cursor={isDark ? "Light mode" : "Dark mode"}
    >
      <span className="theme-toggle__icons" aria-hidden="true">
        {/* Sun */}
        <svg className="theme-toggle__sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="4"/>
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
        </svg>
        {/* Moon */}
        <svg className="theme-toggle__moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
        </svg>
      </span>
    </button>
  );
}

window.ThemeTogglerButton = ThemeTogglerButton;
