import {StrictMode} from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { secureDecrypt, secureEncrypt } from './lib/security';
import { safeB64Decode, safeJsonParse } from './lib/mysqlSync';
import { initPrismaSync } from './lib/prismaSync';

// Initialize initializing flag and initial sync status to prevent initial empty-state writes from overriding cPanel MySQL database
if (typeof window !== 'undefined') {
  (window as any).__ECLASS_INITIALIZING__ = true;
  (window as any).__ECLASS_INITIAL_SYNC_DONE__ = false;
}

// --- Intercept localStorage changes to dispatch global eclass-data-changed custom events and maintain write timestamps ---
const originalSetItem = localStorage.setItem.bind(localStorage);
(localStorage as any).__originalSetItem = originalSetItem;

localStorage.setItem = function (key: string, value: string) {
  try {
    originalSetItem(key, value);
  } catch (e) {
    Storage.prototype.setItem.call(localStorage, key, value);
  }
  
  if (key.startsWith('eclass_') && 
      key !== 'eclass_sync_timestamps' && 
      key !== 'eclass_mysql_sync_cache' && 
      key !== 'eclass_mysql_sync_config' &&
      key !== 'eclass_is_clearing_data_flag') {
    try {
      const tsKey = 'eclass_sync_timestamps';
      const saved = localStorage.getItem(tsKey);
      const timestamps = saved ? safeJsonParse(saved, {}) : {};
      timestamps[key] = Date.now();
      try {
        originalSetItem(tsKey, JSON.stringify(timestamps));
      } catch (err) {
        Storage.prototype.setItem.call(localStorage, tsKey, JSON.stringify(timestamps));
      }
    } catch (e) {
      // ignore
    }
  }

  window.dispatchEvent(new CustomEvent('eclass-data-changed', { detail: { key, value } }));
};

const originalRemoveItem = localStorage.removeItem.bind(localStorage);
(localStorage as any).__originalRemoveItem = originalRemoveItem;

localStorage.removeItem = function (key: string) {
  try {
    originalRemoveItem(key);
  } catch (e) {
    Storage.prototype.removeItem.call(localStorage, key);
  }

  if (key.startsWith('eclass_') && 
      key !== 'eclass_sync_timestamps' && 
      key !== 'eclass_mysql_sync_cache' && 
      key !== 'eclass_mysql_sync_config' &&
      key !== 'eclass_is_clearing_data_flag') {
    try {
      const tsKey = 'eclass_sync_timestamps';
      const saved = localStorage.getItem(tsKey);
      const timestamps = saved ? safeJsonParse(saved, {}) : {};
      timestamps[key] = Date.now();
      try {
        originalSetItem(tsKey, JSON.stringify(timestamps));
      } catch (err) {
        Storage.prototype.setItem.call(localStorage, tsKey, JSON.stringify(timestamps));
      }
    } catch (e) {
      // ignore
    }
  }

  window.dispatchEvent(new CustomEvent('eclass-data-changed', { detail: { key, value: null } }));
};

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
);
