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';

/** 
 * AD CONFIG 
 * These slots use your Google Ad Manager / AdX network ID: /23334523022/
 */
const MANUAL_ADS = {
  HOME_TOP: `
    <script>
  atOptions = {
    'key' : 'b084a53d6ed1bca9f483cb9df1699418',
    'format' : 'iframe',
    'height' : 250,
    'width' : 300,
    'params' : {}
  };
</script>

  `,
  HOME_BOTTOM: `
   <script>
  atOptions = {
    'key' : 'e9f9e9ee3581ae64403537299789af15',
    'format' : 'iframe',
    'height' : 50,
    'width' : 320,
    'params' : {}
  };
</script>

  `,
  PLAYER_TOP: `
    <script>
  atOptions = {
    'key' : 'b084a53d6ed1bca9f483cb9df1699418',
    'format' : 'iframe',
    'height' : 250,
    'width' : 300,
    'params' : {}
  };
</script>

  `,
  PLAYER_BOTTOM: `
    <script>
  atOptions = {
    'key' : 'e9f9e9ee3581ae64403537299789af15',
    'format' : 'iframe',
    'height' : 50,
    'width' : 320,
    'params' : {}
  };
</script>

  `,
  PAUSE_AD: `
    <script>
  atOptions = {
    'key' : '3579a0e58978879606a308d956094d4e',
    'format' : 'iframe',
    'height' : 300,
    'width' : 160,
    'params' : {}
  };
</script>

  `,
  INTERSTITIAL: `
    <script>
  atOptions = {
    'key' : '3579a0e58978879606a308d956094d4e',
    'format' : 'iframe',
    'height' : 300,
    'width' : 160,
    'params' : {}
  };
</script>

  `,
};

