/* Auto-bundled */

/* === components/hero-bg.jsx === */
// Optional: hero bg is fully CSS in styles.css so no JS needed here.
// This file exists so index.html can keep script order stable.

/* === components/seo-head.jsx === */
/* Client-side <head> tag manager. Merges route-level meta with global SEO. */

function _setMeta(name, content, attr) {
  if (!content) return;
  attr = attr || "name";
  let el = document.head.querySelector(`meta[${attr}="${name}"]`);
  if (!el) {
    el = document.createElement("meta");
    el.setAttribute(attr, name);
    document.head.appendChild(el);
  }
  el.setAttribute("content", content);
}
function _setLink(rel, href) {
  if (!href) return;
  let el = document.head.querySelector(`link[rel="${rel}"]`);
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", rel);
    document.head.appendChild(el);
  }
  el.setAttribute("href", href);
}
function _setJsonLd(id, data) {
  let el = document.head.querySelector(`script[data-jsonld="${id}"]`);
  if (data == null) {
    if (el) el.remove();
    return;
  }
  if (!el) {
    el = document.createElement("script");
    el.type = "application/ld+json";
    el.setAttribute("data-jsonld", id);
    document.head.appendChild(el);
  }
  el.textContent = JSON.stringify(data);
}

function SeoHead({ title, description, keywords, image, url, jsonLd, robots }) {
  const [globalSeo, setGlobalSeo] = React.useState(null);
  React.useEffect(() => {
    DB.getSeo().then(setGlobalSeo);
  }, []);
  React.useEffect(() => {
    if (!globalSeo) return;
    const finalTitle = title
      ? `${title} — ${window.ALARAK_CONFIG.SITE_NAME || "Alarak"}`
      : globalSeo.site_title;
    const finalDesc = description || globalSeo.site_description;
    const finalKeywords = [keywords, globalSeo.site_keywords]
      .filter(Boolean)
      .join(", ");
    const finalImage = image || globalSeo.og_image || "assets/logo.png";
    const canon =
      (globalSeo.canonical_base || "") +
      (url || (typeof location !== "undefined" ? location.hash : ""));

    document.title = finalTitle;
    _setMeta("description", finalDesc);
    _setMeta("keywords", finalKeywords);
    _setMeta("robots", robots || "index, follow");
    _setLink("canonical", canon);

    _setMeta("og:title", finalTitle, "property");
    _setMeta("og:description", finalDesc, "property");
    _setMeta("og:image", finalImage, "property");
    _setMeta("og:url", canon, "property");
    _setMeta("og:type", "website", "property");

    _setMeta("twitter:card", "summary_large_image");
    _setMeta("twitter:title", finalTitle);
    _setMeta("twitter:description", finalDesc);
    _setMeta("twitter:image", finalImage);
    if (globalSeo.twitter_handle) _setMeta("twitter:site", globalSeo.twitter_handle);

    _setJsonLd("route", jsonLd || null);

    return () => _setJsonLd("route", null);
  }, [globalSeo, title, description, keywords, image, url, robots, JSON.stringify(jsonLd || {})]);

  return null;
}

window.SeoHead = SeoHead;

/* === components/navbar.jsx === */
function Navbar({ route, go }) {
  const [open, setOpen] = React.useState(false);
  const links = [
    { key: "home", label: "Home", href: "#/" },
    { key: "scripts", label: "Scripts", href: "#/scripts" },
    { key: "videos", label: "Videos", href: "#/videos" },
    { key: "executors", label: "Executors", href: "#/executors" },
  ];
  const activeKey = (() => {
    if (!route || route === "/" || route === "") return "home";
    if (route.startsWith("/scripts")) return "scripts";
    if (route.startsWith("/videos")) return "videos";
    if (route.startsWith("/executors")) return "executors";
    return "";
  })();

  return (
    <nav className="nav">
      <div className="nav-inner">
        <a className="nav-brand" href="#/" onClick={() => setOpen(false)}>
          <img src="assets/logo.png" alt="Alarak logo" />
          <span>Alarak</span>
        </a>
        <div className="nav-links">
          {links.map((l) => (
            <a
              key={l.key}
              href={l.href}
              className={"nav-link " + (activeKey === l.key ? "active" : "")}
            >
              {l.label}
            </a>
          ))}
        </div>
        <button
          className="nav-mobile-toggle"
          onClick={() => setOpen((o) => !o)}
          aria-label="Toggle menu"
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
            <path d="M3 6h18M3 12h18M3 18h18" />
          </svg>
        </button>
      </div>

      {open && (
        <div className="nav-mobile-drawer">
          {links.map((l) => (
            <a
              key={l.key}
              href={l.href}
              className={"nav-link " + (activeKey === l.key ? "active" : "")}
              onClick={() => setOpen(false)}
            >
              {l.label}
            </a>
          ))}
        </div>
      )}
    </nav>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="row gap-16" style={{justifyContent:'center', flexWrap:'wrap'}}>
          <a href="#/" style={{display:'inline-flex', alignItems:'center', gap:8, color:'var(--fg-2)'}}>
            <img src="assets/logo.png" alt="" style={{width:24, height:24, borderRadius:6}} />
            <span style={{fontWeight:600, color:'var(--fg)'}}>Alarak</span>
          </a>
          <span style={{color:'var(--muted-2)'}}>—</span>
          <span>The best Roblox scripts, daily</span>
        </div>
        <div style={{marginTop:12, fontSize:'0.78rem', color:'var(--muted-2)'}}>
          © {new Date().getFullYear()} Alarak. All rights reserved.
        </div>
      </div>
    </footer>
  );
}

window.Navbar = Navbar;
window.Footer = Footer;

/* === components/cards.jsx === */
/* Reusable card components for scripts and executors. */

function EyeIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );
}
function ArrowIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  );
}
function DownloadIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3v12M6 11l6 6 6-6M4 21h16" />
    </svg>
  );
}

function CardThumb({ src, alt }) {
  return (
    <div className="thumb">
      {src ? (
        <img src={src} alt={alt || ""} loading="lazy" />
      ) : (
        <div className="thumb-placeholder">Alarak</div>
      )}
    </div>
  );
}

function ScriptCard({ script }) {
  const popular = DB.isPopular(script);
  return (
    <a href={`#/scripts/${script.id}`} className="glass glass-hover card" aria-label={script.title}>
      <CardThumb src={script.thumbnail} alt={script.title} />
      <div className="card-body">
        <div className="row gap-8" style={{ flexWrap: "wrap" }}>
          {popular && <span className="badge badge-red">🔥 Popular</span>}
          {script.status === "working" && (
            <span className="badge badge-green">Working</span>
          )}
          {script.script_type && (
            <span className="badge">{script.script_type}</span>
          )}
        </div>
        <div>
          <div className="card-title">{script.title}</div>
          <div className="card-game">{script.game || "Roblox"}</div>
        </div>
        <div className="card-meta">
          <span className="card-views">
            <EyeIcon /> {formatViews(script.views_total)} views
          </span>
          <span className="btn btn-sm btn-primary" style={{ pointerEvents: "none" }}>
            Get Script <ArrowIcon />
          </span>
        </div>
      </div>
    </a>
  );
}

function ExecutorCard({ exec }) {
  const popular = DB.isPopular(exec);
  return (
    <a href={`#/executors/${exec.id}`} className="glass glass-hover card" aria-label={exec.title}>
      <CardThumb src={exec.logo} alt={exec.title} />
      <div className="card-body">
        <div className="row gap-8" style={{ flexWrap: "wrap" }}>
          {popular && <span className="badge badge-red">🔥 Popular</span>}
          <span className={"badge " + (exec.tier === "paid" ? "" : "badge-green")}>
            {exec.tier === "paid" ? "Paid" : "Free"}
          </span>
          {(exec.platforms || []).slice(0, 2).map((p) => (
            <span key={p} className="badge badge-blue">{p}</span>
          ))}
        </div>
        <div>
          <div className="card-title">{exec.title}</div>
          <div className="card-game">Executor</div>
        </div>
        <div className="card-meta">
          <span className="card-views">
            <EyeIcon /> {formatViews(exec.views_total)} views
          </span>
          <span className="btn btn-sm btn-primary" style={{ pointerEvents: "none" }}>
            Get Executor <DownloadIcon />
          </span>
        </div>
      </div>
    </a>
  );
}

Object.assign(window, {
  ScriptCard,
  ExecutorCard,
  CardThumb,
  EyeIcon,
  ArrowIcon,
  DownloadIcon,
});

/* === components/ui.jsx === */
/* Shared UI primitives. */

function Spinner({ size = 20 }) {
  return (
    <span
      className="spinner"
      style={{ width: size, height: size }}
      aria-label="Loading"
    />
  );
}

function LoadingBlock({ label = "Loading…" }) {
  return (
    <div className="empty" style={{ padding: "80px 20px" }}>
      <Spinner size={28} />
      <p style={{ marginTop: 16, color: "var(--muted)" }}>{label}</p>
    </div>
  );
}

function Empty({ title, message, action }) {
  return (
    <div className="empty">
      <h3>{title}</h3>
      <p>{message}</p>
      {action}
    </div>
  );
}

/* ---------- Toast ---------- */
const ToastCtx = React.createContext(() => {});

function ToastProvider({ children }) {
  const [toasts, setToasts] = React.useState([]);
  const push = React.useCallback((msg, kind = "ok", ms = 2600) => {
    const id = Math.random().toString(36).slice(2);
    setToasts((t) => [...t, { id, msg, kind }]);
    setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), ms);
  }, []);
  return (
    <ToastCtx.Provider value={push}>
      {children}
      <div className="toast-wrap">
        {toasts.map((t) => (
          <div key={t.id} className={"toast " + t.kind}>
            {t.msg}
          </div>
        ))}
      </div>
    </ToastCtx.Provider>
  );
}
const useToast = () => React.useContext(ToastCtx);

/* ---------- Reveal on scroll ---------- */
function Reveal({ children, delay = 0, as = "div", ...rest }) {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // If IntersectionObserver isn't available, just reveal immediately.
    if (typeof IntersectionObserver === "undefined") {
      setInView(true);
      return;
    }
    // Fallback: if already visible OR after a short timeout, force reveal.
    // This guarantees content doesn't get stuck invisible.
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) {
      setTimeout(() => setInView(true), delay);
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setTimeout(() => setInView(true), delay);
            io.disconnect();
          }
        });
      },
      { threshold: 0.01, rootMargin: "0px 0px -50px 0px" }
    );
    io.observe(el);
    // Safety net: force-reveal after 1.5s no matter what
    const fallback = setTimeout(() => setInView(true), 1500);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, [delay]);
  const Cmp = as;
  const className = ("reveal " + (rest.className || "") + (inView ? " in" : "")).trim();
  return (
    <Cmp ref={ref} {...rest} className={className}>
      {children}
    </Cmp>
  );
}

/* ---------- Animated number (display-only, counts up to whatever value it's given) ---------- */
function AnimatedNumber({ value, format, duration = 900 }) {
  const [display, setDisplay] = React.useState(0);
  const raf = React.useRef(null);
  React.useEffect(() => {
    const target = Number(value) || 0;
    const start = performance.now();
    const from = 0;
    cancelAnimationFrame(raf.current);
    function tick(now) {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3); // ease-out cubic
      setDisplay(from + (target - from) * eased);
      if (t < 1) raf.current = requestAnimationFrame(tick);
      else setDisplay(target);
    }
    raf.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf.current);
  }, [value, duration]);
  const shown = Math.round(display);
  return <>{format ? format(shown) : shown}</>;
}

/* ---------- Number formatting ---------- */
function formatViews(n) {
  n = Number(n) || 0;
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, "") + "M";
  if (n >= 1_000) return (n / 1_000).toFixed(1).replace(/\.0$/, "") + "K";
  return String(n);
}

