import React, { useState, useEffect, useCallback, useRef } from 'https://esm.sh/react@19.0.0';
import { createRoot } from 'https://esm.sh/react-dom@19.0.0/client';

const MANUAL_ADS = {
  HOME_TOP: `<div id='div-gpt-ad-home-top-inner' style='min-width: 250px; min-height: 250px;'><script>googletag.cmd.push(function() { googletag.defineSlot('/23334523022/megastream_ad/home_top_leaderboard', [[336, 280], [250, 250], [300, 600], [300, 250], 'fluid'], 'div-gpt-ad-home-top-inner').addService(googletag.pubads()); googletag.display('div-gpt-ad-home-top-inner'); });</script></div>`,
  HOME_BOTTOM: `<div id='div-gpt-ad-home-bottom-inner' style='min-width: 250px; min-height: 250px;'><script>googletag.cmd.push(function() { googletag.defineSlot('/23334523022/megastream_ad/home_bottom', [[300, 600], [250, 250], [300, 250], [336, 280], 'fluid'], 'div-gpt-ad-home-bottom-inner').addService(googletag.pubads()); googletag.display('div-gpt-ad-home-bottom-inner'); });</script></div>`,
  PLAYER_TOP: `<div id='div-gpt-ad-player-top' style='min-width: 250px; min-height: 250px;'><script>googletag.cmd.push(function() { googletag.defineSlot('/23334523022/megastream_ad/player_top_leaderboard', [[300, 600], 'fluid', [250, 250], [300, 250], [336, 280]], 'div-gpt-ad-player-top').addService(googletag.pubads()); googletag.display('div-gpt-ad-player-top'); });</script></div>`,
  PLAYER_BOTTOM: `<div id='div-gpt-ad-player-bottom' style='min-width: 250px; min-height: 250px;'><script>googletag.cmd.push(function() { googletag.defineSlot('/23334523022/megastream_ad/player_bottom_responsive', [[250, 250], [300, 600], [300, 250], [336, 280], 'fluid'], 'div-gpt-ad-player-bottom').addService(googletag.pubads()); googletag.display('div-gpt-ad-player-bottom'); });</script></div>`,
  PAUSE_AD: `<div id='div-gpt-ad-pause' style='min-width: 250px; min-height: 250px;'><script>googletag.cmd.push(function() { googletag.defineSlot('/23334523022/megastream_ad/pause_overlay_banner', [[336, 280], [250, 250], [300, 600], [300, 250], 'fluid'], 'div-gpt-ad-pause').addService(googletag.pubads()); googletag.display('div-gpt-ad-pause'); });</script></div>`,
  INTERSTITIAL: `<div id='div-gpt-ad-interstitial' style='min-width: 250px; min-height: 250px;'><script>googletag.cmd.push(function() { googletag.defineSlot('/23334523022/megastream_ad/interstitial_popup', [[300, 600], 'fluid', [250, 250], [300, 250], [336, 280]], 'div-gpt-ad-interstitial').addService(googletag.pubads()); googletag.display('div-gpt-ad-interstitial'); });</script></div>`,
};

const AdSpace = ({ id, htmlContent }) => {
  const containerRef = useRef(null);
  useEffect(() => {
    if (!containerRef.current || !htmlContent) return;
    containerRef.current.innerHTML = '';
    const fragment = document.createRange().createContextualFragment(htmlContent);
    containerRef.current.appendChild(fragment);
  }, [htmlContent]);
  return (
    <div className="w-full flex flex-col items-center justify-center my-4">
      <div className="text-[8px] uppercase tracking-[0.4em] text-white/20 font-black mb-2 text-center">SPONSORED</div>
      <div ref={containerRef} id={id} className="w-full flex items-center justify-center min-h-[250px]" />
    </div>
  );
};

