"use client";
import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ArrowUpRight, Maximize2, X, RefreshCw, Monitor, Tablet, Smartphone } from "lucide-react";

const ZYPHRON_URL = "https://zyphron.cloud/";

const HIGHLIGHTS = [
  { label: "Game Hosting", href: "https://zyphron.cloud/" },
  { label: "Minecraft", href: "https://zyphron.cloud/" },
  { label: "FiveM", href: "https://zyphron.cloud/" },
  { label: "VPS", href: "https://zyphron.cloud/" },
  { label: "VDS", href: "https://zyphron.cloud/" },
  { label: "Web Hosting", href: "https://zyphron.cloud/" },
  { label: "Bot Hosting", href: "https://zyphron.cloud/" },
  { label: "Domains", href: "https://zyphron.cloud/" },
  { label: "Cloud Infrastructure", href: "https://zyphron.cloud/" },
];

type Device = "desktop" | "tablet" | "mobile";

export default function LiveZyphronPreview() {
  const [device, setDevice] = useState<Device>("desktop");
  const [fullscreen, setFullscreen] = useState(false);
  const [iframeKey, setIframeKey] = useState(0);
  const [blocked, setBlocked] = useState(false);
  const iframeRef = useRef<HTMLIFrameElement>(null);

  // Detect iframe blocking: if after 4s iframe not loaded or error, fallback
  useEffect(() => {
    const t = setTimeout(() => {
      try {
        const el = iframeRef.current;
        if (!el) return;
        // Try accessing contentWindow; if blocked, will throw but not reliable for X-Frame
        // Instead check if iframe has zero size or hasn't fired load
        // We treat as not blocked by default since headers allowed it
      } catch {}
    }, 4000);
    return () => clearTimeout(t);
  }, [iframeKey]);

  useEffect(() => {
    if (!fullscreen) return;
    const onEsc = (e: KeyboardEvent) => { if (e.key === "Escape") setFullscreen(false); };
    window.addEventListener("keydown", onEsc);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onEsc); document.body.style.overflow = ""; };
  }, [fullscreen]);

  const widthMap: Record<Device, string> = {
    desktop: "w-full",
    tablet: "w-[768px] max-w-full",
    mobile: "w-[390px] max-w-full",
  };
  const heightMap: Record<Device, string> = {
    desktop: "h-[520px] sm:h-[650px]",
    tablet: "h-[900px]",
    mobile: "h-[844px]",
  };

  const BrowserChrome = ({ onFullscreen, onRefresh }: { onFullscreen?: () => void; onRefresh?: () => void }) => (
    <div className="flex items-center justify-between gap-3 px-3 sm:px-4 py-3 bg-[#0e1118] border-b border-white/10 rounded-t-[18px]">
      <div className="flex items-center gap-1.5 shrink-0">
        <span className="w-3 h-3 rounded-full bg-red-500/90 border border-red-600/30" />
        <span className="w-3 h-3 rounded-full bg-yellow-500/90 border border-yellow-600/30" />
        <span className="w-3 h-3 rounded-full bg-green-500/90 border border-green-600/30" />
      </div>
      <div className="flex-1 flex justify-center min-w-0">
        <div className="flex items-center gap-2 bg-black/40 border border-white/10 rounded-full px-3 py-1.5 max-w-[280px] sm:max-w-[360px] w-full">
          <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse shrink-0" />
          <span className="text-[11px] sm:text-[12px] tracking-tight text-white/60 truncate">https://zyphron.cloud</span>
          <span className="ml-auto hidden sm:inline text-[10px] tracking-widest text-white/20">SECURE</span>
        </div>
      </div>
      <div className="flex items-center gap-1.5 shrink-0">
        {onRefresh && <button aria-label="Refresh preview" onClick={onRefresh} className="w-7 h-7 rounded-full bg-white/5 border border-white/10 grid place-items-center text-white/60 hover:text-white hover:bg-white/10"><RefreshCw size={12} /></button>}
        <a href={ZYPHRON_URL} target="_blank" rel="noopener noreferrer" aria-label="Open Zyphron Cloud in new tab" className="hidden sm:inline-flex items-center gap-1 text-[12px] font-medium text-white/70 hover:text-white border border-white/10 rounded-full px-3 py-1.5 bg-white/5">Open <ArrowUpRight size={12} /></a>
        {onFullscreen && <button aria-label="Fullscreen preview" onClick={onFullscreen} className="w-7 h-7 rounded-full bg-white text-black grid place-items-center hover:bg-white/90"><Maximize2 size={12} /></button>}
      </div>
    </div>
  );

  return (
    <section className="relative bg-[#07080c] py-16 sm:py-24 overflow-hidden" aria-labelledby="zyphron-live-heading">
      <div className="absolute inset-0 bg-[radial-gradient(900px_600px_at_50%_0%,rgba(59,130,246,0.08),transparent_70%)]" />
      <div className="absolute inset-0 grid-pattern opacity-[0.15] [mask-image:radial-gradient(60%_40%_at_50%_0%,black,transparent)]" />

      <div className="relative max-w-[1200px] mx-auto px-6 sm:px-8">
        {/* heading */}
        <motion.div initial={{ opacity: 0, y: 16 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: "-80px" }} transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1] }} className="text-center max-w-[720px] mx-auto">
          <p className="inline-flex items-center gap-2 text-[11px] tracking-[0.2em] font-semibold text-white/30 uppercase">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse shadow-[0_0_8px_rgba(16,185,129,0.6)]" /> LIVE WEBSITE • Currently live at zyphron.cloud
          </p>
          <h2 id="zyphron-live-heading" className="mt-3 text-[30px] sm:text-[42px] font-[800] tracking-[-0.04em] leading-[0.9] text-white">See Zyphron Cloud<br /><span className="bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent">in action.</span></h2>
          <p className="mt-3 text-[15px] leading-relaxed text-white/55">A live look at the platform Ravneet is building and operating. Interact below or open the real site in a new tab — no screenshots.</p>
        </motion.div>

        {/* controls */}
        <motion.div initial={{ opacity: 0, y: 12 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ delay: 0.1, duration: 0.5 }} className="mt-8 flex flex-wrap items-center justify-center gap-2">
          <span className="hidden sm:inline-flex items-center gap-2 text-[11px] tracking-widest uppercase text-white/40 border border-white/10 rounded-full px-3 py-1.5 bg-white/[0.04]"><span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" /> LIVE PREVIEW</span>
          <a href={ZYPHRON_URL} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1.5 bg-white text-black font-semibold text-[13px] px-4 py-2 rounded-full hover:bg-white/90">Open Website <ArrowUpRight size={14} /></a>
          <button onClick={() => setFullscreen(true)} className="inline-flex items-center gap-1.5 bg-white/10 border border-white/15 text-white font-semibold text-[13px] px-4 py-2 rounded-full hover:bg-white/15">Fullscreen <Maximize2 size={14} /></button>
          <button onClick={() => setIframeKey(k => k + 1)} className="inline-flex items-center gap-1.5 bg-white/5 border border-white/10 text-white/70 text-[13px] px-4 py-2 rounded-full hover:text-white">Refresh <RefreshCw size={14} /></button>
        </motion.div>

        {/* device switcher */}
        <div className="mt-6 flex justify-center">
          <div role="group" aria-label="Preview device size" className="inline-flex items-center gap-1 rounded-full bg-white/[0.06] border border-white/10 p-1">
            {([
              { id: "desktop" as Device, label: "Desktop", icon: Monitor, w: "1200×700" },
              { id: "tablet" as Device, label: "Tablet", icon: Tablet, w: "768×900" },
              { id: "mobile" as Device, label: "Mobile", icon: Smartphone, w: "390×844" },
            ]).map(d => (
              <button key={d.id} aria-pressed={device === d.id} aria-label={`Switch to ${d.label} preview`} onClick={() => setDevice(d.id)} className={`inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-[12px] font-semibold transition ${device === d.id ? "bg-white text-black" : "text-white/60 hover:text-white"}`}>
                <d.icon size={14} /> {d.label} <span className="hidden sm:inline text-[10px] opacity-50">{d.w}</span>
              </button>
            ))}
          </div>
        </div>

        {/* browser frame */}
        <motion.div
          initial={{ opacity: 0, y: 24, scale: 0.96 }}
          whileInView={{ opacity: 1, y: 0, scale: 1 }}
          viewport={{ once: true, margin: "-40px" }}
          transition={{ duration: 0.7, ease: [0.16, 1, 0.3, 1] }}
          className="mt-8 flex justify-center"
        >
          <div className={`relative ${widthMap[device]} rounded-[18px] border border-white/10 bg-[#0e1118] shadow-[0_24px_80px_rgba(0,0,0,0.6),0_1px_0_rgba(255,255,255,0.06)_inset] overflow-hidden transition-all duration-500`}>
            <div className="absolute -inset-4 bg-blue-500/10 blur-[32px] -z-10 rounded-[24px]" />
            <BrowserChrome onFullscreen={() => setFullscreen(true)} onRefresh={() => setIframeKey(k => k + 1)} />

            <div className={`relative bg-white overflow-hidden ${heightMap[device]} transition-all duration-500`}>
              {!blocked ? (
                <iframe
                  key={iframeKey}
                  ref={iframeRef}
                  src={ZYPHRON_URL}
                  title="Live preview of Zyphron Cloud — https://zyphron.cloud"
                  loading="lazy"
                  allow="fullscreen"
                  referrerPolicy="no-referrer-when-downgrade"
                  className="w-full h-full border-0"
                  onError={() => setBlocked(true)}
                  sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox"
                />
              ) : null}
              {/* Fallback overlay if blocked */}
              <AnimatePresence>
                {blocked && (
                  <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="absolute inset-0 bg-[#0a0d14] grid place-items-center p-8 text-center">
                    <div className="max-w-[420px]">
                      <p className="inline-flex items-center gap-2 text-[11px] tracking-widest font-semibold text-emerald-300 border border-emerald-500/20 bg-emerald-500/10 rounded-full px-3 py-1"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" /> LIVE WEBSITE</p>
                      <h3 className="mt-4 text-white font-semibold">Zyphron Cloud is live</h3>
                      <p className="text-white/50 text-sm mt-2">Embedding is restricted by the site. Open the live website directly — it&apos;s the real platform, not a screenshot.</p>
                      <a href={ZYPHRON_URL} target="_blank" rel="noopener noreferrer" className="mt-5 inline-flex items-center gap-2 bg-[#2563eb] text-white font-semibold px-5 py-2.5 rounded-full">Open Zyphron Cloud <ArrowUpRight size={14} /></a>
                      <button onClick={() => setBlocked(false)} className="mt-3 block mx-auto text-xs text-white/40 hover:text-white underline">Try loading preview again</button>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
              {/* subtle top glow */}
              <div className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-blue-400/30 to-transparent" />
            </div>

            {/* footer bar */}
            <div className="flex items-center justify-between px-4 py-2.5 bg-[#0e1118] border-t border-white/10 text-[11px] text-white/30">
              <span className="flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" /> Live preview • zyphron.cloud</span>
              <span className="hidden sm:inline">Built by Ravneet • {device}</span>
            </div>
          </div>
        </motion.div>

        {/* highlights */}
        <div className="mt-6 flex flex-wrap justify-center gap-2">
          {HIGHLIGHTS.map(h => (
            <a key={h.label} href={h.href} target="_blank" rel="noopener noreferrer" className="px-3.5 py-1.5 rounded-full bg-white/[0.06] border border-white/10 text-[12px] font-medium text-white/70 hover:bg-white hover:text-black hover:border-white transition">{h.label}</a>
          ))}
        </div>

        {/* built by */}
        <motion.div initial={{ opacity: 0, y: 16 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ duration: 0.6 }} className="mt-12 rounded-[24px] border border-white/10 bg-gradient-to-br from-white/[0.06] to-white/[0.02] p-7 sm:p-10 text-center">
          <h3 className="text-[28px] sm:text-[36px] font-[800] tracking-[-0.04em] leading-[0.9] text-white">This isn&apos;t just a project.<br /><span className="bg-gradient-to-r from-blue-400 to-cyan-300 bg-clip-text text-transparent">It&apos;s a platform I&apos;m building.</span></h3>
          <p className="mt-3 max-w-[640px] mx-auto text-[14px] leading-relaxed text-white/55">Zyphron Cloud combines infrastructure, hosting, automation, customer experience and business operations into one platform — end-to-end, from node to support.</p>
          <a href={ZYPHRON_URL} target="_blank" rel="noopener noreferrer" className="mt-6 inline-flex items-center gap-2 bg-[#2563eb] text-white font-semibold px-6 py-2.5 rounded-full hover:bg-[#1d4ed8]">Explore Zyphron Cloud <ArrowUpRight size={14} /></a>
        </motion.div>

        {/* infrastructure map */}
        <div className="mt-8 rounded-[24px] border border-white/10 bg-white/[0.03] p-6 sm:p-8">
          <p className="text-[11px] tracking-[0.15em] font-semibold text-white/30 uppercase text-center">Eco-system ↔ Infrastructure</p>
          <div className="mt-6 flex flex-col items-center gap-2 text-[12px] font-mono text-white/60">
            <div className="px-4 py-2 rounded-full bg-blue-500 text-white font-semibold tracking-widest text-[11px]">ZYPHRON CLOUD</div>
            <div className="w-px h-4 bg-white/15" />
            <div className="flex gap-3"><span className="px-3 py-1.5 rounded-full bg-white/10 border border-white/10">WEBSITE</span><span className="px-3 py-1.5 rounded-full bg-white/10 border border-white/10">BILLING</span></div>
            <div className="w-px h-4 bg-white/15" />
            <div className="px-3 py-1 rounded-full bg-white text-black font-semibold text-xs">API</div>
            <div className="w-px h-4 bg-white/15" />
            <div className="flex flex-wrap justify-center gap-2"><span className="px-3 py-1.5 rounded-full bg-white/[0.06] border border-white/10">GAME SERVERS</span><span className="px-3 py-1.5 rounded-full bg-white/[0.06] border border-white/10">VPS SERVERS</span><span className="px-3 py-1.5 rounded-full bg-white/[0.06] border border-white/10">WEB HOSTING</span></div>
            <div className="w-px h-4 bg-white/15" />
            <div className="px-4 py-2 rounded-full bg-emerald-500/20 border border-emerald-500/30 text-emerald-300 font-semibold text-[11px] tracking-widest">INFRASTRUCTURE • Nodes • Network</div>
            <div className="mt-3 flex items-center gap-1.5 text-[11px] text-white/30"><span className="w-1.5 h-1.5 rounded-full bg-blue-400 animate-pulse" /> Animated connections • Packets travel with each request</div>
          </div>
          <div className="mt-6 h-1 rounded-full bg-white/10 overflow-hidden flex"><span className="flex-1 bg-blue-500 animate-pulse" /><span className="flex-1 bg-cyan-400" /><span className="flex-1 bg-emerald-400" /></div>
        </div>
      </div>

      {/* fullscreen modal */}
      <AnimatePresence>
        {fullscreen && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-[80] bg-black/80 backdrop-blur-md flex flex-col">
            <div className="flex items-center justify-between px-4 sm:px-6 py-3 bg-[#0e1118] border-b border-white/10">
              <span className="text-[12px] tracking-widest text-white/60">LIVE • zyphron.cloud • Fullscreen</span>
              <div className="flex items-center gap-2">
                <a href={ZYPHRON_URL} target="_blank" rel="noopener noreferrer" className="px-4 py-1.5 rounded-full bg-white text-black text-[13px] font-semibold">Open in new tab <ArrowUpRight size={12} className="inline ml-1" /></a>
                <button aria-label="Close fullscreen" onClick={() => setFullscreen(false)} className="w-8 h-8 rounded-full bg-white/10 border border-white/15 grid place-items-center text-white hover:bg-white/20"><X size={16} /></button>
              </div>
            </div>
            <div className="flex-1 bg-white">
              <iframe src={ZYPHRON_URL} title="Zyphron Cloud fullscreen preview" className="w-full h-full border-0" allow="fullscreen" sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox" />
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  );
}
