// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { createContext, useContext, useState, useEffect, useRef } from 'react';

const CommercialContext = createContext();

export function useCommercial() {
  return useContext(CommercialContext);
}

export function CommercialProvider({ children }) {
  const [activeCurrency, setActiveCurrency] = useState('IDR'); // 'IDR', 'USD', 'BTC'

  // Asumsi Kurs Lintas Dimensi (Hardcoded for Zero Dependency speed)
  const EXCHANGE_RATES = {
    IDR: 1,
    USD: 16000, 
    BTC: 1000000000 
  };

  const formatDynamicCurrency = (basePriceIDR) => {
    if (activeCurrency === 'IDR') {
      return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 0
      }).format(basePriceIDR);
    }
    
    if (activeCurrency === 'USD') {
      const converted = basePriceIDR / EXCHANGE_RATES.USD;
      return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2
      }).format(converted);
    }

    if (activeCurrency === 'BTC') {
      const converted = basePriceIDR / EXCHANGE_RATES.BTC;
      return `₿ ${converted.toFixed(6)}`;
    }
  };

  const defaultTiers = [
    {
      id: 'tier_perintis',
      name: 'PAKET PERINTIS',
      price: 1500000, // Rp 1.500.000
      description: 'Akses infrastruktur dasar XCU Ultra untuk bisnis rintisan.',
      modules: ['m1', 'm2', 'm3', 'm4', 'm5', 'm17', 'm20', 'm21', 'm23', 'm29', 'm30']
    },
    {
      id: 'tier_korporat',
      name: 'PAKET KORPORAT',
      price: 7500000, // Rp 7.500.000
      description: 'Kendali mutlak atas Sub-Core Alpha & Beta untuk skalabilitas Enterprise.',
      // Generate m1 to m40
      modules: Array.from({length: 40}, (_, i) => 'm' + (i + 1))
    },
    {
      id: 'tier_kuantum',
      name: 'PAKET KUANTUM',
      price: 25000000, // Rp 25.000.000
      description: 'Dominasi absolut. Membuka seluruh 99 Modul lintas-dimensi.',
      // Generate m1 to m99
      modules: Array.from({length: 99}, (_, i) => 'm' + (i + 1))
    },
    {
      id: 'tier_jumpa_omni',
      name: 'JUMPA.ID OMNI-ENGINE',
      price: 50000000, // Rp 50.000.000
      description: 'Suntikan Sidecar mutlak untuk integrasi JC & JVC tanpa merombak server awal. Murni 99 Modul Kuantum.',
      modules: Array.from({length: 99}, (_, i) => 'm' + (i + 1))
    }
  ];

  const savedTiers = localStorage.getItem('xcu_commercial_tiers');
  let initialTiers = savedTiers ? JSON.parse(savedTiers) : defaultTiers;
  // Auto-inject missing JUMPA.ID OMNI-ENGINE if older localStorage is used
  if (!initialTiers.find(t => t.id === 'tier_jumpa_omni')) {
    const omniTier = defaultTiers.find(t => t.id === 'tier_jumpa_omni');
    if (omniTier) initialTiers.push(omniTier);
  }
  const [tiers, setTiers] = useState(initialTiers);

  const defaultModulePrices = {};
  for (let i = 1; i <= 99; i++) {
    defaultModulePrices[`m${i}`] = 1500000;
  }
  
  const savedModulePrices = localStorage.getItem('xcu_module_prices');
  const [modulePrices, setModulePrices] = useState(savedModulePrices ? JSON.parse(savedModulePrices) : defaultModulePrices);

  const savedTaxRate = localStorage.getItem('xcu_tax_rate');
  const [taxRate, setTaxRate] = useState(savedTaxRate ? Number(savedTaxRate) : 11); // Default 11%

  const defaultGateways = {
    stripe: true,
    xendit: true,
    crypto: true,
    unionpay: true,
    bank_transfer: true,
    cash_manual: true
  };
  const savedGateways = localStorage.getItem('xcu_active_gateways');
  const [activeGateways, setActiveGateways] = useState(savedGateways ? JSON.parse(savedGateways) : defaultGateways);

  const wsRef = useRef(null);
  const isIncomingSync = useRef(false);

  // Initialize XCU Omni-Relay (WebSocket Pub/Sub)
  useEffect(() => {
    const relayUrl = import.meta.env.VITE_OMNI_RELAY_WS_URL || 'ws://localhost:4000';
    const ws = new WebSocket(relayUrl);
    wsRef.current = ws;

    ws.onopen = () => {
      console.log('[XCU COMMAND] Connected to Omni-Relay Server.');
    };

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'SYNC_STATE') {
          console.log('[XCU COMMAND] Quantum Sync Received from Relay.');
          isIncomingSync.current = true;
          
          if (data.payload.tiers) {
            setTiers(data.payload.tiers);
          }
          if (data.payload.modulePrices) {
            setModulePrices(data.payload.modulePrices);
          }
          if (data.payload.taxRate !== undefined) {
            setTaxRate(data.payload.taxRate);
          }
          if (data.payload.activeGateways) {
            setActiveGateways(data.payload.activeGateways);
          }

          // Reset lock after React state flush
          setTimeout(() => {
            isIncomingSync.current = false;
          }, 100);
        }
      } catch (e) {
        console.error('Failed to parse WebSocket message:', e);
      }
    };

    ws.onclose = () => {
      console.log('[XCU COMMAND] Omni-Relay Disconnected.');
    };

    return () => {
      if (ws.readyState === 1) ws.close();
    };
  }, []);

  useEffect(() => {
    localStorage.setItem('xcu_commercial_tiers', JSON.stringify(tiers));
    
    // Broadcast mutation to Omni-Relay if it wasn't triggered by an incoming sync
    if (!isIncomingSync.current && wsRef.current?.readyState === 1) {
      wsRef.current.send(JSON.stringify({
        type: 'UPDATE_PRICING',
        payload: { tiers }
      }));
    }
  }, [tiers]);

  useEffect(() => {
    localStorage.setItem('xcu_module_prices', JSON.stringify(modulePrices));
    
    // Broadcast mutation to Omni-Relay if it wasn't triggered by an incoming sync
    if (!isIncomingSync.current && wsRef.current?.readyState === 1) {
      wsRef.current.send(JSON.stringify({
        type: 'UPDATE_PRICING',
        payload: { modulePrices }
      }));
    }
  }, [modulePrices]);

  useEffect(() => {
    localStorage.setItem('xcu_tax_rate', String(taxRate));
    if (!isIncomingSync.current && wsRef.current?.readyState === 1) {
      wsRef.current.send(JSON.stringify({
        type: 'UPDATE_PRICING',
        payload: { taxRate }
      }));
    }
  }, [taxRate]);

  useEffect(() => {
    localStorage.setItem('xcu_active_gateways', JSON.stringify(activeGateways));
    if (!isIncomingSync.current && wsRef.current?.readyState === 1) {
      wsRef.current.send(JSON.stringify({
        type: 'UPDATE_PRICING',
        payload: { activeGateways }
      }));
    }
  }, [activeGateways]);

  // LIVE CROSS-TAB SYNCHRONIZATION PROTOCOL (Fallback for Local Storage)
  useEffect(() => {
    const syncAcrossTabs = (e) => {
      if (e.key === 'xcu_commercial_tiers' && e.newValue) {
        isIncomingSync.current = true;
        setTiers(JSON.parse(e.newValue));
        setTimeout(() => isIncomingSync.current = false, 100);
      }
      if (e.key === 'xcu_module_prices' && e.newValue) {
        isIncomingSync.current = true;
        setModulePrices(JSON.parse(e.newValue));
        setTimeout(() => isIncomingSync.current = false, 100);
      }
      if (e.key === 'xcu_tax_rate' && e.newValue) {
        isIncomingSync.current = true;
        setTaxRate(Number(e.newValue));
        setTimeout(() => isIncomingSync.current = false, 100);
      }
      if (e.key === 'xcu_active_gateways' && e.newValue) {
        isIncomingSync.current = true;
        setActiveGateways(JSON.parse(e.newValue));
        setTimeout(() => isIncomingSync.current = false, 100);
      }
    };
    
    window.addEventListener('storage', syncAcrossTabs);
    return () => window.removeEventListener('storage', syncAcrossTabs);
  }, []);

  const updateModulePrice = (modId, newPrice) => {
    setModulePrices(prev => ({
      ...prev,
      [modId]: Number(newPrice)
    }));
  };

  const value = {
    tiers,
    setTiers,
    modulePrices,
    updateModulePrice,
    taxRate,
    setTaxRate,
    activeGateways,
    setActiveGateways,
    activeCurrency,
    setActiveCurrency,
    formatDynamicCurrency
  };

  return (
    <CommercialContext.Provider value={value}>
      {children}
    </CommercialContext.Provider>
  );
}