/* ---------- Modal ---------- */
function Modal({ open, onClose, title, children, wide }) {
  React.useEffect(() => {
    if (!open) return;
    const esc = (e) => e.key === "Escape" && onClose && onClose();
    window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-back" onClick={onClose}>
      <div
        className="modal"
        style={wide ? { maxWidth: 820 } : {}}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="between" style={{ marginBottom: 20 }}>
          <h2 style={{ fontSize: "1.4rem" }}>{title}</h2>
          <button className="btn btn-sm btn-ghost" onClick={onClose}>
            ✕
          </button>
        </div>
        {children}
      </div>
    </div>
  );
}

Object.assign(window, {
  Spinner,
  LoadingBlock,
  Empty,
  ToastProvider,
  useToast,
  Reveal,
  formatViews,
  Modal,
  AnimatedNumber,
});

/* === pages/home.jsx === */
function HomePage() {
  const [homepage, setHomepage] = React.useState(null);
  const [scripts, setScripts] = React.useState([]);
  const [executors, setExecutors] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [ytEmbed, setYtEmbed] = React.useState(null);

  React.useEffect(() => {
    let alive = true;
    Promise.all([DB.getHomepage(), DB.listScripts(), DB.listExecutors()]).then(([hp, ss, ee]) => {
      if (!alive) return;
      setHomepage(hp);
      setScripts(ss);
      setExecutors(ee);
      setLoading(false);
    });
    return () => (alive = false);
  }, []);

  // Resolving @handle / vanity URLs to a channel id requires a network
  // lookup, so this runs separately from the main data load above and
  // fills in the embed once (or if) it resolves.
  React.useEffect(() => {
    let alive = true;
    if (!homepage) return;
    resolveYouTubeEmbed(homepage).then((embed) => {
      if (alive) setYtEmbed(embed);
    });
    return () => (alive = false);
  }, [homepage]);

  const popular = React.useMemo(() => {
    return [...scripts]
      .sort((a, b) => (b.views_24h || 0) - (a.views_24h || 0))
      .slice(0, 3);
  }, [scripts]);
  const recent = React.useMemo(() => scripts.slice(0, 6), [scripts]);

  // Sum stats for hero pills
  const totalViews = React.useMemo(() => {
    return [...scripts, ...executors].reduce((s, x) => s + (x.views_total || 0), 0);
  }, [scripts, executors]);

  return (
    <div className="page page-fade">
      <SeoHead
        title={null}
        description={homepage && homepage.hero_subtitle}
        url="#/"
        jsonLd={{
          "@context": "https://schema.org",
          "@type": "WebSite",
          name: "Alarak",
          url: "/",
          potentialAction: {
            "@type": "SearchAction",
            target: "/#/scripts?q={search_term_string}",
            "query-input": "required name=search_term_string",
          },
        }}
      />

      <div className="orb orb-1" />
      <div className="orb orb-2" />

      <section className="hero container">
        <div className="hero-mascot-ring">
          <img src="assets/logo.png" alt="Alarak mascot" />
        </div>

        <div className="hero-eyebrow">
          <span className="pulse-dot" />
          <span className="hero-eyebrow-text">ALARAK · SCRIPT HUB · UPDATED DAILY</span>
        </div>

        <h1>
          {renderHeroTitle((homepage && homepage.hero_title) || "The best Roblox scripts, daily.")}
        </h1>
        <p className="hero-sub">
          {(homepage && homepage.hero_subtitle) ||
            "Curated working scripts and powerful executors. Fresh drops every week."}
        </p>

        <div className="hero-cta">
          <a href="#/scripts" className="btn btn-primary btn-lg">
            Browse Scripts <ArrowIcon />
          </a>
          <a href="#/executors" className="btn btn-lg">
            View Executors
          </a>
        </div>

        <div className="hero-stats">
          <div className="hero-stat">
            <span className="hero-stat-dot" />
            <span>SCRIPTS</span>
            <span className="hero-stat-value">{scripts.length}</span>
          </div>
          <div className="hero-stat">
            <span className="hero-stat-dot" />
            <span>EXECUTORS</span>
            <span className="hero-stat-value">{executors.length}</span>
          </div>
          <div className="hero-stat">
            <span className="hero-stat-dot" />
            <span>TOTAL VIEWS</span>
            <span className="hero-stat-value">{formatViews(totalViews)}</span>
          </div>
        </div>

        {/* Quick nav tiles */}
        <div className="quick-nav">
          <QuickTile href="#/" title="Home" desc="Latest drops and channel highlights" icon={<HouseIcon />} />
          <QuickTile href="#/scripts" title="Scripts" desc="Search working Roblox scripts" icon={<CodeIcon />} />
          <QuickTile href="#/videos" title="Videos" desc="Newest showcases from YouTube" icon={<PlayIcon />} />
          <QuickTile href="#/executors" title="Executors" desc="Trusted PC & mobile executors" icon={<CpuIcon />} />
        </div>
      </section>

      {/* Marquee ticker */}
      <div className="marquee">
        <div className="marquee-track">
          <span>Working scripts</span>
          <span>Daily uploads</span>
          <span>Free executors</span>
          <span>Blox Fruits</span>
          <span>Blade Ball</span>
          <span>Anime scripts</span>
          <span>Key & keyless</span>
          <span>Mobile support</span>
          <span>PC support</span>
          <span>Auto farm</span>
          <span>Working scripts</span>
          <span>Daily uploads</span>
          <span>Free executors</span>
          <span>Blox Fruits</span>
          <span>Blade Ball</span>
          <span>Anime scripts</span>
          <span>Key & keyless</span>
          <span>Mobile support</span>
          <span>PC support</span>
          <span>Auto farm</span>
        </div>
      </div>

      {/* YouTube channel card */}
      <section className="container" style={{ marginTop: 60, position: 'relative' }}>
        <div className="orb orb-3" />
        <Reveal className="glass yt-card">
          <div className="yt-latest">
            {ytEmbed ? (
              <iframe
                src={ytEmbed}
                title="Latest Alarak video"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
              />
            ) : (
              <div style={{display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', width:'100%', height:'100%', color:'var(--muted)', fontFamily:'var(--font-mono)', fontSize:'0.85rem', gap:12, textAlign:'center', padding:20}}>
                <YouTubeIcon />
                <div>Set a YouTube channel URL in admin to embed latest video</div>
              </div>
            )}
          </div>
          <div className="yt-info">
            <div className="yt-badge">
              <span className="live-dot" />
              Latest on YouTube
            </div>
            <h3>{(homepage && homepage.youtube_channel_name) || "Alarak"}</h3>
            <p style={{color:'var(--muted)', marginBottom:20}}>
              Roblox script showcases, executor reviews and gameplay drops every week. Hit subscribe so you don't miss the next one.
            </p>
            <div className="row gap-12" style={{flexWrap:'wrap'}}>
              <a
                className="btn btn-primary"
                href={(homepage && homepage.youtube_channel_url) || "#"}
                target="_blank" rel="noopener noreferrer"
              >
                <YouTubeIcon /> Subscribe
              </a>
              <a className="btn" href="#/videos">Recent videos <ArrowIcon /></a>
            </div>
          </div>
        </Reveal>
      </section>

      {/* Popular Scripts */}
      <section className="section container" style={{position:'relative'}}>
        <div className="section-head">
          <div>
            <div className="eyebrow">TRENDING NOW</div>
            <h2>Popular scripts</h2>
          </div>
          <a href="#/scripts" className="btn btn-sm">View all <ArrowIcon /></a>
        </div>
        {loading ? (
          <LoadingBlock label="Loading popular scripts…" />
        ) : popular.length === 0 ? (
          <Empty
            title="No scripts yet"
            message="Add your first script from the admin panel."
            action={<a href="#/admin" className="btn btn-primary" style={{marginTop:16}}>Open Admin</a>}
          />
        ) : (
          <div className="grid grid-3">
            {popular.map((s, i) => (
              <Reveal key={s.id} delay={i * 80}>
                <ScriptCard script={s} />
              </Reveal>
            ))}
          </div>
        )}
      </section>

      <div className="divider container" />

      {/* Recent */}
      <section className="section container" style={{paddingTop:20}}>
        <div className="section-head">
          <div>
            <div className="eyebrow">FRESH DROPS</div>
            <h2>Recent uploads</h2>
          </div>
          <a href="#/scripts" className="btn btn-sm">All scripts <ArrowIcon /></a>
        </div>
        {loading ? null : recent.length === 0 ? null : (
          <div className="grid grid-3">
            {recent.map((s, i) => (
              <Reveal key={s.id} delay={i * 60}>
                <ScriptCard script={s} />
              </Reveal>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

function renderHeroTitle(title) {
  const words = title.trim().split(/\s+/);
  if (words.length <= 2) return <span className="accent">{title}</span>;
  const accent = words.slice(-2).join(" ");
  const rest = words.slice(0, -2).join(" ");
  return (
    <React.Fragment>
      {rest}
      <br />
      <span className="accent">{accent}</span>
    </React.Fragment>
  );
}

function QuickTile({ href, title, desc, icon }) {
  return (
    <a href={href} className="glass glass-hover quick-tile">
      <div className="qt-icon">{icon}</div>
      <div>
        <h3>{title}</h3>
        <p>{desc}</p>
      </div>
      <div className="qt-arrow">
        <ArrowIcon />
      </div>
    </a>
  );
}

function HouseIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 10.5 12 3l9 7.5V21H3z" />
      <path d="M9 21v-6h6v6" />
    </svg>
  );
}
function CodeIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="m8 6-6 6 6 6M16 6l6 6-6 6" />
    </svg>
  );
}
function PlayIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polygon points="6 4 20 12 6 20 6 4" fill="currentColor" />
    </svg>
  );
}
function CpuIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="5" y="5" width="14" height="14" rx="2" />
      <rect x="9" y="9" width="6" height="6" />
      <path d="M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3" />
    </svg>
  );
}
function YouTubeIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
      <path d="M23 6.2s-.2-1.6-.9-2.3c-.9-.9-1.9-.9-2.3-1C16.4 2.5 12 2.5 12 2.5s-4.4 0-7.7.4c-.5 0-1.5.1-2.3 1-.7.7-.9 2.3-.9 2.3S1 8.1 1 10v1.9c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.9.9 2.1.9 2.6 1 1.9.2 7.9.4 8 .4 0 0 4.4 0 7.7-.4.5-.1 1.5-.1 2.3-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V10c-.1-1.9-.3-3.8-.3-3.8zM9.7 14.4V7.6l6 3.4-6 3.4z" />
    </svg>
  );
}

// Builds the homepage embed URL for the actual latest upload, via the
// youtube-latest Edge Function (see fetchYouTubeData in pages/videos.jsx).
// Falls back to the manually-set latest_video_id if the lookup fails.
async function resolveYouTubeEmbed(hp) {
  if (!hp) return null;
  const url = hp.youtube_channel_url;
  if (url) {
    try {
      const data = await fetchYouTubeData(url, 1);
      const first = data.videos && data.videos[0];
      if (first) return `https://www.youtube.com/embed/${first.id}?rel=0`;
    } catch (e) {
      // fall through to the manual fallback below
    }
  }
  if (hp.latest_video_id) {
    return `https://www.youtube.com/embed/${hp.latest_video_id}?rel=0`;
  }
  return null;
}

window.HomePage = HomePage;

