"use client";

import React, { useEffect, useState } from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";

// Helper function to hex to RGB (basic fallback for dynamic colors)
function hexToRgb(hex: string) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
    const [mounted, setMounted] = useState(false);

    useEffect(() => {
        // In production, this would be an API call dynamically fetching the authenticated user's company settings
        const companyTheme = {
            brand_colors: {
                primary: "#2563eb", // Deep blue - could be anything from API
            }
        };

        if (companyTheme?.brand_colors?.primary) {
            // Inject the company's vibrant custom primary color directly into the CSSOM
            document.documentElement.style.setProperty("--dynamic-primary", companyTheme.brand_colors.primary);

            const rgb = hexToRgb(companyTheme.brand_colors.primary);
            if (rgb) {
                document.documentElement.style.setProperty("--dynamic-primary-rgb", `${rgb.r}, ${rgb.g}, ${rgb.b}`);
            }
        }

        setMounted(true);
    }, []);

    // Prevent hydration mismatch
    if (!mounted) {
        return <>{children}</>;
    }

    return (
        <NextThemesProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
        >
            {children}
        </NextThemesProvider>
    );
}
