/* ============================================================
   Multi-page shell: navigation, auth (localStorage), chrome
   ============================================================ */

/* URL şeması sunucudan (SslRoutes) gelir: dil-bazlı, çevrilmiş slug'lar.
   window.sslRoutes mevcut dilin yollarını taşır; yoksa tr varsayılanlarına düşülür. */
const R = (typeof window !== "undefined" && window.sslRoutes) || {};
const CATWORD = R.catWord || "kategori";
const CATSLUGS = (typeof window !== "undefined" && window.__BOOT__ && window.__BOOT__.catSlugs) || {};  // kanonik → o dildeki kategori slug'ı
const LANG_PREFIX = R.prefix || "";
const PAGES = {
  home: R.home || "/",
  wizard: R.wizard || "/sertifika-al",
  login: R.login || "/giris",
  register: R.register || "/kayit",
  dashboard: R.dashboard || "/panel",
  privacy: R.privacy || "/gizlilik",
  terms: R.terms || "/kosullar",
  blog: R.blog || "/blog",
  admin: R.admin || "/admin",
  reports: R.reports || "/raporlar",
  adminBlog: R.adminBlog || "/admin-blog",
  blogEditor: R.blogEditor || "/makale-duzenle",
  adminSettings: R.adminSettings || "/ayarlar",
  emailTpl: R.emailTpl || "/email-templates",
  users: R.users || "/users",
  notFound: R.notFound || "/404",
};
/* Blog öğe linkleri — path-tabanlı, dil-bazlı (?slug= YOK). */
function articleUrl(slug) { return PAGES.blog + "/" + encodeURIComponent(slug); }
/* Kategori: ayrı SEO sayfası, o dildeki localized slug → /blog/{localized}. slug = kanonik (tr) slug. */
function categoryUrl(slug) { return PAGES.blog + "/" + encodeURIComponent(CATSLUGS[slug] || slug); }
/* Geriye dönük: bazı bileşenler PAGES.article'ı taban olarak kullanıyordu. */
PAGES.article = PAGES.blog;
PAGES.blogCategory = PAGES.blog;

function goView(v) { if (PAGES[v]) window.location.href = PAGES[v]; }

/* Dil değiştirme: aynı sayfanın hedef dildeki URL'ine git (URL = dilin tek kaynağı). */
function switchLang(code) {
  try { localStorage.setItem("ssl_lang", code); } catch (e) {}
  const urls = (typeof window !== "undefined" && window.sslLangUrls) || {};
  window.location.href = urls[code] || PAGES.home;
}
function getUser() { try { return JSON.parse(localStorage.getItem("ssl_user") || "null"); } catch (e) { return null; } }
function setUser(u) { localStorage.setItem("ssl_user", JSON.stringify(u)); }
function logout() { try { localStorage.removeItem("ssl_user"); } catch (e) {} window.location.href = "/cikis"; }
function onAuth(u) { setUser({ email: (u && u.email) || "kerim@acmeyazilim.com", admin: true }); goView("dashboard"); }

const ADMIN_PAGES = ["admin", "reports", "adminBlog", "blogEditor", "adminSettings"];

