'use client';

import { useEffect, useRef } from 'react';

const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1';
const POLL_INTERVAL = 30_000;

interface ThemeColors {
  '--primary': string;
  '--primary-foreground': string;
  '--background': string;
  '--card': string;
  '--error': string;
  '--success': string;
  '--warning': string;
  '--muted': string;
  '--border': string;
  '--sidebar-bg': string;
  '--sidebar-text': string;
  '--sidebar-active': string;
  '--text': string;
}

interface ThemeResponse {
  themeId?: string;
  theme?: {
    primaryColor?: string;
    colors?: ThemeColors;
    fonts?: { heading: string; body: string; importUrl?: string };
    isDark?: boolean;
  };
}

let currentThemeId: string | null = null;

function applyTheme(data: ThemeResponse) {
  if (!data.themeId || data.themeId === currentThemeId) return;
  currentThemeId = data.themeId;

  const root = document.documentElement;
  const theme = data.theme;
  if (!theme) return;

  // Apply all 13 CSS variables
  if (theme.colors) {
    for (const [key, value] of Object.entries(theme.colors)) {
      root.style.setProperty(key, value);
      const tailwindKey = `--color-${key.slice(2)}`;
      root.style.setProperty(tailwindKey, value);
    }
  } else if (theme.primaryColor) {
    // Fallback: at least set primary color
    root.style.setProperty('--color-primary', theme.primaryColor);
  }

  // Apply fonts
  if (theme.fonts) {
    root.style.setProperty('--font-heading', theme.fonts.heading);
    root.style.setProperty('--font-body', theme.fonts.body);
    document.body.style.fontFamily = `${theme.fonts.body}, system-ui, -apple-system, sans-serif`;

    if (theme.fonts.importUrl) {
      const existingLink = document.getElementById('theme-font-link');
      if (existingLink) existingLink.remove();

      const link = document.createElement('link');
      link.id = 'theme-font-link';
      link.rel = 'stylesheet';
      link.href = theme.fonts.importUrl;
      document.head.appendChild(link);
    }
  }

  root.dataset.theme = data.themeId;
  root.dataset.dark = theme.isDark ? 'true' : 'false';
}

/**
 * Lightweight theme sync for the landing page.
 * Fetches the active theme from the API and applies all CSS variables.
 * Polls every 30s for changes.
 */
export function ThemeSync() {
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    const syncTheme = async () => {
      try {
        const res = await fetch(`${API_BASE}/theme/current`, { cache: 'no-store' });
        if (!res.ok) return;
        const data = (await res.json()) as ThemeResponse;
        applyTheme(data);
      } catch {
        // Silently fail — LP works fine with default colors
      }
    };

    void syncTheme();
    pollRef.current = setInterval(() => void syncTheme(), POLL_INTERVAL);

    return () => {
      if (pollRef.current) clearInterval(pollRef.current);
    };
  }, []);

  return null;
}