const AdSpace = ({ id, htmlContent }) => {
  const containerRef = useRef(null);
  useEffect(() => {
    if (!containerRef.current || !htmlContent) return;
    containerRef.current.innerHTML = '';
    const range = document.createRange();
    range.selectNode(containerRef.current);
    const fragment = range.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">SPONSORED</div>
      <div ref={containerRef} id={id} className="w-full flex items-center justify-center min-h-[250px]" />
    </div>
  );
};

const InterstitialOverlay = ({ onComplete }) => {
  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]);

  // 'absolute inset-0' combined with being a child of 'cinema-wrapper' 
  // ensures this shows on top of the video even in Fullscreen mode.
  return (
    <div className="absolute inset-0 z-[999999] bg-[#020617] flex flex-col items-center justify-center p-6 animate-in fade-in duration-500 overflow-hidden">
      <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">
          <p className="text-white/60 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 INITIAL_AD_DELAY_MS = 10000;    
  const RECURRING_AD_INTERVAL_MS = 300000; // EXACTLY 5 MINUTES (300,000ms)

  const [urlInput, setUrlInput] = useState('');
  const [isActive, setIsActive] = useState(false);
  const [embedUrl, setEmbedUrl] = useState('');
  const [isPaused, setIsPaused] = useState(false);
  const [showInterstitial, setShowInterstitial] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [viewCount, setViewCount] = useState(Math.floor(Math.random() * 500) + 1200);

  const lastAdTimestamp = useRef(Date.now());
  const initialAdDone = useRef(false);

  const cleanUrl = useCallback((u) => {
    let t = u.trim();
    if (t.includes('mega.nz/file/')) return t.replace('mega.nz/file/', 'mega.nz/embed/');
    if (t.includes('mega.nz/#!')) return t.replace('mega.nz/#!', 'mega.nz/embed/').replace('!', '#');
    if (t.includes('mega.io/file/')) return 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);
      }
    };
    handleHash();
    window.addEventListener('hashchange', handleHash);
    return () => window.removeEventListener('hashchange', handleHash);
  }, [cleanUrl]);

  // THE RECURRING AD ENGINE
  useEffect(() => {
    const heartbeat = setInterval(() => {
      const now = Date.now();
      const elapsed = now - lastAdTimestamp.current;

      // Rule 1: First ad after 10 seconds of usage
      if (!initialAdDone.current && elapsed >= INITIAL_AD_DELAY_MS) {
        setShowInterstitial(true);
        initialAdDone.current = true;
        lastAdTimestamp.current = now; 
      }

      // Rule 2: Recurring ad every 5 minutes (300,000ms)
      if (initialAdDone.current && elapsed >= RECURRING_AD_INTERVAL_MS) {
        setShowInterstitial(true);
        lastAdTimestamp.current = now; 
      }
    }, 1000);

    return () => clearInterval(heartbeat);
  }, []);

  useEffect(() => {
    const timer = setInterval(() => {
      setViewCount(prev => prev + (Math.random() > 0.5 ? 1 : -1));
    }, 3000);
    return () => clearInterval(timer);
  }, []);

  const handleLaunch = () => {
    if (!urlInput) return;
    window.location.hash = urlInput;
  };

  const handleShare = () => {
    const shareUrl = window.location.href;
    navigator.clipboard.writeText(shareUrl).then(() => {
      setShowToast(true);
      setTimeout(() => setShowToast(false), 2000);
    });
  };

  const toggleFullscreen = () => {
    const fsContainer = document.getElementById('cinema-wrapper');
    if (fsContainer) {
      if (!document.fullscreenElement) {
        fsContainer.requestFullscreen().catch(err => console.error(err));
      } else {
        document.exitFullscreen();
      }
    }
  };

  const handleAdComplete = useCallback(() => {
    setShowInterstitial(false);
  }, []);

  if (!isActive) {
    return (
      <div id="cinema-wrapper" className="min-h-screen flex flex-col bg-[#020617] relative overflow-hidden">
        <header className="sticky top-0 z-[100] 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">
            <div className="flex items-center gap-4">
              <div className="w-10 h-10 bg-red-600 rounded-xl flex items-center justify-center shadow-lg shadow-red-600/30">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="white"><polygon points="5 3 19 12 5 21 5 3"/></svg>
              </div>
              <h1 className="text-xl md:text-2xl font-black tracking-tighter uppercase italic">Mega<span className="text-red-600">Stream</span></h1>
            </div>
          </div>
        </header>
        <main className="flex-1 max-w-7xl mx-auto w-full px-4 py-12 flex flex-col items-center">
          <AdSpace id="ad-home-top" htmlContent={MANUAL_ADS.HOME_TOP} />
          <div className="text-center mb-12 animate-in">
            <h1 className="text-4xl md:text-8xl font-black tracking-tighter italic leading-[1.1] mb-6">Bypass everything.<br/><span className="text-red-600">watch anything</span></h1>
            <h2 className="text-xl md:text-4xl font-bold tracking-tight italic leading-[1.3] text-white/90 max-w-4xl mx-auto">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-[2.5rem] border border-white/10 shadow-2xl mb-16">
            <input type="text" value={urlInput} onChange={(e) => setUrlInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleLaunch()} placeholder="Paste your mega.nz video link here..." className="flex-1 px-8 py-6 bg-transparent text-lg text-white outline-none font-bold" />
            <button onClick={handleLaunch} className="px-12 py-6 bg-red-600 hover:bg-red-700 text-white rounded-[2rem] font-black uppercase text-xs tracking-widest transition-all shadow-xl shadow-red-600/30">Launch Stream</button>
          </div>
          <AdSpace id="ad-home-bottom" htmlContent={MANUAL_ADS.HOME_BOTTOM} />
        </main>
        {/* Ad Overlay rendered as child of cinema-wrapper for Fullscreen coverage */}
        {showInterstitial && <InterstitialOverlay onComplete={handleAdComplete} />}
      </div>
    );
  }

  return (
    <div id="cinema-wrapper" className="min-h-screen flex flex-col bg-[#020617] relative overflow-hidden">
      {showToast && (
        <div className="fixed top-24 left-1/2 -translate-x-1/2 z-[1000] bg-red-600 text-white px-8 py-3 rounded-full text-xs font-black tracking-widest uppercase shadow-2xl animate-in fade-in slide-in-from-top-4">
          URL Copied to Clipboard
        </div>
      )}

      <header className="px-8 py-6 border-b border-white/5 relative z-10">
        <div className="max-w-7xl mx-auto flex justify-between items-center">
          <div onClick={() => { window.location.hash = ''; setIsActive(false); }} className="flex items-center gap-4 cursor-pointer group">
            <div className="w-10 h-10 bg-red-600 rounded-xl flex items-center justify-center transition-transform group-hover:scale-110">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="white"><polygon points="5 3 19 12 5 21 5 3"/></svg>
            </div>
            <h1 className="text-xl font-black uppercase italic">Mega<span className="text-red-600">Stream</span></h1>
          </div>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2 px-4 py-2 bg-red-600/10 border border-red-600/20 rounded-full">
              <span className="w-2 h-2 bg-red-600 rounded-full animate-pulse"></span>
              <span className="text-[10px] font-black uppercase tracking-widest text-red-500">{viewCount.toLocaleString()} WATCHING NOW</span>
            </div>
          </div>
        </div>
      </header>

      <main className="flex-1 max-w-6xl mx-auto w-full px-4 py-8 relative z-10">
        <AdSpace id="ad-player-top" htmlContent={MANUAL_ADS.PLAYER_TOP} />
        
        <div id="player-container" className="relative group bg-black rounded-[2rem] overflow-hidden shadow-2xl border border-white/10">
          <div className="aspect-video relative">
            <iframe 
              src={embedUrl} 
              className={`w-full h-full transition-all duration-700 ${isPaused ? 'opacity-20 blur-2xl scale-110' : 'opacity-100'}`} 
              allowFullScreen 
              allow="autoplay; encrypted-media"
              sandbox="allow-scripts allow-same-origin allow-forms allow-presentation"
            ></iframe>
            
            {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-14 py-5 bg-red-600 text-white rounded-3xl font-black uppercase tracking-[0.2em] text-[11px] hover:scale-105 transition-all shadow-2xl shadow-red-600/40">Resume Stream</button>
              </div>
            )}
          </div>
        </div>

        <div className="mt-8 flex flex-col md:flex-row md:items-center justify-between gap-6 p-8 bg-white/5 border border-white/10 rounded-[2.5rem] shadow-xl">
          <div className="flex items-center gap-6">
            <button 
              onClick={() => setIsPaused(!isPaused)} 
              className={`w-14 h-14 rounded-2xl flex items-center justify-center transition-all ${isPaused ? 'bg-white text-black' : 'bg-red-600 text-white'}`}
            >
              {isPaused ? 
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> : 
                <svg width="24" height="24" 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-sm tracking-widest mb-1 italic">Stream Gateway Active</h4>
              <p className="text-slate-500 text-[10px] font-bold uppercase tracking-widest">Premium Node • Encryption 256-Bit</p>
            </div>
          </div>
          
          <div className="flex flex-wrap items-center gap-3">
            <button 
              onClick={handleShare}
              className="px-8 py-4 bg-white/5 hover:bg-white/10 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest transition-all border border-white/10 flex items-center gap-3"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
              Share Link
            </button>
            <button 
              onClick={toggleFullscreen}
              className="w-12 h-12 flex items-center justify-center bg-white/5 hover:bg-white/10 text-white rounded-2xl transition-all border border-white/10"
              title="Toggle Fullscreen"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><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>
            <button 
              onClick={() => { setIsActive(false); window.location.hash = ''; }}
              className="px-8 py-4 bg-slate-800 hover:bg-slate-700 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest transition-all border border-white/10"
            >
              New Link
            </button>
          </div>
        </div>

        <AdSpace id="ad-player-bottom" htmlContent={MANUAL_ADS.PLAYER_BOTTOM} />
      </main>
      
      <footer className="py-12 border-t border-white/5 mt-auto opacity-20 relative z-10">
        <div className="max-w-7xl mx-auto px-6 text-center text-[9px] font-black uppercase tracking-[0.5em] text-slate-500">
           © 2026 MegaStream - Premium Subdomain Node Infrastructure
        </div>
      </footer>

      {/* Ad Overlay rendered as the absolute LAST child of cinema-wrapper */}
      {showInterstitial && <InterstitialOverlay onComplete={handleAdComplete} />}
    </div>
  );
};

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