import { createRoot } from 'react-dom/client';
import { App } from './components/App';
import { Storage } from './Storage';
import { $appSettings } from './stores/appSettings';
import { setShaderCode } from './stores/shader';
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts';

// Load initial state from storage
const savedSettings = Storage.getSettings();
$appSettings.set(savedSettings);

// Load URL hash if present
function loadFromURL() {
  if (window.location.hash) {
    try {
      const hash = window.location.hash.substring(1);
      console.log('Loading from URL hash:', hash);

      const decoded = atob(hash);
      console.log('Decoded data:', decoded);

      try {
        const shareData = JSON.parse(decoded);
        console.log('Parsed share data:', shareData);

        if (shareData.code) {
          setShaderCode(shareData.code);
        }

        $appSettings.set({
          resolution: shareData.resolution || savedSettings.resolution,
          fps: shareData.fps || savedSettings.fps,
          renderMode: shareData.renderMode || savedSettings.renderMode,
          valueMode: shareData.valueMode || savedSettings.valueMode,
          uiOpacity:
            shareData.uiOpacity !== undefined
              ? shareData.uiOpacity
              : savedSettings.uiOpacity,
          hueShift:
            shareData.hueShift !== undefined
              ? shareData.hueShift
              : savedSettings.hueShift,
        });

        console.log('Settings updated from URL');
      } catch (jsonError) {
        console.log('JSON parse failed, falling back to old format');
        // Fall back to old format (just code as string)
        setShaderCode(decoded);
      }
    } catch (e) {
      console.error('Failed to decode URL hash:', e);
    }
  } else {
    // Load last shader code if no URL hash
    setShaderCode(savedSettings.lastShaderCode ?? 'x^y');
  }
}

// Main App component that includes keyboard shortcuts
function AppWithShortcuts() {
  useKeyboardShortcuts();
  return <App />;
}

// Set up hash change listener
window.addEventListener('hashchange', loadFromURL);

// Initialize the app
loadFromURL();

// Mount React app
const container = document.getElementById('app');
if (!container) {
  // Create app container if it doesn't exist
  const appDiv = document.createElement('div');
  appDiv.id = 'app';
  document.body.appendChild(appDiv);
}

const root = createRoot(container || document.getElementById('app')!);
root.render(<AppWithShortcuts />);
