// NEKO — Site core: constants, theme, shared tweaks, toast, navbar, footer
// Loads after React/Babel + tweaks-panel.jsx. Exports to window.

// One-time localStorage migration for the Troya → Neko rename. Any value still
// stored under an old `troya-*` key is copied to its new `neko-*` key (without
// clobbering newer data) and the stale key is removed. Idempotent — no-ops once
// migrated, so it is safe to run on every load. Keeps saved cart/tweaks/theme/
// joined-events intact across the rename; Midnight-only behaviour is unaffected
// because the theme value is still normalised below.
(function nekoMigrateStorage() {
  try {
    var map = {
      "troya-theme": "neko-theme",
      "troya-tweaks": "neko-tweaks",
      "troya-cart-v1": "neko-cart-v1",
      "troya-ev-joined": "neko-ev-joined",
    };
    for (var oldKey in map) {
      var oldVal = localStorage.getItem(oldKey);
      if (oldVal === null) continue;
      if (localStorage.getItem(map[oldKey]) === null) localStorage.setItem(map[oldKey], oldVal);
      localStorage.removeItem(oldKey);
    }
  } catch (e) {}
})();

const NEKO = {
  ip: "mc.nekocraft.net",
  version: "1.13 – 26.1.2",
  discord: "discord.gg/Nm4uYfpaPn",
  online: 184,
};

// ---------------------------------------------------------------
// Theme — Midnight is the ONLY active site theme for now. The slider sun/moon
// toggle is retired from public chrome; Sunlight lives only in the design
// system as a passive/future reference. Lock forces Midnight and ignores any
// previously-saved "sunlight" preference, so a refresh never resurfaces it.
// ---------------------------------------------------------------
const NEKO_THEME_LOCK = "midnight"; // null = switchable; "midnight" = locked

function useNekoTheme() {
  const [theme, setThemeRaw] = React.useState(() => {
    if (NEKO_THEME_LOCK) return NEKO_THEME_LOCK; // ignore any saved preference for now
    try { return localStorage.getItem("neko-theme") || "midnight"; } catch (e) { return "midnight"; }
  });
  React.useEffect(() => {
    document.body.classList.remove("theme-sunlight", "theme-midnight");
    document.body.classList.add("theme-" + theme);
    // When locked, normalise any stale stored value back to the locked theme
    // so nothing accidentally reactivates Sunlight on the next visit.
    try { localStorage.setItem("neko-theme", NEKO_THEME_LOCK || theme); } catch (e) {}
  }, [theme]);
  const setTheme = (t) => { if (NEKO_THEME_LOCK) return; setThemeRaw(t); };
  return [theme, setTheme];
}

// ---------------------------------------------------------------
// Shared design tweaks — persisted in localStorage (cross-page)
// ---------------------------------------------------------------
const NEKO_TWEAK_DEFAULTS = {
  navVariant: "B",       // A: Saray Camı, B: Kale Burcu (aktif), C: Yüzen Adalar
  cardVariant: "auto",   // auto: kategoriye göre A/B/C — A/B/C: tek tip taslak varyant
  heroVariant: "1",      // 1: Sinematik Merkez (aktif), 2: Bölünmüş Çerçeve
  headingFont: "minecraft", // minecraft | pixelify
  glassBlur: 18,         // px — liquid-glass varsayılanı (katmanlı cam hissi geri yüklendi)
  decor: "2",            // 0 yok, 1 az, 2 normal
};

// One-time migration: the active site now uses Hero 1 + Navbar B and
// category-based product cards ("auto"). Older saved tweak values are
// re-pointed once; the variants themselves remain selectable as drafts.
// v4: glassBlur'u 0'dan 18'e taşı (liquid-glass geri yüklendi); tema kilidi
// Midnight. Eski kayıtlar bir kez yeniden eşlenir; varyantlar taslak kalır.
const NEKO_TWEAKS_VERSION = 4;
function nekoReadTweaks() {
  let saved = {};
  try { saved = JSON.parse(localStorage.getItem("neko-tweaks") || "{}"); } catch (e) { saved = {}; }
  if (saved.__v !== NEKO_TWEAKS_VERSION) {
    saved = { ...saved, navVariant: "B", heroVariant: "1", cardVariant: "auto", glassBlur: 18, __v: NEKO_TWEAKS_VERSION };
    try { localStorage.setItem("neko-tweaks", JSON.stringify(saved)); } catch (e) {}
  }
  return { ...NEKO_TWEAK_DEFAULTS, ...saved };
}

