"use client";

import { useEffect, useState } from 'react';

export function ColorProvider({ children }: { children: React.ReactNode }) {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    loadPrimaryColor();
  }, []);

  const loadPrimaryColor = async () => {
    try {
      const response = await fetch('/api/config');
      if (response.ok) {
        const data = await response.json();
        if (data.primaryColor) {
          applyPrimaryColor(data.primaryColor);
        }
      }
    } catch (error) {
      console.error('Erro ao carregar cor primária:', error);
    }
  };

  const applyPrimaryColor = (color: string) => {
    // Converte hex para RGB
    const r = parseInt(color.slice(1, 3), 16);
    const g = parseInt(color.slice(3, 5), 16);
    const b = parseInt(color.slice(5, 7), 16);

    // Define as CSS variables
    document.documentElement.style.setProperty('--color-primary-rgb', `${r} ${g} ${b}`);
    document.documentElement.style.setProperty('--color-primary', color);
  };

  if (!mounted) {
    return <>{children}</>;
  }

  return <>{children}</>;
}