/* === pages/scripts.jsx === */
function ScriptsPage() {
  const [all, setAll] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [q, setQ] = React.useState(() => {
    const m = (location.hash || "").match(/\?q=([^&]+)/);
    return m ? decodeURIComponent(m[1]) : "";
  });
  const [activeTag, setActiveTag] = React.useState("all");

  React.useEffect(() => {
    let alive = true;
    DB.listScripts().then((ss) => {
      if (!alive) return;
      setAll(ss);
      setLoading(false);
    });
    return () => (alive = false);
  }, []);

  const allTags = React.useMemo(() => {
    const t = new Set();
    all.forEach((s) => (s.tags || []).forEach((tag) => t.add(tag)));
    return ["all", "popular", ...Array.from(t)];
  }, [all]);

  const filtered = React.useMemo(() => {
    let list = all;
    if (activeTag === "popular") list = list.filter((s) => DB.isPopular(s));
    else if (activeTag !== "all")
      list = list.filter((s) => (s.tags || []).includes(activeTag));
    if (q) {
      const needle = q.toLowerCase();
      list = list.filter(
        (s) =>
          s.title.toLowerCase().includes(needle) ||
          (s.game || "").toLowerCase().includes(needle) ||
          (s.tags || []).some((t) => t.toLowerCase().includes(needle))
      );
    }
    return list;
  }, [all, q, activeTag]);

  return (
    <div className="page page-fade">
      <SeoHead
        title="All Roblox Scripts"
        description="Search working Roblox scripts by Alarak. Auto farms, teleports, script hubs and more."
        keywords="roblox scripts, script search, working scripts, auto farm, script hub"
        url="#/scripts"
      />
      <div className="orb orb-1" />
      <section className="container" style={{paddingTop:60, position:'relative'}}>
        <div className="eyebrow">LIBRARY</div>
        <h1 style={{fontSize:'clamp(2.4rem, 5vw, 3.6rem)', marginBottom:12}}>
          All <span style={{color:'var(--red-hot)'}}>scripts</span>
        </h1>
        <p style={{color:'var(--muted)', maxWidth:640, fontSize:'1.05rem'}}>Search and filter every script we've ever released. Popular ones are auto-tagged based on views in the last 24 hours.</p>

        <div style={{marginTop:32}}>
          <div className="search-wrap">
            <SearchIcon className="search-ico" />
            <input
              className="input"
              placeholder="Search by title, game, or tag…"
              value={q}
              onChange={(e) => setQ(e.target.value)}
              aria-label="Search scripts"
            />
          </div>
          {allTags.length > 2 && (
            <div className="filter-row">
              {allTags.map((t) => (
                <button
                  key={t}
                  className={"chip " + (activeTag === t ? "active" : "")}
                  onClick={() => setActiveTag(t)}
                >
                  {t === "popular" ? "🔥 popular" : t}
                </button>
              ))}
            </div>
          )}
        </div>
      </section>

      <section className="container" style={{marginTop:40, paddingBottom:80}}>
        {loading ? (
          <LoadingBlock />
        ) : filtered.length === 0 ? (
          <Empty
            title={all.length === 0 ? "No scripts yet" : "No matches"}
            message={
              all.length === 0
                ? "Add your first script from the admin panel."
                : "Try a different search or filter."
            }
          />
        ) : (
          <div className="grid grid-3">
            {filtered.map((s, i) => (
              <Reveal key={s.id} delay={i * 40}>
                <ScriptCard script={s} />
              </Reveal>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

function SearchIcon({ className }) {
  return (
    <svg className={className} width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="7" />
      <path d="m21 21-4.3-4.3" />
    </svg>
  );
}

window.ScriptsPage = ScriptsPage;

/* === pages/script-detail.jsx === */
function ScriptDetailPage({ id }) {
  const [script, setScript] = React.useState(null);
  const [related, setRelated] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [notFound, setNotFound] = React.useState(false);
  const cleanupRef = React.useRef(null);

  React.useEffect(() => {
    let alive = true;
    (async () => {
      const s = await DB.getScript(id).catch(() => null);
      if (!alive) return;
      if (!s) {
        setNotFound(true);
        setLoading(false);
        return;
      }
      setScript(s);
      setLoading(false);
      // YouTube-style: only counts after 5s dwell + tab focused + 12h cooldown.
      const cancel = DB.recordViewDelayed("script", id, 5000);
      // Store cancel on ref for cleanup
      cleanupRef.current = cancel;
      const all = await DB.listScripts();
      if (!alive) return;
      setRelated(
        all
          .filter((x) => x.id !== id && (x.game === s.game || (s.tags || []).some((t) => (x.tags || []).includes(t))))
          .slice(0, 3)
      );
    })();
    return () => {
      alive = false;
      if (cleanupRef.current) cleanupRef.current();
    };
  }, [id]);

  if (loading) return <div className="page"><LoadingBlock /></div>;
  if (notFound || !script)
    return (
      <div className="page container" style={{ paddingTop: 60 }}>
        <Empty title="Script not found" message="The script you're looking for doesn't exist." action={<a href="#/scripts" className="btn btn-primary" style={{marginTop:16}}>Back to scripts</a>} />
      </div>
    );

  const popular = DB.isPopular(script);

  return (
    <div className="page page-fade container">
      <SeoHead
        title={`${script.title} — ${script.game || "Roblox"} Script`}
        description={script.seo_description || script.description || `Get the ${script.title} script for ${script.game}. Working, updated.`}
        keywords={script.seo_keywords || (script.tags || []).join(", ")}
        image={script.thumbnail || "assets/logo.png"}
        url={`#/scripts/${script.id}`}
        jsonLd={{
          "@context": "https://schema.org",
          "@type": "SoftwareApplication",
          name: script.title,
          applicationCategory: "GameApplication",
          operatingSystem: "Roblox",
          description: script.description,
          image: script.thumbnail,
          aggregateRating: {
            "@type": "AggregateRating",
            ratingValue: "4.8",
            reviewCount: Math.max(1, Math.floor((script.views_total || 0) / 20)),
          },
          offers: { "@type": "Offer", price: "0", priceCurrency: "USD" },
        }}
      />

      <a href="#/scripts" className="btn btn-sm" style={{marginTop:8, marginBottom:24}}>← Back to scripts</a>

      <div className="detail">
        <div>
          <div className="detail-hero-thumb">
            {script.thumbnail ? (
              <img src={script.thumbnail} alt={script.title} />
            ) : (
              <div className="thumb-placeholder" style={{alignSelf:'center', margin:'auto'}}>Alarak</div>
            )}
          </div>

          <div className="row gap-8" style={{ marginTop: 20, flexWrap: "wrap" }}>
            {popular && <span className="badge badge-red">🔥 Popular</span>}
            <span className={"badge " + (script.status === "working" ? "badge-green" : "")}>
              {script.status === "working" ? "Working" : script.status}
            </span>
            {script.script_type && <span className="badge">{script.script_type}</span>}
            {(script.tags || []).map((t) => (
              <span key={t} className="badge">{t}</span>
            ))}
          </div>

          <h1 className="detail-title" style={{marginTop:16}}>{script.title}</h1>
          <p className="mono" style={{color:'var(--muted)', marginTop:6}}>{script.game}</p>

          {script.description && (
            <p style={{marginTop:20, fontSize:'1.05rem', lineHeight:1.7}}>{script.description}</p>
          )}

          {script.features && script.features.length > 0 && (
            <div className="glass detail-features" style={{marginTop:24}}>
              <div className="eyebrow" style={{marginBottom:12}}>Features</div>
              <ul>
                {script.features.map((f, i) => <li key={i}>{f}</li>)}
              </ul>
            </div>
          )}
        </div>

        <aside className="glass detail-side">
          <div className="stack-16">
            <div>
              <div className="eyebrow" style={{marginBottom:8}}>Stats</div>
              <div className="row gap-24" style={{flexWrap:'wrap'}}>
                <StatMini label="Views" value={formatViews(script.views_total)} />
                <StatMini label="24h" value={formatViews(script.views_24h)} />
                <StatMini label="7d" value={formatViews(script.views_7d)} />
              </div>
            </div>
            <a
              className="btn btn-primary btn-block btn-lg"
              href={script.script_link || "#"}
              target="_blank" rel="noopener noreferrer"
              onClick={(e) => {
                if (!script.script_link) {
                  e.preventDefault();
                  alert("This script has no link set. Add one in the admin panel.");
                }
              }}
            >
              Get Script <ArrowIcon />
            </a>
            <button
              className="btn btn-block"
              onClick={() => {
                navigator.clipboard.writeText(location.href).then(
                  () => alert("Link copied to clipboard!"),
                  () => alert("Failed to copy link")
                );
              }}
            >
              Share
            </button>
            <div style={{fontSize:'0.8rem', color:'var(--muted-2)', textAlign:'center'}}>
              Uploaded {new Date(script.created_at || Date.now()).toLocaleDateString()}
            </div>
          </div>
        </aside>
      </div>

      {related.length > 0 && (
        <section style={{marginTop:80}}>
          <div className="section-head">
            <h2 style={{fontSize:'1.6rem'}}>Related scripts</h2>
          </div>
          <div className="grid grid-3">
            {related.map((s) => <ScriptCard key={s.id} script={s} />)}
          </div>
        </section>
      )}
    </div>
  );
}

function StatMini({ label, value }) {
  return (
    <div>
      <div style={{fontFamily:'var(--font-mono)', fontSize:'1.4rem', fontWeight:600, letterSpacing:'-0.02em'}}>{value}</div>
      <div style={{fontSize:'0.72rem', textTransform:'uppercase', letterSpacing:'0.1em', color:'var(--muted)'}}>{label}</div>
    </div>
  );
}

window.ScriptDetailPage = ScriptDetailPage;
window.StatMini = StatMini;

/* === pages/executors.jsx === */
function ExecutorsPage() {
  const [all, setAll] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [q, setQ] = React.useState("");
  const [tier, setTier] = React.useState("all");

  React.useEffect(() => {
    let alive = true;
    DB.listExecutors().then((es) => {
      if (!alive) return;
      setAll(es);
      setLoading(false);
    });
    return () => (alive = false);
  }, []);

  const filtered = React.useMemo(() => {
    let list = all;
    if (tier !== "all") list = list.filter((e) => e.tier === tier);
    if (q) {
      const n = q.toLowerCase();
      list = list.filter(
        (e) =>
          e.title.toLowerCase().includes(n) ||
          (e.description || "").toLowerCase().includes(n) ||
          (e.platforms || []).some((p) => p.toLowerCase().includes(n))
      );
    }
    return list;
  }, [all, q, tier]);

  return (
    <div className="page page-fade">
      <SeoHead
        title="Roblox Executors"
        description="Free and paid Roblox executors for PC, Mac and Mobile. Reliable, tested executors curated by Alarak."
        keywords="roblox executor, roblox exploit, script executor, PC executor, mobile executor, mac executor"
        url="#/executors"
      />
      <div className="orb orb-1" />
      <section className="container" style={{paddingTop:60, position:'relative'}}>
        <div className="eyebrow">TOOLS</div>
        <h1 style={{fontSize:'clamp(2.4rem, 5vw, 3.6rem)', marginBottom:12}}>
          <span style={{color:'var(--red-hot)'}}>Executors</span>
        </h1>
        <p style={{color:'var(--muted)', maxWidth:640, fontSize:'1.05rem'}}>Curated Roblox executors for every platform. Only tested and trusted tools make the list.</p>

        <div style={{marginTop:32}}>
          <div className="search-wrap">
            <SearchIcon className="search-ico" />
            <input
              className="input"
              placeholder="Search executors, platforms…"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
          </div>
          <div className="filter-row">
            {["all", "free", "paid"].map((t) => (
              <button
                key={t}
                className={"chip " + (tier === t ? "active" : "")}
                onClick={() => setTier(t)}
              >
                {t}
              </button>
            ))}
          </div>
        </div>
      </section>

      <section className="container" style={{marginTop:40, paddingBottom:80}}>
        {loading ? (
          <LoadingBlock />
        ) : filtered.length === 0 ? (
          <Empty
            title={all.length === 0 ? "No executors yet" : "No matches"}
            message={all.length === 0 ? "Add your first executor from the admin panel." : "Try a different search."}
          />
        ) : (
          <div className="grid grid-3">
            {filtered.map((e, i) => (
              <Reveal key={e.id} delay={i * 40}>
                <ExecutorCard exec={e} />
              </Reveal>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

window.ExecutorsPage = ExecutorsPage;

/* === pages/executor-detail.jsx === */
function ExecutorDetailPage({ id }) {
  const [exec, setExec] = React.useState(null);
  const [related, setRelated] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [notFound, setNotFound] = React.useState(false);
  const cleanupRef = React.useRef(null);

  React.useEffect(() => {
    let alive = true;
    (async () => {
      const e = await DB.getExecutor(id).catch(() => null);
      if (!alive) return;
      if (!e) { setNotFound(true); setLoading(false); return; }
      setExec(e);
      setLoading(false);
      cleanupRef.current = DB.recordViewDelayed("executor", id, 5000);
      const all = await DB.listExecutors();
      if (!alive) return;
      setRelated(all.filter((x) => x.id !== id).slice(0, 3));
    })();
    return () => {
      alive = false;
      if (cleanupRef.current) cleanupRef.current();
    };
  }, [id]);

  if (loading) return <div className="page"><LoadingBlock /></div>;
  if (notFound || !exec)
    return (
      <div className="page container" style={{ paddingTop: 60 }}>
        <Empty title="Executor not found" message="This executor doesn't exist." action={<a href="#/executors" className="btn btn-primary" style={{marginTop:16}}>Back to executors</a>} />
      </div>
    );

  const popular = DB.isPopular(exec);

  return (
    <div className="page page-fade container">
      <SeoHead
        title={`${exec.title} — Roblox Executor`}
        description={exec.seo_description || exec.description || `Download ${exec.title}, a Roblox executor for ${(exec.platforms || []).join(', ')}.`}
        keywords={exec.seo_keywords || (exec.tags || []).join(", ")}
        image={exec.logo || "assets/logo.png"}
        url={`#/executors/${exec.id}`}
      />

      <a href="#/executors" className="btn btn-sm" style={{marginTop:8, marginBottom:24}}>← Back to executors</a>

      <div className="detail">
        <div>
          <div className="detail-hero-thumb">
            {exec.logo ? (
              <img src={exec.logo} alt={exec.title} />
            ) : (
              <div className="thumb-placeholder" style={{alignSelf:'center', margin:'auto'}}>Alarak</div>
            )}
          </div>

          <div className="row gap-8" style={{ marginTop: 20, flexWrap: "wrap" }}>
            {popular && <span className="badge badge-red">🔥 Popular</span>}
            <span className={"badge " + (exec.tier === "paid" ? "" : "badge-green")}>{exec.tier === "paid" ? "Paid" : "Free"}</span>
            {(exec.platforms || []).map((p) => <span key={p} className="badge badge-blue">{p}</span>)}
            {(exec.tags || []).map((t) => <span key={t} className="badge">{t}</span>)}
          </div>

          <h1 className="detail-title" style={{marginTop:16}}>{exec.title}</h1>

          {exec.description && (
            <p style={{marginTop:20, fontSize:'1.05rem', lineHeight:1.7}}>{exec.description}</p>
          )}

          {exec.features && exec.features.length > 0 && (
            <div className="glass detail-features" style={{marginTop:24}}>
              <div className="eyebrow" style={{marginBottom:12}}>Features</div>
              <ul>
                {exec.features.map((f, i) => <li key={i}>{f}</li>)}
              </ul>
            </div>
          )}
        </div>

        <aside className="glass detail-side">
          <div className="stack-16">
            <div>
              <div className="eyebrow" style={{marginBottom:8}}>Stats</div>
              <div className="row gap-24" style={{flexWrap:'wrap'}}>
                <StatMini label="Views" value={formatViews(exec.views_total)} />
                <StatMini label="24h" value={formatViews(exec.views_24h)} />
                <StatMini label="7d" value={formatViews(exec.views_7d)} />
              </div>
            </div>
            <a
              className="btn btn-primary btn-block btn-lg"
              href={exec.download_link || "#"}
              target="_blank" rel="noopener noreferrer"
              onClick={(e) => {
                if (!exec.download_link) {
                  e.preventDefault();
                  alert("This executor has no link set. Add one in the admin panel.");
                }
              }}
            >
              Get Executor <DownloadIcon />
            </a>
            <button
              className="btn btn-block"
              onClick={() => {
                navigator.clipboard.writeText(location.href).then(
                  () => alert("Link copied!"),
                  () => alert("Copy failed")
                );
              }}
            >
              Share
            </button>
            <div style={{fontSize:'0.8rem', color:'var(--muted-2)', textAlign:'center'}}>
              Added {new Date(exec.created_at || Date.now()).toLocaleDateString()}
            </div>
          </div>
        </aside>
      </div>

      {related.length > 0 && (
        <section style={{marginTop:80}}>
          <div className="section-head">
            <h2 style={{fontSize:'1.6rem'}}>More executors</h2>
          </div>
          <div className="grid grid-3">
            {related.map((e) => <ExecutorCard key={e.id} exec={e} />)}
          </div>
        </section>
      )}
    </div>
  );
}

window.ExecutorDetailPage = ExecutorDetailPage;

/* === pages/videos.jsx === */
function VideosPage() {
  const [homepage, setHomepage] = React.useState(null);
  const [videos, setVideos] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    let alive = true;
    DB.getHomepage().then(async (hp) => {
      if (!alive) return;
      setHomepage(hp);
      if (!hp.youtube_channel_url) {
        setLoading(false);
        setError("Set a YouTube channel URL in the admin panel to load videos.");
        return;
      }
      try {
        const data = await fetchYouTubeData(hp.youtube_channel_url);
        if (!alive) return;
        setVideos((data.videos || []).slice(0, 3));
      } catch (e) {
        if (!alive) return;
        setError("Couldn't load videos. Make sure the YouTube channel URL is correct.");
      } finally {
        if (alive) setLoading(false);
      }
    });
    return () => (alive = false);
  }, []);

  return (
    <div className="page page-fade">
      <SeoHead
        title="Recent Videos"
        description="Latest Roblox script showcase videos from the Alarak YouTube channel."
        keywords="roblox youtube, roblox script videos, alarak youtube"
        url="#/videos"
      />
      <div className="orb orb-1" />
      <section className="container" style={{paddingTop:60, position:'relative'}}>
        <div className="eyebrow">YOUTUBE</div>
        <h1 style={{fontSize:'clamp(2.4rem, 5vw, 3.6rem)', marginBottom:12}}>
          Recent <span style={{color:'var(--red-hot)'}}>videos</span>
        </h1>
        <p style={{color:'var(--muted)', maxWidth:640, fontSize:'1.05rem'}}>The three most recent uploads from the Alarak YouTube channel.</p>
        {homepage && homepage.youtube_channel_url && (
          <a
            className="btn btn-primary"
            style={{marginTop:20}}
            href={homepage.youtube_channel_url}
            target="_blank" rel="noopener noreferrer"
          >
            Subscribe on YouTube
          </a>
        )}
      </section>

      <section className="container" style={{marginTop:40, paddingBottom:80}}>
        {loading ? (
          <LoadingBlock label="Loading YouTube feed…" />
        ) : error ? (
          <Empty title="No videos to show" message={error} />
        ) : videos.length === 0 ? (
          <Empty title="No videos found" message="Check the channel URL in the admin panel." />
        ) : (
          <div className="grid grid-3">
            {videos.map((v, i) => (
              <Reveal key={v.id} delay={i * 80}>
                <a href={v.link} target="_blank" rel="noopener noreferrer" className="glass glass-hover video-card">
                  <div className="thumb">
                    <img src={v.thumbnail} alt={v.title} loading="lazy" />
                    <div className="video-play-overlay">
                      <div>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><polygon points="6 4 20 12 6 20 6 4"/></svg>
                      </div>
                    </div>
                  </div>
                  <div className="video-body">
                    <div className="card-title" style={{marginBottom:10}}>{v.title}</div>
                    <div className="row between">
                      <span className="mono" style={{fontSize:'0.8rem', color:'var(--muted)'}}>
                        {new Date(v.published).toLocaleDateString()}
                      </span>
                      <span className="btn btn-sm btn-primary" style={{pointerEvents:'none'}}>Watch <ArrowIcon /></span>
                    </div>
                  </div>
                </a>
              </Reveal>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

// ---- YouTube data fetching (via secure Supabase Edge Function) ----
// The YouTube Data API v3 key lives server-side as a Supabase Edge
// Function secret (see supabase/functions/youtube-latest) — it is never
// shipped to the browser. This replaces the old public-RSS-feed +
// free-CORS-proxy approach, which broke whenever a proxy went down or
// got rate-limited.
const YT_DATA_CACHE_PREFIX = "alarak:yt_data_cache:";
const YT_DATA_CACHE_MAX_AGE_MS = 30 * 60 * 1000; // 30 min — API quota is cheap, keep this fresh

function _ytDataCacheGet(key) {
  try {
    const raw = localStorage.getItem(YT_DATA_CACHE_PREFIX + key);
    if (!raw) return null;
    const { t, data } = JSON.parse(raw);
    if (!data || Date.now() - t > YT_DATA_CACHE_MAX_AGE_MS) return null;
    return data;
  } catch (e) {
    return null;
  }
}
function _ytDataCacheSet(key, data) {
  try {
    localStorage.setItem(YT_DATA_CACHE_PREFIX + key, JSON.stringify({ t: Date.now(), data }));
  } catch (e) {}
}

// Fetches { channelId, channelTitle, channelThumbnail, videos: [...] }
// for a channel URL/handle, via the youtube-latest Edge Function.
async function fetchYouTubeData(channelUrl, max = 6) {
  if (!channelUrl) throw new Error("No channel URL configured");
  const cacheKey = `${channelUrl}::${max}`;

  const cfg = window.ALARAK_CONFIG || {};
  if (!cfg.SUPABASE_URL || !cfg.SUPABASE_ANON_KEY) {
    const cached = _ytDataCacheGet(cacheKey);
    if (cached) return cached;
    throw new Error("Supabase is not configured");
  }

  const fnUrl = `${cfg.SUPABASE_URL}/functions/v1/youtube-latest?channel=${encodeURIComponent(
    channelUrl
  )}&max=${max}`;

  try {
    const res = await fetch(fnUrl, {
      headers: {
        apikey: cfg.SUPABASE_ANON_KEY,
        Authorization: `Bearer ${cfg.SUPABASE_ANON_KEY}`,
      },
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data?.error || "HTTP " + res.status);
    _ytDataCacheSet(cacheKey, data);
    return data;
  } catch (e) {
    // A brief function outage shouldn't blank out a page that was working
    // a moment ago — fall back to the last-known-good response.
    const cached = _ytDataCacheGet(cacheKey);
    if (cached) return cached;
    throw e;
  }
}

window.VideosPage = VideosPage;
window.fetchYouTubeData = fetchYouTubeData;

/* === admin/login.jsx === */
function AdminLoginPage({ onLoggedIn }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const s = await DB.signIn(email, password);
      onLoggedIn && onLoggedIn(s);
      location.hash = "#/admin";
    } catch (err) {
      setError(err.message || "Sign in failed. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-wrap page-fade">
      <SeoHead title="Sign in" robots="noindex, nofollow" />
      <div className="glass login-card">
        <img src="assets/logo.png" alt="Alarak" className="login-logo" />
        <div style={{textAlign:'center', marginBottom:24}}>
          <div className="eyebrow" style={{marginBottom:6}}>Admin</div>
          <h2 style={{fontSize:'1.6rem'}}>Sign in to continue</h2>
        </div>
        <form onSubmit={submit} className="stack-16">
          <label className="field">
            <span className="lbl">Email</span>
            <input
              className="input"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="admin@example.com"
              autoComplete="email"
              required
            />
          </label>
          <label className="field">
            <span className="lbl">Password</span>
            <input
              className="input"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete="current-password"
              required
            />
          </label>
          {error && (
            <div style={{color:'#ff8b8b', fontSize:'0.88rem', textAlign:'center'}}>{error}</div>
          )}
          <button type="submit" className="btn btn-primary btn-lg btn-block" disabled={loading}>
            {loading ? <Spinner size={16} /> : "Sign in"}
          </button>
          {!DB.hasSupabase && (
            <div style={{fontSize:'0.75rem', color:'var(--muted-2)', textAlign:'center', marginTop:4}}>
              Demo mode — any email + password (6+ chars) will sign you in.
            </div>
          )}
        </form>
      </div>
    </div>
  );
}

window.AdminLoginPage = AdminLoginPage;

/* === admin/analytics.jsx === */
/* ================================================================
   Alarak — Admin analytics widgets
   ------------------------------------------------------------------
   Pure presentation. Every chart here is computed client-side from
   data the dashboard already fetches (DB.siteStats, DB.listScripts,
   DB.listExecutors) — no new Supabase queries, no schema changes,
   no altered business logic. Safe, additive, display-only.
   ================================================================ */

/* ---------- shared helpers ---------- */
function _weekKey(d) {
  // Monday-anchored week bucket key, e.g. "2026-W07"
  const date = new Date(d);
  const day = (date.getUTCDay() + 6) % 7; // 0 = Monday
  date.setUTCDate(date.getUTCDate() - day);
  date.setUTCHours(0, 0, 0, 0);
  return date.getTime();
}

// Cumulative growth over the last `weeks` weeks, from real created_at dates.
function _growthSeries(items, weeks) {
  const now = Date.now();
  const buckets = [];
  for (let i = weeks - 1; i >= 0; i--) {
    buckets.push(now - i * 7 * 24 * 3600 * 1000);
  }
  const bucketKeys = buckets.map(_weekKey);
  const created = (items || [])
    .map((it) => new Date(it.created_at || 0).getTime())
    .filter((t) => !isNaN(t) && t > 0);

  return bucketKeys.map((bk, i) => {
    const upperBound = i < bucketKeys.length - 1 ? bucketKeys[i + 1] : Infinity;
    return created.filter((t) => t < upperBound + 7 * 24 * 3600 * 1000 && _weekKey(t) <= bk).length;
  });
}

function _formatShortDate(ts) {
  return new Date(ts).toLocaleDateString(undefined, { month: "short", day: "numeric" });
}

/* ---------- Mini sparkline (used inside StatCard) ---------- */
function Sparkline({ data, width = 120, height = 34, color = "var(--red-hot)" }) {
  if (!data || data.length < 2) return null;
  const max = Math.max(...data, 1);
  const min = Math.min(...data, 0);
  const range = max - min || 1;
  const stepX = width / (data.length - 1);
  const points = data.map((v, i) => {
    const x = i * stepX;
    const y = height - ((v - min) / range) * (height - 4) - 2;
    return [x, y];
  });
  const path = points.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(" ");
  const areaPath = `${path} L${width},${height} L0,${height} Z`;
  const last = points[points.length - 1];
  const gradId = "spark-grad-" + Math.round(max * 7 + data.length);
  return (
    <svg viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.35" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={areaPath} fill={`url(#${gradId})`} stroke="none" />
      <path d={path} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={last[0]} cy={last[1]} r="2.6" fill="#fff" stroke={color} strokeWidth="1.6" />
    </svg>
  );
}

/* ---------- Growth timeline (area chart) ---------- */
function GrowthTimeline({ scripts, executors }) {
  const weeks = 8;
  const combined = [...(scripts || []), ...(executors || [])];
  const series = React.useMemo(() => _growthSeries(combined, weeks), [scripts, executors]);

  const W = 640, H = 190, PAD = 24;
  const max = Math.max(...series, 4);
  const stepX = (W - PAD * 2) / (series.length - 1 || 1);
  const pts = series.map((v, i) => {
    const x = PAD + i * stepX;
    const y = H - PAD - (v / max) * (H - PAD * 1.6);
    return [x, y];
  });
  const linePath = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(" ");
  const areaPath = `${linePath} L${pts[pts.length - 1][0]},${H - PAD} L${pts[0][0]},${H - PAD} Z`;

  const now = Date.now();
  const firstLabel = _formatShortDate(now - (weeks - 1) * 7 * 24 * 3600 * 1000);
  const lastLabel = _formatShortDate(now);

  const hasAny = combined.length > 0;

  return (
    <div className="glass glass-hover chart-card">
      <div className="chart-card-head">
        <div>
          <h3>Content growth</h3>
          <div className="chart-card-sub">Scripts + executors added, last {weeks} weeks</div>
        </div>
        <div className="chip-tab-row">
          <span className="chip-tab active">Weekly</span>
        </div>
      </div>

      {hasAny ? (
        <>
          <svg className="area-chart" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
            <defs>
              <linearGradient id="growth-area" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="var(--red-hot)" stopOpacity="0.38" />
                <stop offset="100%" stopColor="var(--red-hot)" stopOpacity="0" />
              </linearGradient>
            </defs>
            {[0.25, 0.5, 0.75].map((f) => (
              <line key={f} className="grid-line" x1={PAD} x2={W - PAD} y1={PAD + f * (H - PAD * 1.6)} y2={PAD + f * (H - PAD * 1.6)} />
            ))}
            <path className="area-fill" d={areaPath} fill="url(#growth-area)" stroke="none" />
            <path className="line-path" d={linePath} />
            {pts.map((p, i) => (
              <circle key={i} className="dot" cx={p[0]} cy={p[1]} r="3.5" />
            ))}
          </svg>
          <div className="between" style={{ marginTop: 4 }}>
            <span className="chart-card-sub">{firstLabel}</span>
            <span className="chart-card-sub">{lastLabel}</span>
          </div>
        </>
      ) : (
        <div className="empty" style={{ padding: "40px 20px" }}>
          <p>Not enough content yet to chart growth.</p>
        </div>
      )}
    </div>
  );
}

/* ---------- Top content by views (horizontal bars) ---------- */
function TopContentBarList({ scripts, executors }) {
  const items = [
    ...(scripts || []).map((s) => ({ id: "s" + s.id, title: s.title, views: s.views_total || 0, icon: <ScrollIcon />, href: `#/scripts/${s.id}` })),
    ...(executors || []).map((e) => ({ id: "e" + e.id, title: e.title, views: e.views_total || 0, icon: <CpuIconSm />, href: `#/executors/${e.id}` })),
  ]
    .sort((a, b) => b.views - a.views)
    .slice(0, 5);

  const max = Math.max(...items.map((i) => i.views), 1);

  return (
    <div className="glass glass-hover chart-card">
      <div className="chart-card-head">
        <div>
          <h3>Top content</h3>
          <div className="chart-card-sub">Ranked by all-time views</div>
        </div>
      </div>
      {items.length === 0 ? (
        <div className="empty" style={{ padding: "40px 20px" }}>
          <p>No views recorded yet.</p>
        </div>
      ) : (
        <div className="bar-list">
          {items.map((it, i) => (
            <div className="bar-row" key={it.id}>
              <div className="bar-row-label">
                <span className={"bar-rank " + (i === 0 ? "top" : "")}>{i + 1}</span>
                <span>{it.title}</span>
              </div>
              <div className="bar-row-value">{formatViews(it.views)}</div>
              <div className="bar-track">
                <div className="bar-fill" style={{ width: Math.max(4, (it.views / max) * 100) + "%" }} />
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------- Views overview (24h / 7d / total) ---------- */
function ViewsOverviewChart({ stats }) {
  if (!stats) return null;
  const rows = [
    { label: "Last 24h", value: stats.views_24h || 0 },
    { label: "Last 7 days", value: stats.views_7d || 0 },
    { label: "All time", value: stats.views_total || 0 },
  ];
  const max = Math.max(...rows.map((r) => r.value), 1);
  return (
    <div className="glass glass-hover chart-card">
      <div className="chart-card-head">
        <div>
          <h3>Views overview</h3>
          <div className="chart-card-sub">Traffic across all scripts &amp; executors</div>
        </div>
      </div>
      <div className="bar-list">
        {rows.map((r) => (
          <div className="bar-row" key={r.label}>
            <div className="bar-row-label"><span>{r.label}</span></div>
            <div className="bar-row-value">{formatViews(r.value)}</div>
            <div className="bar-track">
              <div className="bar-fill" style={{ width: Math.max(4, (r.value / max) * 100) + "%" }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Script status donut ---------- */
const STATUS_COLORS = {
  working: "#6ee79e",
  patched: "#ff6b6b",
  beta: "#ffd166",
  other: "#8a8a92",
};
const STATUS_LABELS = { working: "Working", patched: "Patched", beta: "Beta", other: "Other" };

function ScriptStatusDonut({ scripts }) {
  const counts = { working: 0, patched: 0, beta: 0, other: 0 };
  (scripts || []).forEach((s) => {
    const k = counts.hasOwnProperty(s.status) ? s.status : "other";
    counts[k]++;
  });
  const total = scripts ? scripts.length : 0;
  const entries = Object.keys(counts).filter((k) => counts[k] > 0);

  const R = 60, C = 2 * Math.PI * R;
  let offset = 0;
  const segments = entries.map((k) => {
    const frac = total ? counts[k] / total : 0;
    const seg = {
      key: k,
      color: STATUS_COLORS[k],
      dash: `${frac * C} ${C - frac * C}`,
      dashoffset: -offset * C,
    };
    offset += frac;
    return seg;
  });

  return (
    <div className="glass glass-hover chart-card donut-card">
      <div style={{ width: "100%" }}>
        <div className="chart-card-head" style={{ marginBottom: 16 }}>
          <div>
            <h3>Script health</h3>
            <div className="chart-card-sub">By status</div>
          </div>
        </div>
        <div className="row gap-24" style={{ flexWrap: "wrap", justifyContent: "center" }}>
          <div className="donut-wrap">
            <svg width="148" height="148" viewBox="0 0 148 148">
              <circle cx="74" cy="74" r={R} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="16" />
              {total === 0 ? null : segments.map((s) => (
                <circle
                  key={s.key}
                  cx="74" cy="74" r={R}
                  fill="none"
                  stroke={s.color}
                  strokeWidth="16"
                  strokeDasharray={s.dash}
                  strokeDashoffset={s.dashoffset}
                  strokeLinecap="butt"
                  style={{ transition: "stroke-dasharray 1s var(--ease-out)" }}
                />
              ))}
            </svg>
            <div className="donut-center">
              <div className="donut-total">{total}</div>
              <div className="donut-label">Scripts</div>
            </div>
          </div>
          <div className="legend">
            {total === 0 ? (
              <span className="chart-card-sub">No scripts yet</span>
            ) : (
              entries.map((k) => (
                <div className="legend-item" key={k}>
                  <span className="legend-dot" style={{ background: STATUS_COLORS[k], color: STATUS_COLORS[k] }} />
                  <span>{STATUS_LABELS[k]}</span>
                  <span className="legend-value">{counts[k]}</span>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Sparkline,
  GrowthTimeline,
  TopContentBarList,
  ViewsOverviewChart,
  ScriptStatusDonut,
});

/* === admin/dashboard.jsx === */
function AdminShell({ children, active }) {
  const [session, setSession] = React.useState(null);
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    DB.getSession().then(setSession);
  }, []);

  // Close mobile drawer whenever the route changes.
  React.useEffect(() => {
    const onHash = () => setMenuOpen(false);
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Prevent background scroll while drawer is open
  React.useEffect(() => {
    if (menuOpen) {
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = ""; };
    }
  }, [menuOpen]);

  const nav = [
    { key: "dashboard", label: "Dashboard", href: "#/admin", icon: <DashIcon /> },
    { key: "scripts", label: "Scripts", href: "#/admin/scripts", icon: <ScrollIcon /> },
    { key: "executors", label: "Executors", href: "#/admin/executors", icon: <CpuIconSm /> },
    { key: "homepage", label: "Homepage", href: "#/admin/homepage", icon: <PageIcon /> },
    { key: "seo", label: "SEO", href: "#/admin/seo", icon: <SearchIconSm /> },
  ];

  const activeLabel = (nav.find(n => n.key === active) || nav[0]).label;

  const signOut = async () => {
    await DB.signOut();
    location.hash = "#/admin/login";
  };

  return (
    <div className="admin-shell page-fade">
      <SeoHead title="Admin" robots="noindex, nofollow" />

      {/* Mobile top bar */}
      <div className="admin-topbar">
        <div className="admin-brand">
          <img src="assets/logo.png" alt="" />
          <div>
            <div style={{fontSize:'0.95rem', lineHeight:1}}>Alarak</div>
            <div style={{fontSize:'0.66rem', color:'var(--muted)', letterSpacing:'0.1em', textTransform:'uppercase', marginTop:3}}>{activeLabel}</div>
          </div>
        </div>
        <button
          className="admin-menu-btn"
          aria-label="Open menu"
          onClick={() => setMenuOpen(true)}
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
        </button>
      </div>

      {/* Scrim for mobile drawer */}
      <div
        className={"admin-scrim " + (menuOpen ? "open" : "")}
        onClick={() => setMenuOpen(false)}
      />

      <aside className={"admin-side " + (menuOpen ? "open" : "")}>
        <div className="row gap-12" style={{justifyContent:'space-between'}}>
          <div className="row gap-12">
            <img src="assets/logo.png" alt="" style={{width:36, height:36, borderRadius:8}} />
            <div>
              <div style={{fontWeight:700}}>Alarak</div>
              <div style={{fontSize:'0.72rem', color:'var(--muted)', letterSpacing:'0.1em', textTransform:'uppercase'}}>Admin</div>
            </div>
          </div>
          {/* Close button — only visible on mobile */}
          <button
            className="admin-menu-btn"
            aria-label="Close menu"
            onClick={() => setMenuOpen(false)}
            style={{display:'none'}}
            data-mobile-close
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6l-12 12"/></svg>
          </button>
        </div>
        <div className="admin-nav">
          {nav.map((n) => (
            <a
              key={n.key}
              href={n.href}
              className={active === n.key ? "active" : ""}
              onClick={() => setMenuOpen(false)}
            >
              {n.icon}
              <span>{n.label}</span>
            </a>
          ))}
        </div>
        <div style={{marginTop:'auto', paddingTop:24}}>
          <a href="#/" className="btn btn-sm btn-ghost btn-block" style={{marginBottom:8}}>View site →</a>
          <button className="btn btn-sm btn-block" onClick={signOut}>Sign out</button>
          {session && (
            <div style={{marginTop:16, fontSize:'0.75rem', color:'var(--muted-2)', wordBreak:'break-all'}}>
              {session.email}
            </div>
          )}
        </div>
      </aside>
      <main className="admin-main">{children}</main>
    </div>
  );
}

function AdminDashboardPage() {
  const [stats, setStats] = React.useState(null);
  const [scripts, setScripts] = React.useState([]);
  const [executors, setExecutors] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let alive = true;
    Promise.all([DB.siteStats(), DB.listScripts(), DB.listExecutors()]).then(([s, ss, es]) => {
      if (!alive) return;
      setStats(s);
      setScripts(ss);
      setExecutors(es);
      setLoading(false);
    });
    return () => (alive = false);
  }, []);

  return (
    <AdminShell active="dashboard">
      <div className="between admin-page-head" style={{marginBottom:32, flexWrap:'wrap', gap:16}}>
        <div>
          <div className="eyebrow">Overview</div>
          <h1 style={{fontSize:'2rem'}}>Dashboard</h1>
        </div>
        <div className="row gap-12 admin-head-actions" style={{flexWrap:'wrap'}}>
          <a href="#/admin/scripts" className="btn btn-primary">+ New script</a>
          <a href="#/admin/executors" className="btn">+ New executor</a>
        </div>
      </div>

      {loading ? (
        <LoadingBlock />
      ) : (
        <>
          <div className="stat-grid">
            <StatCard
              label="Total scripts"
              value={stats.scripts_total}
              icon={<ScrollIcon />}
              spark={_growthSeries(scripts, 8)}
            />
            <StatCard
              label="Total executors"
              value={stats.executors_total}
              icon={<CpuIconSm />}
              spark={_growthSeries(executors, 8)}
            />
            <StatCard label="Views · 24h" value={stats.views_24h} format={formatViews} icon={<EyeIcon />} accent />
            <StatCard label="Views · last 7 days" value={stats.views_7d} format={formatViews} icon={<TrendIcon />} />
          </div>

          <div className="analytics-grid">
            <GrowthTimeline scripts={scripts} executors={executors} />
            <TopContentBarList scripts={scripts} executors={executors} />
          </div>

          <div className="analytics-secondary-grid">
            <ViewsOverviewChart stats={stats} />
            <ScriptStatusDonut scripts={scripts} />
          </div>

          <div className="admin-recent-grid">
            <RecentScriptsCard scripts={scripts} />
            <RecentExecutorsCard executors={executors} />
          </div>
        </>
      )}
    </AdminShell>
  );
}

/* ---------- Recent scripts (redesigned) ---------- */
function RecentScriptsCard({ scripts }) {
  return (
    <div className="glass recent-card">
      <div className="recent-head">
        <div>
          <div className="eyebrow" style={{marginBottom:4}}>Latest</div>
          <h3 style={{margin:0}}>Recent scripts</h3>
        </div>
        <a href="#/admin/scripts" className="btn btn-sm">Manage →</a>
      </div>

      {scripts.length === 0 ? (
        <div className="recent-empty">
          <div className="recent-empty-ico"><ScrollIcon /></div>
          <div>
            <div style={{fontWeight:600, marginBottom:4}}>No scripts yet</div>
            <div style={{fontSize:'0.85rem', color:'var(--muted)'}}>Upload your first one to see it here.</div>
          </div>
          <a href="#/admin/scripts" className="btn btn-sm btn-primary">+ New</a>
        </div>
      ) : (
        <div className="recent-list">
          {scripts.slice(0, 5).map((s) => {
            const popular = DB.isPopular ? DB.isPopular(s) : false;
            return (
              <a
                key={s.id}
                href={`#/scripts/${s.id}`}
                className="recent-item"
                aria-label={s.title}
              >
                <div className="recent-thumb-wrap">
                  {s.thumbnail ? (
                    <img src={s.thumbnail} className="recent-thumb" alt="" loading="lazy" />
                  ) : (
                    <div className="recent-thumb recent-thumb-fallback">
                      <ScrollIcon />
                    </div>
                  )}
                  {popular && <span className="recent-pop">🔥</span>}
                </div>
                <div className="recent-body">
                  <div className="recent-title">{s.title}</div>
                  <div className="recent-sub">
                    <span className="recent-game">{s.game || "Roblox"}</span>
                    {s.status === "working" && (
                      <span className="recent-dot recent-dot-green" title="Working" />
                    )}
                    {s.script_type && (
                      <span className="recent-type">{s.script_type}</span>
                    )}
                  </div>
                </div>
                <div className="recent-stats">
                  <div className="recent-views">
                    <EyeIcon /> {formatViews(s.views_total)}
                  </div>
                  <div className="recent-views-label">views</div>
                </div>
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ---------- Recent executors (redesigned) ---------- */
function RecentExecutorsCard({ executors }) {
  return (
    <div className="glass recent-card">
      <div className="recent-head">
        <div>
          <div className="eyebrow" style={{marginBottom:4}}>Latest</div>
          <h3 style={{margin:0}}>Recent executors</h3>
        </div>
        <a href="#/admin/executors" className="btn btn-sm">Manage →</a>
      </div>

      {executors.length === 0 ? (
        <div className="recent-empty">
          <div className="recent-empty-ico"><CpuIconSm /></div>
          <div>
            <div style={{fontWeight:600, marginBottom:4}}>No executors yet</div>
            <div style={{fontSize:'0.85rem', color:'var(--muted)'}}>Add one from the Executors tab.</div>
          </div>
          <a href="#/admin/executors" className="btn btn-sm btn-primary">+ New</a>
        </div>
      ) : (
        <div className="recent-list">
          {executors.slice(0, 5).map((e) => (
            <a
              key={e.id}
              href={`#/executors/${e.id}`}
              className="recent-item"
              aria-label={e.title}
            >
              <div className="recent-thumb-wrap">
                {e.logo ? (
                  <img src={e.logo} className="recent-thumb" alt="" loading="lazy" />
                ) : (
                  <div className="recent-thumb recent-thumb-fallback">
                    <CpuIconSm />
                  </div>
                )}
              </div>
              <div className="recent-body">
                <div className="recent-title">{e.title}</div>
                <div className="recent-sub">
                  <span className={"recent-tier " + (e.tier === "paid" ? "paid" : "free")}>
                    {e.tier === "paid" ? "Paid" : "Free"}
                  </span>
                  <span className="recent-platforms">
                    {(e.platforms || []).slice(0, 2).join(" · ") || "—"}
                  </span>
                </div>
              </div>
              <div className="recent-stats">
                <div className="recent-views">
                  <EyeIcon /> {formatViews(e.views_total)}
                </div>
                <div className="recent-views-label">views</div>
              </div>
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

function StatCard({ label, value, icon, accent, format, spark }) {
  return (
    <div className={"glass glass-hover stat"} style={accent ? {borderColor:'rgba(255,42,42,0.35)', boxShadow:'0 8px 30px rgba(255,42,42,0.12)'} : {}}>
      <div className="row between">
        <div className="stat-icon-chip">{icon}</div>
      </div>
      <div className="stat-label" style={{marginTop:14}}>{label}</div>
      <div className="stat-value">
        <AnimatedNumber value={value} format={format} />
      </div>
      {spark && spark.length > 1 && (
        <div className="stat-spark">
          <Sparkline data={spark} color={accent ? "var(--red-hot)" : "var(--muted)"} />
        </div>
      )}
    </div>
  );
}

/* ---- Icons ---- */
function DashIcon() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg>; }
function ScrollIcon() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M8 21h8a2 2 0 0 0 2-2V7l-5-5H8a2 2 0 0 0-2 2v3"/><path d="M13 2v5h5"/><path d="M2 15h6M2 11h4M2 19h6"/></svg>; }
function CpuIconSm() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><rect x="5" y="5" width="14" height="14" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3"/></svg>; }
function PageIcon() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><rect x="4" y="3" width="16" height="18" rx="2"/><path d="M8 8h8M8 12h8M8 16h5"/></svg>; }
function SearchIconSm() { return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>; }
function TrendIcon() { return <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 17 9 11l4 4L21 7"/><path d="M14 7h7v7"/></svg>; }

Object.assign(window, { AdminShell, AdminDashboardPage, StatCard, RecentScriptsCard, RecentExecutorsCard });

/* === admin/manage-scripts.jsx === */
function AdminScriptsPage() {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [editing, setEditing] = React.useState(null);
  const [q, setQ] = React.useState("");
  const toast = useToast();

  const load = React.useCallback(() => {
    setLoading(true);
    DB.listScripts().then((ss) => {
      setItems(ss);
      setLoading(false);
    });
  }, []);
  React.useEffect(load, [load]);

  const filtered = q
    ? items.filter((s) => s.title.toLowerCase().includes(q.toLowerCase()) || (s.game || "").toLowerCase().includes(q.toLowerCase()))
    : items;

  const del = async (id) => {
    if (!confirm("Delete this script? This can't be undone.")) return;
    await DB.deleteScript(id);
    toast("Script deleted", "ok");
    load();
  };

  return (
    <AdminShell active="scripts">
      <div className="between" style={{marginBottom:24, flexWrap:'wrap', gap:16}}>
        <div>
          <div className="eyebrow">Content</div>
          <h1 style={{fontSize:'2rem'}}>Scripts</h1>
        </div>
        <button className="btn btn-primary" onClick={() => setEditing({})}>+ Upload new script</button>
      </div>

      <div className="glass" style={{padding:20, marginBottom:20}}>
        <div className="search-wrap">
          <svg className="search-ico" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
          <input className="input" placeholder="Search scripts…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
      </div>

      <div className="glass" style={{padding:0, overflow:'hidden'}}>
        {loading ? (
          <div style={{padding:60}}><LoadingBlock /></div>
        ) : filtered.length === 0 ? (
          <div style={{padding:40}}>
            <Empty title={items.length === 0 ? "No scripts yet" : "No matches"} message={items.length === 0 ? "Upload your first script." : "Try a different search."} />
          </div>
        ) : (
          <div style={{overflowX:'auto'}}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>Script</th>
                  <th>Game</th>
                  <th>Views</th>
                  <th>24h</th>
                  <th>Tags</th>
                  <th style={{textAlign:'right'}}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((s) => (
                  <tr key={s.id}>
                    <td>
                      <div className="row gap-12" style={{minWidth:0}}>
                        <img src={s.thumbnail || "assets/logo.png"} className="row-thumb" alt="" />
                        <div style={{minWidth:0}}>
                          <div style={{fontWeight:600}}>{s.title}</div>
                          <div style={{fontSize:'0.75rem', color:'var(--muted)'}}>{s.script_type}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{color:'var(--muted)'}}>{s.game || "—"}</td>
                    <td className="mono">{formatViews(s.views_total)}</td>
                    <td className="mono">
                      {formatViews(s.views_24h)}{DB.isPopular(s) ? <span className="badge badge-red" style={{marginLeft:8}}>🔥</span> : null}
                    </td>
                    <td>
                      <div className="row gap-8" style={{flexWrap:'wrap', maxWidth:200}}>
                        {(s.tags || []).slice(0, 3).map((t) => <span key={t} className="badge">{t}</span>)}
                      </div>
                    </td>
                    <td style={{textAlign:'right'}}>
                      <div className="row gap-8" style={{justifyContent:'flex-end'}}>
                        <a href={`#/scripts/${s.id}`} target="_blank" className="btn btn-sm">View</a>
                        <button className="btn btn-sm" onClick={() => setEditing(s)}>Edit</button>
                        <button className="btn btn-sm" onClick={() => del(s.id)} style={{color:'#ff8b8b', borderColor:'rgba(255,42,42,0.3)'}}>Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <ScriptEditor
        open={editing !== null}
        initial={editing || {}}
        onClose={() => setEditing(null)}
        onSaved={() => { setEditing(null); toast("Script saved", "ok"); load(); }}
      />
    </AdminShell>
  );
}

function ScriptEditor({ open, initial, onClose, onSaved }) {
  const [form, setForm] = React.useState(initial);
  React.useEffect(() => { setForm(initial); }, [initial, open]);
  const [saving, setSaving] = React.useState(false);

  if (!open) return null;
  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const save = async () => {
    setSaving(true);
    try {
      const payload = {
        ...form,
        tags: strToArr(form.tags),
        features: strToArr(form.features, "\n"),
      };
      await DB.upsertScript(payload);
      onSaved && onSaved();
    } catch (e) {
      alert("Save failed: " + (e.message || e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title={initial.id ? "Edit script" : "Upload new script"} wide>
      <div className="stack-16">
        <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:16}}>
          <Field label="Title *">
            <input className="input" value={form.title || ""} onChange={(e) => update("title", e.target.value)} placeholder="Blox Fruits — Auto Farm" />
          </Field>
          <Field label="Game name">
            <input className="input" value={form.game || ""} onChange={(e) => update("game", e.target.value)} placeholder="Blox Fruits" />
          </Field>
        </div>
        <Field label="Description">
          <textarea className="textarea" value={form.description || ""} onChange={(e) => update("description", e.target.value)} placeholder="What does this script do?" style={{fontFamily:'var(--font-display)'}} />
        </Field>
        <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:16}}>
          <Field label="Thumbnail image URL">
            <input className="input" value={form.thumbnail || ""} onChange={(e) => update("thumbnail", e.target.value)} placeholder="https://…jpg" />
          </Field>
          <Field label="Script link (redirect on 'Get Script')">
            <input className="input" value={form.script_link || ""} onChange={(e) => update("script_link", e.target.value)} placeholder="https://pastebin.com/…" />
          </Field>
        </div>
        <div className="grid" style={{gridTemplateColumns:'1fr 1fr 1fr', gap:16}}>
          <Field label="Script type">
            <select className="select input" value={form.script_type || "keyless"} onChange={(e) => update("script_type", e.target.value)}>
              <option value="keyless">Keyless</option>
              <option value="key">Key system</option>
              <option value="paid">Paid</option>
            </select>
          </Field>
          <Field label="Status">
            <select className="select input" value={form.status || "working"} onChange={(e) => update("status", e.target.value)}>
              <option value="working">Working</option>
              <option value="patched">Patched</option>
              <option value="beta">Beta</option>
            </select>
          </Field>
          <Field label="Tags (comma-separated)">
            <input className="input" value={arrToStr(form.tags)} onChange={(e) => update("tags", e.target.value)} placeholder="auto farm, teleport" />
          </Field>
        </div>
        <Field label="Features (one per line)">
          <textarea className="textarea" value={arrToStr(form.features, "\n")} onChange={(e) => update("features", e.target.value)} placeholder={"Auto Farm\nAuto Sea Events\nESP"} />
        </Field>

        <div style={{marginTop:8, paddingTop:20, borderTop:'1px solid var(--line)'}}>
          <div className="eyebrow" style={{marginBottom:12}}>SEO — this script</div>
          <div className="stack-16">
            <Field label="SEO keywords / hashtags (comma-separated)">
              <input className="input" value={form.seo_keywords || ""} onChange={(e) => update("seo_keywords", e.target.value)} placeholder="blox fruits script, auto farm blox fruits, blox fruits hack" />
            </Field>
            <Field label="SEO description (max 160 chars recommended)">
              <textarea className="textarea" value={form.seo_description || ""} onChange={(e) => update("seo_description", e.target.value)} placeholder="Best working Blox Fruits auto farm script — updated for the latest update." style={{fontFamily:'var(--font-display)'}} />
            </Field>
          </div>
        </div>

        <div className="row gap-12" style={{justifyContent:'flex-end', paddingTop:8}}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={save} disabled={saving}>
            {saving ? <Spinner size={16} /> : (initial.id ? "Save changes" : "Upload script")}
          </button>
        </div>
      </div>
    </Modal>
  );
}

function Field({ label, children }) {
  return (
    <label className="field">
      <span className="lbl">{label}</span>
      {children}
    </label>
  );
}
function arrToStr(v, sep = ", ") {
  if (Array.isArray(v)) return v.join(sep);
  return v || "";
}
function strToArr(v, sep) {
  if (Array.isArray(v)) return v;
  if (!v) return [];
  const s = sep || ",";
  return v.split(s).map((x) => x.trim()).filter(Boolean);
}

Object.assign(window, { AdminScriptsPage, ScriptEditor, Field, arrToStr, strToArr });

/* === admin/manage-executors.jsx === */
function AdminExecutorsPage() {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [editing, setEditing] = React.useState(null);
  const [q, setQ] = React.useState("");
  const toast = useToast();

  const load = React.useCallback(() => {
    setLoading(true);
    DB.listExecutors().then((es) => { setItems(es); setLoading(false); });
  }, []);
  React.useEffect(load, [load]);

  const filtered = q ? items.filter((e) => e.title.toLowerCase().includes(q.toLowerCase())) : items;

  const del = async (id) => {
    if (!confirm("Delete this executor?")) return;
    await DB.deleteExecutor(id);
    toast("Executor deleted", "ok");
    load();
  };

  return (
    <AdminShell active="executors">
      <div className="between" style={{marginBottom:24, flexWrap:'wrap', gap:16}}>
        <div>
          <div className="eyebrow">Content</div>
          <h1 style={{fontSize:'2rem'}}>Executors</h1>
        </div>
        <button className="btn btn-primary" onClick={() => setEditing({})}>+ Upload new executor</button>
      </div>

      <div className="glass" style={{padding:20, marginBottom:20}}>
        <div className="search-wrap">
          <svg className="search-ico" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
          <input className="input" placeholder="Search executors…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
      </div>

      <div className="glass" style={{padding:0, overflow:'hidden'}}>
        {loading ? (
          <div style={{padding:60}}><LoadingBlock /></div>
        ) : filtered.length === 0 ? (
          <div style={{padding:40}}>
            <Empty title={items.length === 0 ? "No executors yet" : "No matches"} message={items.length === 0 ? "Upload your first executor." : "Try a different search."} />
          </div>
        ) : (
          <div style={{overflowX:'auto'}}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>Executor</th>
                  <th>Tier</th>
                  <th>Platforms</th>
                  <th>Views</th>
                  <th>24h</th>
                  <th style={{textAlign:'right'}}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((e) => (
                  <tr key={e.id}>
                    <td>
                      <div className="row gap-12" style={{minWidth:0}}>
                        <img src={e.logo || "assets/logo.png"} className="row-thumb" alt="" />
                        <div style={{minWidth:0}}>
                          <div style={{fontWeight:600}}>{e.title}</div>
                          <div style={{fontSize:'0.75rem', color:'var(--muted)', maxWidth:280, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{e.description}</div>
                        </div>
                      </div>
                    </td>
                    <td><span className={"badge " + (e.tier === "paid" ? "" : "badge-green")}>{e.tier === "paid" ? "Paid" : "Free"}</span></td>
                    <td style={{color:'var(--muted)'}}>{(e.platforms || []).join(", ") || "—"}</td>
                    <td className="mono">{formatViews(e.views_total)}</td>
                    <td className="mono">{formatViews(e.views_24h)}</td>
                    <td style={{textAlign:'right'}}>
                      <div className="row gap-8" style={{justifyContent:'flex-end'}}>
                        <a href={`#/executors/${e.id}`} target="_blank" className="btn btn-sm">View</a>
                        <button className="btn btn-sm" onClick={() => setEditing(e)}>Edit</button>
                        <button className="btn btn-sm" onClick={() => del(e.id)} style={{color:'#ff8b8b', borderColor:'rgba(255,42,42,0.3)'}}>Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <ExecutorEditor
        open={editing !== null}
        initial={editing || {}}
        onClose={() => setEditing(null)}
        onSaved={() => { setEditing(null); toast("Executor saved", "ok"); load(); }}
      />
    </AdminShell>
  );
}

function ExecutorEditor({ open, initial, onClose, onSaved }) {
  const [form, setForm] = React.useState(initial);
  React.useEffect(() => setForm(initial), [initial, open]);
  const [saving, setSaving] = React.useState(false);

  if (!open) return null;
  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const togglePlat = (p) => {
    const cur = form.platforms || [];
    update("platforms", cur.includes(p) ? cur.filter((x) => x !== p) : [...cur, p]);
  };

  const save = async () => {
    setSaving(true);
    try {
      const payload = {
        ...form,
        tags: strToArr(form.tags),
        features: strToArr(form.features, "\n"),
        platforms: Array.isArray(form.platforms) ? form.platforms : ["PC"],
      };
      await DB.upsertExecutor(payload);
      onSaved && onSaved();
    } catch (e) {
      alert("Save failed: " + (e.message || e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title={initial.id ? "Edit executor" : "Upload new executor"} wide>
      <div className="stack-16">
        <Field label="Title *">
          <input className="input" value={form.title || ""} onChange={(e) => update("title", e.target.value)} placeholder="Fluxus" />
        </Field>
        <Field label="Description">
          <textarea className="textarea" value={form.description || ""} onChange={(e) => update("description", e.target.value)} placeholder="A short description of this executor…" style={{fontFamily:'var(--font-display)'}} />
        </Field>
        <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:16}}>
          <Field label="Logo image URL">
            <input className="input" value={form.logo || ""} onChange={(e) => update("logo", e.target.value)} placeholder="https://…png" />
          </Field>
          <Field label="Download link (redirect on 'Get Executor')">
            <input className="input" value={form.download_link || ""} onChange={(e) => update("download_link", e.target.value)} placeholder="https://…" />
          </Field>
        </div>
        <div className="grid" style={{gridTemplateColumns:'1fr 2fr', gap:16}}>
          <Field label="Tier">
            <select className="select input" value={form.tier || "free"} onChange={(e) => update("tier", e.target.value)}>
              <option value="free">Free</option>
              <option value="paid">Paid</option>
            </select>
          </Field>
          <Field label="Platforms">
            <div className="row gap-8" style={{flexWrap:'wrap', paddingTop:8}}>
              {["PC", "Mac", "Mobile", "Android", "iOS"].map((p) => (
                <button
                  key={p}
                  type="button"
                  className={"chip " + ((form.platforms || []).includes(p) ? "active" : "")}
                  onClick={() => togglePlat(p)}
                >
                  {p}
                </button>
              ))}
            </div>
          </Field>
        </div>
        <Field label="Tags (comma-separated)">
          <input className="input" value={arrToStr(form.tags)} onChange={(e) => update("tags", e.target.value)} placeholder="lightweight, fast, ui" />
        </Field>
        <Field label="Features (one per line)">
          <textarea className="textarea" value={arrToStr(form.features, "\n")} onChange={(e) => update("features", e.target.value)} placeholder={"Level 8 execution\nBuilt-in script hub\nAuto-update"} />
        </Field>

        <div style={{marginTop:8, paddingTop:20, borderTop:'1px solid var(--line)'}}>
          <div className="eyebrow" style={{marginBottom:12}}>SEO — this executor</div>
          <div className="stack-16">
            <Field label="SEO keywords / hashtags">
              <input className="input" value={form.seo_keywords || ""} onChange={(e) => update("seo_keywords", e.target.value)} placeholder="fluxus executor, roblox pc executor, best free executor" />
            </Field>
            <Field label="SEO description">
              <textarea className="textarea" value={form.seo_description || ""} onChange={(e) => update("seo_description", e.target.value)} placeholder="Download Fluxus, a fast free Roblox executor…" style={{fontFamily:'var(--font-display)'}} />
            </Field>
          </div>
        </div>

        <div className="row gap-12" style={{justifyContent:'flex-end', paddingTop:8}}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={save} disabled={saving}>
            {saving ? <Spinner size={16} /> : (initial.id ? "Save changes" : "Upload executor")}
          </button>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { AdminExecutorsPage, ExecutorEditor });

/* === admin/homepage-info.jsx === */
function AdminHomepagePage() {
  const [form, setForm] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const toast = useToast();

  React.useEffect(() => { DB.getHomepage().then(setForm); }, []);

  if (!form) return <AdminShell active="homepage"><LoadingBlock /></AdminShell>;

  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const save = async () => {
    setSaving(true);
    try {
      await DB.setHomepage(form);
      toast("Homepage updated", "ok");
    } catch (e) {
      alert("Save failed: " + (e.message || e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <AdminShell active="homepage">
      <div className="between" style={{marginBottom:24}}>
        <div>
          <div className="eyebrow">Content</div>
          <h1 style={{fontSize:'2rem'}}>Homepage & YouTube</h1>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:20}}>
        <div className="glass" style={{padding:24}}>
          <h3 style={{marginBottom:16}}>Hero</h3>
          <div className="stack-16">
            <Field label="Hero title">
              <input className="input" value={form.hero_title || ""} onChange={(e) => update("hero_title", e.target.value)} />
            </Field>
            <Field label="Hero subtitle">
              <textarea className="textarea" value={form.hero_subtitle || ""} onChange={(e) => update("hero_subtitle", e.target.value)} style={{fontFamily:'var(--font-display)'}} />
            </Field>
          </div>
        </div>

        <div className="glass" style={{padding:24}}>
          <h3 style={{marginBottom:16}}>YouTube channel</h3>
          <div className="stack-16">
            <Field label="Channel URL">
              <input className="input" value={form.youtube_channel_url || ""} onChange={(e) => update("youtube_channel_url", e.target.value)} placeholder="https://www.youtube.com/@alarak" />
            </Field>
            <Field label="Channel display name">
              <input className="input" value={form.youtube_channel_name || ""} onChange={(e) => update("youtube_channel_name", e.target.value)} placeholder="Alarak" />
            </Field>
            <Field label="Latest video ID (optional — for homepage embed if channel embed fails)">
              <input className="input" value={form.latest_video_id || ""} onChange={(e) => update("latest_video_id", e.target.value)} placeholder="dQw4w9WgXcQ" />
            </Field>
            <div style={{fontSize:'0.78rem', color:'var(--muted)'}}>
              Videos page and homepage embed auto-load the latest uploads from this channel via the YouTube Data API v3, through a secure server-side proxy (your API key never reaches the browser).
            </div>
          </div>
        </div>
      </div>

      <div className="row" style={{marginTop:24, justifyContent:'flex-end'}}>
        <button className="btn btn-primary btn-lg" onClick={save} disabled={saving}>
          {saving ? <Spinner size={16} /> : "Save changes"}
        </button>
      </div>
    </AdminShell>
  );
}

window.AdminHomepagePage = AdminHomepagePage;

/* === admin/seo-settings.jsx === */
function AdminSeoPage() {
  const [form, setForm] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const toast = useToast();

  React.useEffect(() => { DB.getSeo().then(setForm); }, []);

  if (!form) return <AdminShell active="seo"><LoadingBlock /></AdminShell>;

  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const save = async () => {
    setSaving(true);
    try {
      await DB.setSeo(form);
      toast("SEO updated", "ok");
    } catch (e) {
      alert("Save failed: " + (e.message || e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <AdminShell active="seo">
      <div className="between" style={{marginBottom:24}}>
        <div>
          <div className="eyebrow">Rankings</div>
          <h1 style={{fontSize:'2rem'}}>SEO settings</h1>
          <p style={{color:'var(--muted)', marginTop:8, maxWidth:640}}>These meta tags apply site-wide. Individual scripts and executors have their own SEO keywords/descriptions in their editor.</p>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:20}}>
        <div className="glass" style={{padding:24}}>
          <h3 style={{marginBottom:16}}>Site meta</h3>
          <div className="stack-16">
            <Field label="Site title (used on homepage & fallback)">
              <input className="input" value={form.site_title || ""} onChange={(e) => update("site_title", e.target.value)} />
            </Field>
            <Field label="Site description (default meta description)">
              <textarea className="textarea" value={form.site_description || ""} onChange={(e) => update("site_description", e.target.value)} style={{fontFamily:'var(--font-display)'}} />
            </Field>
            <Field label="Global keywords / hashtags (comma-separated)">
              <textarea className="textarea" value={form.site_keywords || ""} onChange={(e) => update("site_keywords", e.target.value)} style={{fontFamily:'var(--font-display)'}} placeholder="roblox scripts, alarak, roblox exploits…" />
            </Field>
          </div>
        </div>

        <div className="glass" style={{padding:24}}>
          <h3 style={{marginBottom:16}}>Social & sharing</h3>
          <div className="stack-16">
            <Field label="Open Graph / Twitter image URL">
              <input className="input" value={form.og_image || ""} onChange={(e) => update("og_image", e.target.value)} placeholder="https://…png" />
            </Field>
            <Field label="Twitter handle">
              <input className="input" value={form.twitter_handle || ""} onChange={(e) => update("twitter_handle", e.target.value)} placeholder="@alarak" />
            </Field>
            <Field label="Canonical base URL (your site's root)">
              <input className="input" value={form.canonical_base || ""} onChange={(e) => update("canonical_base", e.target.value)} placeholder="https://alarak.com" />
            </Field>
            <div style={{fontSize:'0.78rem', color:'var(--muted)'}}>
              Tip: after you deploy, set this to your production domain so canonical + OG URLs point to the right place.
            </div>
          </div>
        </div>
      </div>

      <div className="row" style={{marginTop:24, justifyContent:'flex-end'}}>
        <button className="btn btn-primary btn-lg" onClick={save} disabled={saving}>
          {saving ? <Spinner size={16} /> : "Save changes"}
        </button>
      </div>
    </AdminShell>
  );
}

window.AdminSeoPage = AdminSeoPage;

/* === app.jsx === */
/* ================================================================
   Alarak — Router + App Entry
   ================================================================ */

function useHashRoute() {
  const [hash, setHash] = React.useState(location.hash || "#/");
  React.useEffect(() => {
    const onHash = () => {
      setHash(location.hash || "#/");
      window.scrollTo({ top: 0, behavior: "smooth" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // route path (without query)
  const path = hash.replace(/^#/, "").split("?")[0] || "/";
  return { path, hash };
}

function App() {
  const { path } = useHashRoute();
  const [session, setSession] = React.useState(null);
  const [sessionChecked, setSessionChecked] = React.useState(false);

  React.useEffect(() => {
    DB.getSession().then((s) => {
      setSession(s);
      setSessionChecked(true);
    });
  }, [path]);

  // Route
  let content = null;
  let showNav = true;
  let showFooter = true;

  // Admin routes
  if (path.startsWith("/admin")) {
    showNav = false;
    showFooter = false;
    if (path === "/admin/login") {
      content = <AdminLoginPage onLoggedIn={setSession} />;
    } else {
      // Guarded
      if (!sessionChecked) {
        content = <LoadingBlock />;
      } else if (!session) {
        // redirect
        location.hash = "#/admin/login";
        content = <LoadingBlock />;
      } else if (path === "/admin" || path === "/admin/") {
        content = <AdminDashboardPage />;
      } else if (path === "/admin/scripts") {
        content = <AdminScriptsPage />;
      } else if (path === "/admin/executors") {
        content = <AdminExecutorsPage />;
      } else if (path === "/admin/homepage") {
        content = <AdminHomepagePage />;
      } else if (path === "/admin/seo") {
        content = <AdminSeoPage />;
      } else {
        content = <NotFound />;
      }
    }
  }
  // Public routes
  else if (path === "/" || path === "") {
    content = <HomePage />;
  } else if (path === "/scripts") {
    content = <ScriptsPage />;
  } else if (path.startsWith("/scripts/")) {
    const id = path.slice("/scripts/".length);
    content = <ScriptDetailPage id={id} />;
  } else if (path === "/executors") {
    content = <ExecutorsPage />;
  } else if (path.startsWith("/executors/")) {
    const id = path.slice("/executors/".length);
    content = <ExecutorDetailPage id={id} />;
  } else if (path === "/videos") {
    content = <VideosPage />;
  } else {
    content = <NotFound />;
  }

  return (
    <ToastProvider>
      {showNav && <Navbar route={path} />}
      <div key={path}>{content}</div>
      {showFooter && <Footer />}
    </ToastProvider>
  );
}

function NotFound() {
  return (
    <div className="page container" style={{ paddingTop: 80, textAlign: "center" }}>
      <SeoHead title="Not Found" robots="noindex" />
      <img src="assets/logo.png" alt="" style={{width:80, height:80, borderRadius:16, margin:'0 auto 20px', opacity:0.5}} />
      <h1 style={{ fontSize: "3rem" }}>404</h1>
      <p style={{ color: "var(--muted)", marginTop: 8 }}>Page not found.</p>
      <a href="#/" className="btn btn-primary" style={{ marginTop: 20 }}>Go home</a>
    </div>
  );
}

// Mount — wait until DB (data-client.js) is loaded. Babel-standalone
// evaluates <script type="text/babel"> asynchronously, so it can beat
// non-babel scripts to execution.
function mountApp() {
  if (typeof window.DB === "undefined") {
    return setTimeout(mountApp, 30);
  }
  const root = ReactDOM.createRoot(document.getElementById("root"));
  root.render(<App />);
}
mountApp();
