"use client";
// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.

import React, { createContext, useContext, useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';

type Theme = 'dark' | 'light';
type Currency = 'Rp' | 'USD' | 'Crypto';
type Locale = 'id' | 'en';

interface OmniContextProps {
  theme: Theme;
  setTheme: (t: Theme) => void;
  currency: Currency;
  setCurrency: (c: Currency) => void;
  locale: Locale;
  setLocale: (l: Locale) => void;
}

const OmniContext = createContext<OmniContextProps | null>(null);

export const useOmni = () => {
  const ctx = useContext(OmniContext);
  if (!ctx) throw new Error("useOmni must be used within OmniSyncProvider");
  return ctx;
};

export function OmniSyncProvider({ children, initialLocale }: { children: React.ReactNode, initialLocale: Locale }) {
  const [theme, setThemeState] = useState<Theme>(() => {
    if (typeof window === 'undefined') return 'dark';
    const value = `; ${document.cookie}`;
    const parts = value.split(`; omni_theme=`);
    if (parts.length === 2) return (parts.pop()?.split(';').shift() as Theme) || 'dark';
    return 'dark';
  });
  const [currency, setCurrencyState] = useState<Currency>(() => {
    if (typeof window === 'undefined') return 'Rp';
    const value = `; ${document.cookie}`;
    const parts = value.split(`; omni_currency=`);
    if (parts.length === 2) return (parts.pop()?.split(';').shift() as Currency) || 'Rp';
    return 'Rp';
  });
  const [locale, setLocaleState] = useState<Locale>(initialLocale);
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  const setCookie = (name: string, value: string) => {
    const host = window.location.hostname;
    const cookieDomain = process.env.NEXT_PUBLIC_COOKIE_DOMAIN || (host === 'localhost' || host === '127.0.0.1' ? host : `.${host}`);
    document.cookie = `${name}=${value}; path=/; domain=${cookieDomain}; max-age=31536000`;
    // For local dev fallback
    if (window.location.hostname === 'localhost') {
      document.cookie = `${name}=${value}; path=/; max-age=31536000`;
    }
  };

  const setTheme = (t: Theme) => {
    setThemeState(t);
    setCookie('omni_theme', t);
    document.documentElement.setAttribute('data-theme', t);
    if (channel) channel.postMessage({ type: 'SYNC_THEME', payload: t });
  };

  const setCurrency = (c: Currency) => {
    setCurrencyState(c);
    setCookie('omni_currency', c);
    if (channel) channel.postMessage({ type: 'SYNC_CURRENCY', payload: c });
  };

  const setLocale = (l: Locale) => {
    setLocaleState(l);
    setCookie('NEXT_LOCALE', l); // next-intl standard cookie
    if (channel) channel.postMessage({ type: 'SYNC_LOCALE', payload: l });
  };

  // Broadcast Channel for Cross-Tab Sync
  const [channel] = useState<BroadcastChannel | null>(() => typeof window !== 'undefined' ? new BroadcastChannel('omni_sync_channel') : null);

  useEffect(() => {
    if (channel) {
      const handleMessage = (event: MessageEvent) => {
        const { type, payload } = event.data;
        if (type === 'SYNC_THEME') {
          setThemeState(payload);
          document.documentElement.setAttribute('data-theme', payload);
        }
        if (type === 'SYNC_CURRENCY') {
          setCurrencyState(payload);
        }
        if (type === 'SYNC_LOCALE') {
          setLocaleState(payload);
        }
      };
      channel.addEventListener('message', handleMessage);
      return () => {
        channel.removeEventListener('message', handleMessage);
      };
    }
  }, [channel, pathname, router]);

  return (
    <OmniContext.Provider value={{ theme, setTheme, currency, setCurrency, locale, setLocale }}>
      {children}
    </OmniContext.Provider>
  );
}