const InterstitialOverlay = ({ onComplete, isFullPage }) => {
  const [timer, setTimer] = useState(10); 
  useEffect(() => {
    const interval = setInterval(() => {
      setTimer((p) => { if (p <= 1) { onComplete(); return 0; } return p - 1; });
    }, 1000);
    return () => clearInterval(interval);
  }, [onComplete]);

  const classes = isFullPage 
    ? "fixed inset-0 z-[1000000] bg-[#020617] flex flex-col items-center justify-center p-6" 
    : "absolute inset-0 z-[999999] bg-[#020617] flex flex-col items-center justify-center p-6";

  return (
    <div className={classes}>
      <div className="max-w-2xl w-full text-center space-y-8">
        <div className="inline-flex items-center gap-3 px-6 py-3 bg-red-600/10 border border-red-600/20 rounded-full text-red-500 text-[10px] font-black uppercase tracking-[0.4em]">ADVERTISING BREAK</div>
        <AdSpace id="ad-interstitial-render" htmlContent={MANUAL_ADS.INTERSTITIAL} />
        <div className="flex flex-col items-center gap-4 text-white">
          <p className="text-lg font-medium italic">Your stream resumes in <span className="text-red-600 font-black">{timer}s</span></p>
          <div className="w-48 h-1 bg-white/5 rounded-full overflow-hidden">
            <div className="h-full bg-red-600 transition-all duration-1000 linear" style={{ width: `${(timer / 10) * 100}%` }}></div>
          </div>
        </div>
      </div>
    </div>
  );
};

