"use client";
import type React from "react";
import { useState, useRef, useEffect } from "react";

interface AdaptiveTextProps {
  children: React.ReactNode;
  className?: string;
}

export function AdaptiveText({ children, className = "" }: AdaptiveTextProps) {
  const textRef = useRef<HTMLDivElement | null>(null);
  const [textColor, setTextColor] = useState("text-white");

  useEffect(() => {
    if (!textRef.current) return;

    const updateTextColor = () => {
      const element = textRef.current;
      if (!element) return;

      // Get background color by creating a temporary element
      const tempElement = document.createElement("div");
      tempElement.style.position = "absolute";
      tempElement.style.height = "100%";
      tempElement.style.width = "100%";
      tempElement.style.top = "0";
      tempElement.style.left = "0";
      tempElement.style.pointerEvents = "none";
      tempElement.style.zIndex = "-1";

      // Insert the temp element as a sibling
      if (element.parentNode) {
        element.parentNode.insertBefore(tempElement, element);
      }

      // Get computed background color
      const bgColor = window.getComputedStyle(tempElement).backgroundColor;

      // Clean up
      if (tempElement.parentNode) {
        tempElement.parentNode.removeChild(tempElement);
      }

      // Parse RGB values
      const rgbMatch = bgColor.match(
        /rgba?$$(\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?$$/
      );

      if (rgbMatch) {
        const [, r, g, b] = rgbMatch.map(Number);

        // Calculate relative luminance (per WCAG)
        if (r && g && b) {
          const luminance =
            0.2126 * (r / 255) + 0.7152 * (g / 255) + 0.0722 * (b / 255);

          // Use white text on dark backgrounds, black text on light backgrounds
          setTextColor(luminance < 0.5 ? "text-white" : "text-black");
        }
      }
    };

    // Initial update
    updateTextColor();

    const observer = new MutationObserver(updateTextColor);

    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["class", "data-theme"],
    });

    window.addEventListener("resize", updateTextColor);

    return () => {
      observer.disconnect();
      window.removeEventListener("resize", updateTextColor);
    };
  }, []);

  return (
    <span ref={textRef} className={`${textColor} ${className}`}>
      {children}
    </span>
  );
}