/* Compact language switcher — only when i18n is on and >1 language */
function LangSwitcher({ compact }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  if (!i18nEnabled()) return null;
  const langs = getLangs();
  if (langs.length < 2) return null;
  const cur = langs.find(l => l.code === getLang()) || langs[0];
  return (
    <div className="lang-switch" ref={ref}>
      <button className="lang-btn" onClick={() => setOpen(o => !o)} aria-label="Dil" title="Dil / Language">
        <span style={{ fontSize: 15 }}>{cur.flag}</span>
        <span style={{ textTransform: "uppercase", fontWeight: 700, fontSize: 12.5 }}>{cur.code}</span>
        <span className="sel-chev" style={{ transform: open ? "rotate(180deg)" : "none", display: "inline-flex" }}>{Ic.chevron({ s: 14 })}</span>
      </button>
      {open && (
        <div className="lang-pop">
          {langs.map(l => (
            <button key={l.code} className={`lang-opt ${l.code === cur.code ? "on" : ""}`} onClick={() => { setOpen(false); if (l.code !== cur.code) switchLang(l.code); }}>
              <span style={{ fontSize: 15 }}>{l.flag}</span>
              <span style={{ flex: 1, textAlign: "left" }}>{l.name}</span>
              {l.code === cur.code && <span style={{ color: "var(--primary)", display: "inline-flex" }}>{Ic.check({ s: 14 })}</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function Nav({ page }) {
  const [open, setOpen] = useState(false);
  const user = getUser();
  const links = [["home", t("nav.home")], ["wizard", t("nav.wizard")], ["blog", t("nav.blog")]];
  if (user) links.push(["dashboard", t("nav.dashboard")]);
  const active = (k) => page === k || (k === "blog" && page === "article");

  return (
    <header className="nav">
      <div className="wrap nav-inner">
        <Brand onClick={() => goView("home")} />
        <nav className="nav-links">
          {links.map(([k, l]) => <a key={k} className={`nav-link ${active(k) ? "active" : ""}`} href={PAGES[k]}>{l}</a>)}
        </nav>
        <div className="nav-right">
          <LangSwitcher />
          {user ? (
            <>
              <a href={PAGES.dashboard} className="desktop-only" style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, color: "var(--text-2)", fontWeight: 500 }}>
                <span style={{ width: 30, height: 30, borderRadius: "50%", background: "var(--primary-soft)", color: "var(--primary)", display: "grid", placeItems: "center" }}>{Ic.user({ s: 16 })}</span>
                {user.email}
              </a>
              <button className="nav-link desktop-only" onClick={logout} title="Çıkış">{Ic.logout({ s: 18 })}</button>
            </>
          ) : (
            <>
              <a className="nav-link desktop-only" href={PAGES.login}>{t("nav.login")}</a>
              <a className="btn btn-primary btn-sm" href={PAGES.register}>{t("nav.register")}</a>
            </>
          )}
          <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label="Menü">
            {open ? Ic.close({ s: 20 }) : (<svg width="20" height="20" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>)}
          </button>
        </div>
      </div>
      {open && (
        <div className="wrap" style={{ paddingBottom: 16, display: "flex", flexDirection: "column", gap: 4, borderTop: "1px solid var(--border)" }}>
          {links.map(([k, l]) => <a key={k} className={`nav-link ${active(k) ? "active" : ""}`} style={{ padding: "12px 13px" }} href={PAGES[k]}>{l}</a>)}
          <hr className="divider" style={{ margin: "6px 0" }} />
          {user
            ? <a className="nav-link" style={{ padding: "12px 13px" }} onClick={logout}>{t("nav.logout")} ({user.email})</a>
            : <>
                <a className="nav-link" style={{ padding: "12px 13px" }} href={PAGES.login}>{t("nav.login")}</a>
                <a className="btn btn-primary" href={PAGES.register}>{t("nav.register")}</a>
              </>}
        </div>
      )}
    </header>
  );
}

function Footer() {
  return (
    <footer style={{ borderTop: "1px solid var(--border)", background: "var(--surface)", marginTop: "auto" }}>
      <div className="wrap" style={{ padding: "32px 24px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
        <Brand onClick={() => goView("home")} />
        <div style={{ display: "flex", gap: 22, fontSize: 13.5, flexWrap: "wrap" }}>
          <a className="mut" href={PAGES.wizard}>{t("footer.certificate")}</a>
          <a className="mut" href={PAGES.blog}>{t("footer.blog")}</a>
          <a className="mut" href={PAGES.privacy}>{t("footer.privacy")}</a>
          <a className="mut" href={PAGES.terms}>{t("footer.terms")}</a>
          <a className="mut" href={PAGES.dashboard}>{t("footer.dashboard")}</a>
        </div>
        <span className="hint">{t("footer.copy")}</span>
      </div>
    </footer>
  );
}

function ProtoBar({ page }) {
  const items = [["home", "Anasayfa"], ["wizard", "Akış"], ["blog", "Blog"], ["dashboard", "Müşteri Paneli"], ["admin", "Admin"], ["reports", "Raporlar"], ["adminBlog", "Blog Yön."], ["adminSettings", "Ayarlar"], ["login", "Giriş"]];
  return (
    <div className="proto-bar">
      <span className="pb-lbl">Demo</span>
      {items.map(([k, l]) => <a key={k} className={page === k ? "active" : ""} href={PAGES[k]}>{l}</a>)}
    </div>
  );
}

function AdminTabs({ active }) {
  const tabs = [["admin", t("admintabs.apps"), Ic.globe], ["reports", t("admintabs.reports"), Ic.layers], ["adminBlog", t("admintabs.blog"), Ic.file], ["emailTpl", t("settings.navEmail"), Ic.mail], ["users", "Kullanıcılar", Ic.user], ["adminSettings", t("admintabs.settings"), Ic.lock]];
  return (
    <div className="tabs">
      {tabs.map(([k, l, I]) => <a key={k} className={`tab ${active === k ? "active" : ""}`} href={PAGES[k]}>{I({ s: 16 })}{l}</a>)}
    </div>
  );
}

function Shell({ page, children }) {
  return (
    <div className="app-shell">
      <Nav page={page} />
      <main style={{ flex: 1 }}>{children}</main>
      <Footer />
      {(typeof window !== "undefined" && window.__BOOT__ && window.__BOOT__.demo) && <ProtoBar page={page} />}
    </div>
  );
}

Object.assign(window, { PAGES, goView, articleUrl, categoryUrl, switchLang, CATWORD, LANG_PREFIX, getUser, setUser, logout, onAuth, ADMIN_PAGES, Nav, Footer, ProtoBar, AdminTabs, Shell, LangSwitcher });