const App = () => {
  const RECURRING_AD_INTERVAL_MS = 300000;
  const [urlInput, setUrlInput] = useState('');
  const [isActive, setIsActive] = useState(false);
  const [embedUrl, setEmbedUrl] = useState('');
  const [isPaused, setIsPaused] = useState(false);
  const [showInterstitial, setShowInterstitial] = useState(false);
  const [isFullPageAd, setIsFullPageAd] = useState(false);
  const [isStreamReady, setIsStreamReady] = useState(false);
  const [viewCount, setViewCount] = useState(Math.floor(Math.random() * 500) + 1200);
  const [liked, setLiked] = useState(false);
  const lastAdTimestamp = useRef(Date.now());
  const initialAdDone = useRef(false);

  const cleanUrl = useCallback((u) => {
    let t = u.trim();
    if (t.includes('mega.nz/file/')) t = t.replace('mega.nz/file/', 'mega.nz/embed/');
    if (t.includes('mega.nz/#!')) t = t.replace('mega.nz/#!', 'mega.nz/embed/').replace('!', '#');
    if (t.includes('mega.io/file/')) t = t.replace('mega.io/file/', 'mega.io/embed/');
    return t;
  }, []);

  useEffect(() => {
    const handleHash = () => {
      const hash = window.location.hash.substring(1);
      if (hash && (hash.includes('mega.nz') || hash.includes('mega.io'))) {
        setEmbedUrl(cleanUrl(hash));
        setIsActive(true);
      } else { setIsActive(false); setIsStreamReady(false); }
    };
    handleHash();
    window.addEventListener('hashchange', handleHash);
    return () => window.removeEventListener('hashchange', handleHash);
  }, [cleanUrl]);

  useEffect(() => {
    const heartbeat = setInterval(() => {
      const now = Date.now();
      const elapsed = now - lastAdTimestamp.current;
      if (!initialAdDone.current && elapsed >= 10000) {
        setIsFullPageAd(true);
        setShowInterstitial(true);
        initialAdDone.current = true;
        lastAdTimestamp.current = now;
      } else if (initialAdDone.current && elapsed >= RECURRING_AD_INTERVAL_MS) {
        setIsFullPageAd(false);
        setShowInterstitial(true);
        lastAdTimestamp.current = now;
        if (window.googletag?.pubads) { googletag.cmd.push(() => googletag.pubads().refresh()); }
      }
    }, 1000);
    return () => clearInterval(heartbeat);
  }, []);

  const toggleFullscreen = () => {
    const container = document.getElementById('player-container');
    if (!document.fullscreenElement) {
        container.requestFullscreen().catch(() => {
            const frame = document.querySelector('iframe');
            if (frame?.webkitEnterFullscreen) frame.webkitEnterFullscreen();
        });
    } else { document.exitFullscreen(); }
  };

  if (!isActive) {
    return (
      <div id="cinema-wrapper" className="min-h-screen flex flex-col bg-[#020617] text-white">
        <header className="sticky top-0 z-[100] px-6 md:px-8 py-6 bg-[#020617]/95 border-b border-white/5 backdrop-blur-xl">
          <div className="max-w-7xl mx-auto flex justify-between items-center text-white">
            <h1 className="text-xl md:text-2xl font-black uppercase italic text-white">Mega<span className="text-red-600">Stream</span></h1>
          </div>
        </header>
        <main className="flex-1 max-w-7xl mx-auto w-full px-4 py-8 flex flex-col items-center">
          <AdSpace id="ad-home-top" htmlContent={MANUAL_ADS.HOME_TOP} />
          <div className="text-center mb-10">
            <h1 className="text-4xl md:text-8xl font-black tracking-tighter italic leading-[1.1] mb-6 uppercase text-white">Bypass everything.<br/><span className="text-red-600">watch anything</span></h1>
            <h2 className="text-lg md:text-4xl font-bold tracking-tight italic leading-[1.3] text-white/90 max-w-4xl mx-auto px-4">Stream movies and series directly on one screen. Zero ads. Zero redirection. Just pure viewing.</h2>
          </div>
          <div className="w-full max-w-4xl flex flex-col md:flex-row gap-3 p-2 bg-white/5 rounded-[1.5rem] md:rounded-[2.5rem] border border-white/10 shadow-2xl mb-12">
            <input type="text" value={urlInput} onChange={(e) => setUrlInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && (window.location.hash = urlInput)} placeholder="Paste your mega.nz video link here..." className="flex-1 px-6 md:px-8 py-4 md:py-6 bg-transparent text-base md:text-lg text-white outline-none font-bold" />
            <button onClick={() => window.location.hash = urlInput} className="px-8 md:px-12 py-4 md:py-6 bg-red-600 hover:bg-red-700 text-white rounded-[1rem] md:rounded-[2rem] font-black uppercase text-xs tracking-widest transition-all">Launch Stream</button>
          </div>
          <AdSpace id="ad-home-bottom" htmlContent={MANUAL_ADS.HOME_BOTTOM} />
        </main>
        {showInterstitial && isFullPageAd && <InterstitialOverlay isFullPage={true} onComplete={() => setShowInterstitial(false)} />}
      </div>
    );
  }

  return (
    <div id="cinema-wrapper" className="min-h-screen flex flex-col bg-[#020617] relative">
      <header className="px-6 md:px-8 py-6 border-b border-white/5 relative z-10 flex justify-between items-center text-white">
        <div onClick={() => window.location.hash = ''} className="flex items-center gap-3 cursor-pointer">
          <div className="w-8 h-8 md:w-10 md:h-10 bg-red-600 rounded-xl flex items-center justify-center"><svg width="18" height="18" viewBox="0 0 24 24" fill="white"><polygon points="5 3 19 12 5 21 5 3"/></svg></div>
          <h1 className="text-lg md:text-xl font-black uppercase italic text-white">MegaStream</h1>
        </div>
        <div className="px-3 py-1.5 bg-red-600/10 border border-red-600/20 rounded-full text-red-500 font-black text-[9px] md:text-[10px]">
          {viewCount.toLocaleString()} WATCHING
        </div>
      </header>

      <main className="flex-1 max-w-6xl mx-auto w-full px-2 md:px-4 py-4 md:py-8 relative z-10 text-white">
        <AdSpace id="ad-player-top" htmlContent={MANUAL_ADS.PLAYER_TOP} />
        
        <div id="player-container" className="relative aspect-video bg-black rounded-xl md:rounded-[2rem] overflow-hidden shadow-2xl border border-white/10 group">
          {isStreamReady ? (
            <iframe 
                src={embedUrl} 
                className={`w-full h-full transition-all duration-700 ${isPaused ? 'opacity-20 blur-2xl' : 'opacity-100'}`} 
                allowFullScreen 
                /* 100% IPHONE FIX: These flags are required to allow Mega decryptor to work inside a sandbox */
                sandbox="allow-scripts allow-same-origin allow-forms allow-presentation allow-storage-access-by-user-activation allow-downloads"
                allow="autoplay; fullscreen; encrypted-media; picture-in-picture"
                referrerPolicy="no-referrer"
                frameBorder="0"
            ></iframe>
          ) : (
            <div className="absolute inset-0 flex flex-col items-center justify-center bg-[#020617] p-8 text-center space-y-6">
                <div className="w-20 h-20 bg-red-600 rounded-full flex items-center justify-center animate-pulse shadow-2xl shadow-red-600/40">
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="white"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                </div>
                <div className="space-y-2">
                    <h3 className="text-xl font-black uppercase italic tracking-tighter">Ready to Stream</h3>
                    <p className="text-white/40 text-[10px] font-black uppercase tracking-[0.2em]">Satisfy security node initialization</p>
                </div>
                <button 
                    onClick={() => setIsStreamReady(true)}
                    className="px-12 py-5 bg-red-600 text-white rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl active:scale-95 transition-all"
                >
                    Start Stream
                </button>
            </div>
          )}

          <button onClick={toggleFullscreen} className="absolute bottom-4 right-4 z-[70] w-10 h-10 bg-black/60 backdrop-blur-md rounded-lg flex items-center justify-center text-white border border-white/20 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-all shadow-xl">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>
          </button>
            
          {isPaused && (
            <div className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/60 backdrop-blur-md">
              <AdSpace id="ad-pause" htmlContent={MANUAL_ADS.PAUSE_AD} />
              <button onClick={() => setIsPaused(false)} className="px-10 md:px-14 py-4 md:py-5 bg-red-600 text-white rounded-2xl md:rounded-3xl font-black uppercase text-[10px] md:text-[11px]">Resume</button>
            </div>
          )}

          {showInterstitial && !isFullPageAd && <InterstitialOverlay isFullPage={false} onComplete={() => setShowInterstitial(false)} />}
        </div>

        <div className="mt-6 md:mt-8 flex flex-col md:flex-row items-center justify-between gap-4 md:gap-6 p-6 md:p-8 bg-white/5 border border-white/10 rounded-[1.5rem] md:rounded-[2.5rem] text-white">
          <div className="flex items-center gap-4 md:gap-6 w-full md:w-auto">
            <button onClick={() => setIsPaused(!isPaused)} className={`w-12 h-12 md:w-14 md:h-14 rounded-xl md:rounded-2xl flex items-center justify-center transition-all ${isPaused ? 'bg-white text-black' : 'bg-red-600 text-white'}`}>
              {isPaused ? <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> : <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>}
            </button>
            <div>
              <h4 className="text-white font-black uppercase text-xs md:text-sm tracking-widest italic">Stream Active</h4>
              <p className="text-slate-500 text-[9px] md:text-[10px] font-bold uppercase tracking-widest italic">Encrypted 256-Bit Node</p>
            </div>
          </div>
          <div className="flex items-center gap-3 w-full md:w-auto text-white">
            <button onClick={() => setLiked(!liked)} className={`flex-1 md:flex-none px-6 md:px-8 py-3 md:py-4 rounded-xl md:rounded-2xl font-black uppercase text-[10px] tracking-widest border flex items-center justify-center gap-3 ${liked ? 'bg-red-600 text-white border-red-600' : 'bg-white/5 border-white/10 text-white'}`}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill={liked ? "currentColor" : "none"} stroke="currentColor" strokeWidth="3"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
                {liked ? 'Liked' : 'Like'}
            </button>
            <button onClick={() => { navigator.clipboard.writeText(window.location.href); }} className="flex-1 md:flex-none px-6 md:px-8 py-3 md:py-4 bg-white/5 border border-white/10 text-white rounded-xl md:rounded-2xl font-black uppercase text-[10px] tracking-widest flex items-center justify-center gap-3 text-white">Share</button>
          </div>
        </div>
        <AdSpace id="ad-player-bottom" htmlContent={MANUAL_ADS.PLAYER_BOTTOM} />
      </main>

      {showInterstitial && isFullPageAd && <InterstitialOverlay isFullPage={true} onComplete={() => setShowInterstitial(false)} />}
    </div>
  );
};

const rootElement = document.getElementById('root');
if (rootElement) { createRoot(rootElement).render(<App />); }