'use client';

import { useEffect } from 'react';
import { useAppEnv } from '@/lib/env-store';

function hexToHSL(hex: string): string {
  const r = parseInt(hex.slice(1, 3), 16) / 255;
  const g = parseInt(hex.slice(3, 5), 16) / 255;
  const b = parseInt(hex.slice(5, 7), 16) / 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h = 0;
  let s = 0;
  const l = (max + min) / 2;

  if (max !== min) {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
      case g: h = ((b - r) / d + 2) / 6; break;
      case b: h = ((r - g) / d + 4) / 6; break;
    }
  }

  return `${Math.round(h * 360)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
}

export function useApplyEnv() {
  const env = useAppEnv();

  useEffect(() => {
    const root = document.documentElement;

    // Apply primary color as HSL CSS variable for shadcn compatibility
    const primaryHSL = hexToHSL(env.primaryColor);
    root.style.setProperty('--primary', primaryHSL);
    root.style.setProperty('--ring', primaryHSL);

    // Compute foreground based on luminance
    const r = parseInt(env.primaryColor.slice(1, 3), 16);
    const g = parseInt(env.primaryColor.slice(3, 5), 16);
    const b = parseInt(env.primaryColor.slice(5, 7), 16);
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    const foreground = luminance > 0.5 ? '0 0% 0%' : '0 0% 100%';
    root.style.setProperty('--primary-foreground', foreground);

    // Apply accent color
    const accentHSL = hexToHSL(env.accentColor);
    root.style.setProperty('--accent', accentHSL);

    // Store gradient values as custom properties for components to use
    root.style.setProperty('--app-gradient-from', env.gradientFrom);
    root.style.setProperty('--app-gradient-to', env.gradientTo);
    root.style.setProperty('--app-primary', env.primaryColor);
    root.style.setProperty('--app-primary-hover', env.primaryHover);
    root.style.setProperty('--app-accent', env.accentColor);

  }, [env.primaryColor, env.primaryHover, env.accentColor, env.gradientFrom, env.gradientTo]);
}