function useNekoTweaks() {
  const [tw, setTwState] = React.useState(nekoReadTweaks);
  const setTw = (key, val) => {
    setTwState((p) => {
      const next = { ...p, [key]: val, __v: NEKO_TWEAKS_VERSION };
      try { localStorage.setItem("neko-tweaks", JSON.stringify(next)); } catch (e) {}
      return next;
    });
  };
  // Side effects: fonts, glass intensity, decor density
  React.useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--font-hero",
      tw.headingFont === "minecraft" ? '"MinecraftTTF", "Pixelify Sans", monospace' : '"Pixelify Sans", monospace');
    root.style.setProperty("--glass-blur", "blur(" + tw.glassBlur + "px) saturate(150%)");
    root.style.setProperty("--frost-blur", "blur(" + Math.max(6, Math.round(tw.glassBlur * 0.6)) + "px) saturate(135%)");
    document.body.classList.remove("decor-0", "decor-1", "decor-2");
    document.body.classList.add("decor-" + tw.decor);
    // Bulanıklık düşükken cam yüzeyler okunabilirliğini kenar/parlama/opaklıkla korur
    document.body.classList.toggle("glass-flat", (tw.glassBlur || 0) < 6);
  }, [tw]);
  return [tw, setTw];
}

// ---------------------------------------------------------------
// Toast
// ---------------------------------------------------------------
function nekoToast(msg) {
  window.dispatchEvent(new CustomEvent("neko:toast", { detail: msg }));
}
function ToastHost() {
  const [msg, setMsg] = React.useState(null);
  React.useEffect(() => {
    let t;
    const on = (e) => { setMsg(e.detail); clearTimeout(t); t = setTimeout(() => setMsg(null), 2200); };
    window.addEventListener("neko:toast", on);
    return () => { window.removeEventListener("neko:toast", on); clearTimeout(t); };
  }, []);
  if (!msg) return null;
  return (
    <div className="toast-host" role="status" aria-live="polite">
      <div className="toast glass-1 pill">
        <span aria-hidden="true" style={{ width: 8, height: 8, background: "#76C5FF" }}></span>
        {msg}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Clipboard helper + Copy-IP button (toast + inline feedback)
// ---------------------------------------------------------------
function nekoCopy(text) {
  try {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      return navigator.clipboard.writeText(text).then(() => true, () => false);
    }
  } catch (e) {}
  try {
    const ta = document.createElement("textarea");
    ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0";
    document.body.appendChild(ta); ta.select();
    const ok = document.execCommand("copy");
    document.body.removeChild(ta);
    return Promise.resolve(ok);
  } catch (e) { return Promise.resolve(false); }
}

function CopyIpButton({ small, ghost }) {
  const [copied, setCopied] = React.useState(false);
  const onCopy = () => {
    nekoCopy(NEKO.ip).then(() => {
      setCopied(true);
      nekoToast("Sunucu adresi kopyalandı: " + NEKO.ip);
      setTimeout(() => setCopied(false), 1900);
    });
  };
  return (
    <button
      type="button"
      className={"btn btn-copy " + (ghost ? "btn-ghost" : "btn-secondary") + (copied ? " copied" : "") + (small ? " btn-sm" : "")}
      onClick={onCopy}
      style={copied ? { color: "#F7F9FD" } : null}
    >
      {copied ? "Kopyalandı ✓" : <span>IP'yi Kopyala <span className="ip">· {NEKO.ip}</span></span>}
    </button>
  );
}

// ---------------------------------------------------------------
// Theme toggle (CANONICAL sliding pixel sun/moon) — recovered from the
// design system. Slides between Sunlight (sun, left) and Midnight (moon,
// right); the knob carries the active celestial body. Persists via
// useNekoTheme. The old 2-square segment version is archived in the DS.
// ---------------------------------------------------------------
function ThemeToggle({ theme, setTheme, small }) {
  const next = theme === "midnight" ? "sunlight" : "midnight";
  return (
    <button
      type="button"
      className={"neko-sw" + (small ? " neko-sw-small" : "")}
      data-theme={theme}
      role="switch"
      aria-checked={theme === "midnight"}
      aria-label={"Tema değiştir — şu an " + (theme === "midnight" ? "Midnight" : "Sunlight")}
      title={"Tema: " + (theme === "midnight" ? "Midnight" : "Sunlight")}
      onClick={() => setTheme(next)}
    >
      <span className="neko-sw-track" aria-hidden="true">
        <span className="neko-sw-star a"></span>
        <span className="neko-sw-star b"></span>
        <span className="neko-sw-star c"></span>
        <span className="neko-sw-ghost neko-sw-ghost-l"></span>
        <span className="neko-sw-ghost neko-sw-ghost-r"></span>
      </span>
      <span className="neko-sw-knob" aria-hidden="true">
        <span className="neko-sw-sun"></span>
        <span className="neko-sw-moon"></span>
      </span>
    </button>
  );
}

// ---------------------------------------------------------------
// Navbar — variants A/B/C, active page, mobile menu, optional cart
// ---------------------------------------------------------------
const NEKO_NAV = [
  { id: "home", label: "Anasayfa", href: "Anasayfa.html" },
  { id: "store", label: "Mağaza", href: "Magaza.html" },
  { id: "pazar", label: "Pazar", href: "Pazar.html" },
  { id: "duyurular", label: "Duyurular", href: "Duyurular.html" }, // sayfa başlığı: "Duyurular & Güncellemeler"
  { id: "credits", label: "Krediler", href: "Krediler.html" },
  { id: "support", label: "Destek", href: "Destek.html" },
];

function NavLinksRow({ active }) {
  return (
    <nav className="nav-links" aria-label="Ana navigasyon">
      {NEKO_NAV.map((n) => (
        <a key={n.id} href={n.href} aria-current={n.id === active ? "page" : undefined}>{n.label}</a>
      ))}
    </nav>
  );
}

function NavActions({ theme, setTheme, cartCount, onCartOpen, active }) {
  return (
    <div className="nav-actions">
      {/* Online player counter removed from navbar (kept elsewhere on site) */}
      {/* Tema anahtarı kaldırıldı — site şimdilik yalnız Midnight; Sunlight tasarım sisteminde pasif/gelecek referans olarak duruyor */}
      {/* Prototip aşamasında herkese görünür — sayfa başlığı: "Admin Yönetim Paneli" */}
      <a href="Admin Paneli.html" className="btn btn-ghost btn-sm nav-admin-link" aria-current={active === "admin" ? "page" : undefined}>Admin</a>
      {onCartOpen && (
        <button type="button" className="btn btn-ghost btn-sm" onClick={onCartOpen} aria-label={"Sepeti aç, " + cartCount + " ürün"}>
          Sepet{cartCount > 0 ? " · " + cartCount : ""}
        </button>
      )}
      <a href="Giris Yap.html" className="btn btn-primary btn-sm" aria-current={active === "login" ? "page" : undefined}>Giriş Yap</a>
    </div>
  );
}

function SiteNavbar({ active, theme, setTheme, variant, cartCount, onCartOpen }) {
  const [open, setOpen] = React.useState(false);
  const v = variant || "A";
  const actions = <NavActions theme={theme} setTheme={setTheme} cartCount={cartCount} onCartOpen={onCartOpen} active={active} />;
  const burger = (
    <button type="button" className="nav-burger" aria-expanded={open} aria-label="Menüyü aç/kapat" onClick={() => setOpen(!open)}>
      <span className="bar"></span>
    </button>
  );
  const mobileMenu = (
    <div className={"nav-mobile glass-1" + (open ? " open" : "")}>
      {NEKO_NAV.map((n) => (
        <a key={n.id} href={n.href} aria-current={n.id === active ? "page" : undefined}>{n.label}</a>
      ))}
      <a href="Admin Paneli.html" aria-current={active === "admin" ? "page" : undefined}>Admin Paneli</a>
      <a href="Giris Yap.html" aria-current={active === "login" ? "page" : undefined}>Giriş Yap</a>
    </div>
  );

  if (v === "B") {
    return (
      <div className="site-nav-wrap">
        <div className="px-shadow-sm">
          <div className="frost-2 site-nav-b">
            <div className="block-3" style={{ padding: "9px 16px 11px", "--px-step": "5px" }}>
              <a className="nav-wordmark" href="Anasayfa.html">NEKO</a>
            </div>
            <NavLinksRow active={active} />
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>{actions}{burger}</div>
          </div>
        </div>
        {mobileMenu}
      </div>
    );
  }
  if (v === "C") {
    return (
      <div className="site-nav-wrap">
        <div className="site-nav-c">
          <div className="glass-1 pill" style={{ padding: "11px 22px" }}>
            <a className="nav-wordmark" href="Anasayfa.html">NEKO</a>
          </div>
          <div className="glass-1 pill" style={{ padding: "11px 30px" }}>
            <NavLinksRow active={active} />
          </div>
          <div className="glass-1 pill" style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 10px" }}>
            {actions}{burger}
          </div>
        </div>
        {mobileMenu}
      </div>
    );
  }
  // Variant A — Saray Camı (default)
  return (
    <div className="site-nav-wrap">
      <div className="glass-1 pill site-nav-a">
        {theme === "midnight"
          ? <span className="px-spark deco" aria-hidden="true" style={{ position: "absolute", right: "30%", top: 12 }}></span>
          : <span className="px-vine deco" aria-hidden="true" style={{ position: "absolute", left: 26, top: -4 }}></span>}
        <a className="nav-wordmark" href="Anasayfa.html">NEKO</a>
        <NavLinksRow active={active} />
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>{actions}{burger}</div>
      </div>
      {mobileMenu}
    </div>
  );
}

// ---------------------------------------------------------------
// Section helpers
// ---------------------------------------------------------------
function SectionHead({ title, sub, cta }) {
  return (
    <div className="section-head">
      <div>
        <h2 className="section-title">{title}</h2>
        {sub ? <p className="section-sub">{sub}</p> : null}
      </div>
      {cta ? <div className="section-cta">{cta}</div> : null}
    </div>
  );
}

function PixelDivider() {
  return (
    <div className="px-divider deco" aria-hidden="true">
      <span></span><span></span><span className="mid"></span><span></span><span></span>
    </div>
  );
}

// ---------------------------------------------------------------
// Status strip (hero)
// ---------------------------------------------------------------
function StatusStrip() {
  const cell = { display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-body)", fontSize: 13, whiteSpace: "nowrap" };
  const div = <span aria-hidden="true" style={{ width: 1, alignSelf: "stretch", background: "var(--glass-border)" }}></span>;
  return (
    <div className="glass-1 pill" style={{ display: "inline-flex", gap: 18, alignItems: "center", padding: "13px 26px" }}>
      <span style={cell}><span className="status-dot"></span><strong>{NEKO.online}</strong>&nbsp;oyuncu çevrimiçi</span>
      {div}
      <span style={cell}>{NEKO.ip}</span>
      {div}
      <span style={cell}>Sürüm {NEKO.version}</span>
      {div}
      <a href="#" onClick={(e) => e.preventDefault()} style={{ ...cell, color: "var(--c-accent)", fontWeight: 700, textDecoration: "none" }}>Discord'a Katıl →</a>
    </div>
  );
}

// ---------------------------------------------------------------
// Footer
// ---------------------------------------------------------------
function SiteFooter() {
  return (
    <footer className="site-footer band">
      <div className="footer-inner">
        <div className="footer-cols">
          <div className="footer-col">
            <a className="nav-wordmark" href="Anasayfa.html" style={{ fontSize: 26 }}>NEKO</a>
            <p style={{ fontSize: 13, lineHeight: 1.7, color: "var(--c-text-2)", maxWidth: "34ch", marginTop: 12 }}>
              Keşif, görev ve topluluk odaklı Minecraft sunucusu.
            </p>
            <span style={{ fontSize: 12.5, color: "var(--c-text-2)" }}>{NEKO.ip} · {NEKO.version}</span>
          </div>
          <div className="footer-col">
            <h3>Site</h3>
            {NEKO_NAV.filter((n) => n.id !== "pazar" && n.id !== "duyurular").map((n) => <a key={n.id} href={n.href}>{n.label}</a>)}
            <a href="Pazar.html">Pazar</a>
            <a href="Duyurular.html">Duyurular &amp; Güncellemeler</a>
            <a href="Etkinlikler.html">Etkinlikler</a>
            <a href="Giris Yap.html">Giriş Yap</a>
          </div>
          <div className="footer-col">
            <h3>Topluluk</h3>
            <a href="#" onClick={(e) => e.preventDefault()}>Discord — {NEKO.discord}</a>
            <a href="#" onClick={(e) => e.preventDefault()}>YouTube — Neko Sineması</a>
            <a href="#" onClick={(e) => e.preventDefault()}>X — @nekocraft</a>
            <a href="#" onClick={(e) => e.preventDefault()}>Instagram — @nekocraft</a>
          </div>
          <div className="footer-col">
            <h3>Yardım</h3>
            <a href="Destek.html">Destek Al</a>
            <a href="Destek.html">Kurallar &amp; İtiraz</a>
            <a href="Krediler.html">Kredi Yükle</a>
          </div>
        </div>
        <div className="footer-legal">
          <span>© 2026 Neko. Tüm hakları saklıdır.</span>
          <span style={{ maxWidth: "62ch" }}>
            Neko; Mojang Studios, Microsoft veya resmi Minecraft hizmetleriyle bağlantılı değildir ve onlar tarafından desteklenmemektedir.
          </span>
        </div>
      </div>
    </footer>
  );
}

// ---------------------------------------------------------------
// Tweaks panel (prototype-only)
// ---------------------------------------------------------------
function NekoTweaks({ theme, setTheme, tw, setTw, page }) {
  return (
    <TweaksPanel>
      {/* Tema seçimi kaldırıldı — site Midnight-only; Sunlight yalnız tasarım sisteminde pasif referans */}
      <TweakSection label="Tipografi" />
      <TweakRadio label="Başlık fontu" value={tw.headingFont} options={["minecraft", "pixelify"]} onChange={(v) => setTw("headingFont", v)} />
      <TweakSection label="Cam & Dekor" />
      <TweakSlider label="Cam bulanıklığı" value={tw.glassBlur} min={0} max={32} unit="px" onChange={(v) => setTw("glassBlur", v)} />
      <TweakRadio label="Dekor yoğunluğu" value={tw.decor} options={["0", "1", "2"]} onChange={(v) => setTw("decor", v)} />
      <TweakSection label="Varyantlar" />
      <TweakRadio label="Navbar" value={tw.navVariant} options={["A", "B", "C"]} onChange={(v) => setTw("navVariant", v)} />
      {page === "home" && <TweakRadio label="Hero" value={tw.heroVariant} options={["1", "2"]} onChange={(v) => setTw("heroVariant", v)} />}
      {(page === "home" || page === "store") && <TweakRadio label="Ürün kartı" value={tw.cardVariant} options={["auto", "A", "B", "C", "D"]} onChange={(v) => setTw("cardVariant", v)} />}
    </TweaksPanel>
  );
}

Object.assign(window, {
  NEKO, NEKO_NAV, useNekoTheme, useNekoTweaks, nekoToast, nekoCopy,
  ToastHost, CopyIpButton, ThemeToggle, SiteNavbar, SectionHead, PixelDivider,
  StatusStrip, SiteFooter, NekoTweaks,
});
