import { useEffect } from 'react';
import { rommApiClient } from '../api/client';
import { pause, resume } from '@noriginmedia/norigin-spatial-navigation';

interface EmulatorPlayerProps {
  romId: string; // Kept for Save uploading
  romUrl: string; // Exact static asset URL
  platformSlug: string;
  core?: string;
  saveId?: number;
  stateId?: number;
  onClose: () => void;
}

export const EmulatorPlayer = ({ romId, romUrl, platformSlug, core, saveId, stateId, onClose }: EmulatorPlayerProps) => {
  useEffect(() => {
    // 1. Pause spatial navigation
    pause();

    // 2. Listen for messages from the iframe
    const handleMessage = async (event: MessageEvent) => {
      if (event.data.type === 'EJS_SAVE') {
        try {
          const blob = new Blob([event.data.data], { type: 'application/octet-stream' });
          await rommApiClient.uploadSave(romId, blob, core || 'default');
        } catch (err) {
          console.error('EmulatorJS: Failed to upload save to RomM:', err);
        }
      } else if (event.data.type === 'EJS_EXIT') {
        onClose();
      } else if (event.data.type === 'EJS_ERROR') {
        console.error('EmulatorJS: Error from iframe:', event.data.error);
      }
    };

    window.addEventListener('message', handleMessage);

    return () => {
      window.removeEventListener('message', handleMessage);
      resume();
    };
  }, [romId, platformSlug, core, saveId, stateId, onClose]);

  const coreMapping: Record<string, string> = {
    'nes': 'fceumm',
    'nintendo-entertainment-system': 'fceumm',
    'snes': 'snes9x',
    'super-nintendo-entertainment-system': 'snes9x',
    'gb': 'gambatte',
    'game-boy': 'gambatte',
    'gbc': 'gambatte',
    'game-boy-color': 'gambatte',
    'gba': 'mgba',
    'game-boy-advance': 'mgba',
    'nds': 'desmume2015',
    'nintendo-ds': 'desmume2015',
    'nintendo-dsi': 'desmume2015',
    
    // Sega Systems
    'genesis': 'genesis_plus_gx',
    'megadrive': 'genesis_plus_gx',
    'sega-genesis': 'genesis_plus_gx',
    'sega-mega-drive': 'genesis_plus_gx',
    'mega-drive': 'genesis_plus_gx',
    'smd': 'genesis_plus_gx',
    'sms': 'genesis_plus_gx',
    'sega-master-system': 'genesis_plus_gx',
    'master-system': 'genesis_plus_gx',
    'gg': 'genesis_plus_gx',
    'game-gear': 'genesis_plus_gx',
    'sega-game-gear': 'genesis_plus_gx',
    'sega-cd': 'genesis_plus_gx',
    'mega-cd': 'genesis_plus_gx',
    'sega-32x': 'picodrive',
    '32x': 'picodrive',
    'sega-cd-32x': 'picodrive',
    'mega-cd-32x': 'picodrive',
    'saturn': 'yabause',
    'sega-saturn': 'yabause',
    'sg-1000': 'genesis_plus_gx',
    'sg1000': 'genesis_plus_gx',

    // Nintendo / NEC / Others
    'n64': 'mupen64plus_next',
    'nintendo-64': 'mupen64plus_next',
    'virtual-boy': 'mednafen_vb',
    'virtualboy': 'mednafen_vb',
    'vb': 'mednafen_vb',
    'turbografx-16': 'mednafen_pce_fast',
    'turbografx': 'mednafen_pce_fast',
    'tg16': 'mednafen_pce_fast',
    'pc-engine': 'mednafen_pce_fast',
    'pce': 'mednafen_pce_fast',
    'pc-engine-cd': 'mednafen_pce_fast',
    
    // Sony
    'psx': 'pcsx_rearmed',
    'playstation': 'pcsx_rearmed',
    'sony-playstation': 'pcsx_rearmed',
    'psp': 'ppsspp',
    'playstation-portable': 'ppsspp',
    'sony-playstation-portable': 'ppsspp',
    
    // Panasonic / 3DO
    '3do': 'opera',
    '3do-interactive-multiplayer': 'opera',
    
    // Atari
    'atari-2600': 'stella2014',
    'atari-5200': 'a5200',
    'atari-7800': 'prosystem',
    'jaguar': 'virtualjaguar',
    'atari-jaguar': 'virtualjaguar',
    'lynx': 'handy',
    'atari-lynx': 'handy',
    
    // Misc
    'arcade': 'mame2003_plus',
    'mame': 'mame2003_plus',
    'neogeo': 'fbneo',
    'neo-geo': 'fbneo',
    'colecovision': 'gearcoleco',
    'vectrex': 'vecx',
    'msx': 'fmsx',
    'msx1': 'fmsx',
    'msx2': 'fmsx',
    'neo-geo-pocket': 'mednafen_ngp',
    'ngp': 'mednafen_ngp',
    'neo-geo-pocket-color': 'mednafen_ngp',
    'ngpc': 'mednafen_ngp',
    'odyssey-2': 'o2em',
    'odyssey2': 'o2em',
    'videopac': 'o2em'
  };
  const activeCore = core || coreMapping[platformSlug] || 'default';

  // Map slugs to exactly match the generated bios/XXXX.zip names
  const biosFolderMapping: Record<string, string> = {
    '3do': '3do',
    '3do-interactive-multiplayer': '3do',
    'saturn': 'saturn',
    'sega-saturn': 'saturn',
    'sega-cd': 'segacd',
    'mega-cd': 'segacd',
    'sega-cd-32x': 'segacd',
    'mega-cd-32x': 'segacd',
    'turbografx-cd': 'turbografx-cd',
    'pc-engine-cd': 'turbografx-cd',
    'psx': 'psx',
    'playstation': 'psx',
    'sony-playstation': 'psx',
    'ps2': 'ps2',
    'psp': 'psp',
    'playstation-portable': 'psp',
    'sony-playstation-portable': 'psp',
    'gba': 'gba',
    'game-boy-advance': 'gba',
    'nds': 'nds',
    'nintendo-ds': 'nds',
    'nintendo-dsi': 'nintendo-dsi',
    'msx': 'msx',
    'msx1': 'msx',
    'msx2': 'msx',
    'amiga': 'amiga',
    'jaguar': 'jaguar',
    'atari-jaguar': 'jaguar',
    'odyssey-2': 'odyssey-2',
    'odyssey2': 'odyssey-2',
    'videopac': 'odyssey-2',
    'colecovision': 'colecovision',
    'fds': 'fds',
    'neogeoaes': 'neogeoaes',
    'neogeo': 'arcade', // Fallback for neogeo.zip
    'neo-geo': 'arcade',
    'arcade': 'arcade',
    'dc': 'dc'
  };
  const activeBios = biosFolderMapping[platformSlug];

  const config = {
    windowNum: 1,
    language: 'en-US',
    showControls: true,
    showMenu: true,
    allowFullscreen: true,
    screenshot: true,
    cache: false,
    gameUrl: romUrl,
    gameId: romId,
    system: activeCore,
    core: activeCore,
    dataPath: '/emu/',
    ...(activeBios && { biosUrl: `/bios/${activeBios}.zip` }),
    ...(saveId && { loadSaveUrl: rommApiClient.getSaveFileUrl(saveId) }),
    ...(stateId && { loadStateUrl: rommApiClient.getStateFileUrl(stateId) }),
  };

  const iframeSrc = `/emulator.html?v=${Date.now()}#${encodeURIComponent(JSON.stringify(config))}`;

  return (
    <div className="w-full h-full bg-black relative">
      <iframe 
        src={iframeSrc}
        className="w-full h-full border-0"
        allow="autoplay; fullscreen; cross-origin-isolated"
      />
      
      {/* Fallback exit button */}
      <button 
        onClick={onClose}
        className="absolute top-4 right-4 z-[300] w-10 h-10 flex items-center justify-center rounded-full bg-black/50 text-white/50 hover:bg-red-500 hover:text-white transition-all opacity-0 hover:opacity-100"
      >
        <span className="material-symbols-outlined">close</span>
      </button>
    </div>
  );
};
