/* ============================================================
   i18n engine + dictionary
   - Languages, current language, and per-language string
     overrides are persisted in localStorage so the admin can
     manage everything from the Settings page.
   - t(key) is exposed globally (window.t) so every Babel
     script can call it like Ic / Btn.
   ============================================================ */

/* ---- Built-in dictionary (seed). TR is the source of truth. ---- */
const DICT = {
  tr: {
    /* common */
    "common.free": "Ücretsiz", "common.days90": "90 gün", "common.back": "Geri", "common.next": "Devam",
    "common.save": "Kaydet", "common.cancel": "İptal", "common.delete": "Sil", "common.edit": "Düzenle",
    "common.download": "İndir", "common.optional": "opsiyonel", "common.search": "Ara…", "common.close": "Kapat",
    /* nav */
    "nav.home": "Anasayfa", "nav.wizard": "Sertifika Al", "nav.blog": "Blog", "nav.dashboard": "Panelim",
    "nav.login": "Giriş Yap", "nav.register": "Ücretsiz Üye Ol", "nav.logout": "Çıkış",
    /* footer */
    "footer.certificate": "Sertifika Al", "footer.blog": "Blog", "footer.privacy": "Gizlilik", "footer.terms": "Hizmet Şartları",
    "footer.dashboard": "Panelim", "footer.copy": "© 2026 90 Day Free SSL · Let's Encrypt ile güçlendirilmiştir",
    /* admin tabs */
    "admintabs.apps": "Başvurular", "admintabs.reports": "Raporlar", "admintabs.blog": "Blog", "admintabs.settings": "Ayarlar",
    /* landing */
    "landing.eyebrow": "%100 ücretsiz · kredi kartı yok",
    "landing.heroTitleHtml": "Sitenizi <span class='hl'>dakikalar içinde</span> güvene alın.",
    "landing.heroText": "Let's Encrypt altyapısıyla 90 günlük ücretsiz SSL sertifikası oluşturun. DNS veya HTTP ile doğrulayın, tüm dosyaları (CRT, KEY, PFX) tek ZIP'te indirin.",
    "landing.cta1": "Ücretsiz Sertifika Al", "landing.cta2": "Panelimi Gör",
    "landing.check1": "Tüm tarayıcılarda geçerli", "landing.check2": "Sınırsız ücretsiz yenileme", "landing.check3": "Wildcard & www desteği",
    "landing.howEyebrow": "Nasıl çalışır", "landing.howTitle": "Üç adımda hazır",
    "landing.step1t": "Bilgileri girin", "landing.step1b": "Alan adınızı ve e-postanızı girin. www ve sahip bilgileri opsiyonel.",
    "landing.step2t": "DNS veya HTTP ile doğrulayın", "landing.step2b": "Verilen kayıtları ekleyin ya da dosyayı yükleyin, tek tıkla doğrulayın.",
    "landing.step3t": "ZIP'i indirin", "landing.step3b": "CRT, KEY, CA, fullchain ve şifreli PFX dosyalarını tek pakette alın.",
    "landing.start": "Hemen Başla",
    "landing.cardTitle": "TLS / SSL Sertifikası", "landing.cardDomain": "Alan adı", "landing.cardStatus": "Durum",
    "landing.cardActive": "Aktif", "landing.cardValidity": "Geçerlilik", "landing.cardLeft": "78 gün kaldı",
    "landing.cardRemindT": "Hatırlatma planlandı", "landing.cardRemindS": "7 gün kala e-posta",
    /* auth */
    "auth.loginTitle": "Tekrar hoş geldiniz", "auth.loginSub": "Sertifikalarınızı yönetmek için giriş yapın.",
    "auth.regTitle": "Ücretsiz hesap oluşturun", "auth.regSub": "Tüm sertifikalarınızı tek panelden izleyin.",
    "auth.email": "E-posta", "auth.password": "Şifre", "auth.login": "Giriş Yap", "auth.register": "Hesap Oluştur",
    "auth.forgot": "Şifremi unuttum",
    "auth.noAccount": "Hesabınız yok mu? ", "auth.haveAccount": "Zaten hesabınız var mı? ",
    "auth.doRegister": "Ücretsiz kaydolun", "auth.doLogin": "Giriş yapın",
    "auth.guest1": "Üye olmadan da ", "auth.guest2": "sertifika oluşturabilirsiniz",
    "auth.fpTitle": "Şifrenizi mi unuttunuz?", "auth.fpSub": "Hesap e-postanızı girin; size bir şifre sıfırlama bağlantısı gönderelim.",
    "auth.fpSend": "Sıfırlama bağlantısı gönder", "auth.fpBack": "Girişe dön",
    "auth.sentTitle": "Bağlantı gönderildi", "auth.sentBody": "ile kayıtlı bir hesap varsa, şifre sıfırlama bağlantısını gönderdik. Gelen kutunuzu (ve spam klasörünü) kontrol edin.",
    "auth.sentNote": "Bağlantı 30 dakika geçerlidir. E-posta gelmediyse birkaç dakika sonra tekrar deneyin.",
    "auth.resend": "Tekrar gönder",
    /* wizard */
    "wiz.step1": "Bilgiler", "wiz.step2": "Doğrulama", "wiz.step3": "İndir",
    "wiz.eyebrow": "Ücretsiz · 90 gün · Let's Encrypt", "wiz.title": "Ücretsiz SSL Sertifikanızı Oluşturun",
    "wiz.domain": "Alan adı", "wiz.domainHint": "Başında www. veya https:// olmadan girin.",
    "wiz.wwwInc": "www alt alanını da dahil et", "wiz.email": "E-posta adresi",
    "wiz.emailHint": "Sertifika ve yenileme hatırlatmaları bu adrese gönderilir.",
    "wiz.remindTitle": "Süre dolmadan hatırlat", "wiz.remindSub": "30, 7 ve 1 gün kala e-posta ile bilgilendirelim.",
    "wiz.toVerify": "Doğrulamaya Geç",
    "wiz.chooseMethod": "Doğrulama yöntemini seçin",
    "wiz.chooseMethodSub": "Alan adının size ait olduğunu kanıtlamak için bir yöntem kullanın. İkisi de ücretsizdir; istediğinizi seçebilirsiniz.",
    "wiz.dnsName": "DNS ile doğrula", "wiz.dnsTag": "Önerilen",
    "wiz.dnsDesc": "DNS panelinize TXT kaydı ekleyin. Sunucuya erişim gerektirmez, wildcard destekler.",
    "wiz.httpName": "HTTP (dosya) ile doğrula",
    "wiz.httpDesc": "Sunucunuza bir dosya yükleyin. DNS erişiminiz yoksa idealdir.",
    "wiz.verifyDo": "Doğrulamayı Tamamla", "wiz.verifying": "Doğrulanıyor…", "wiz.toDownload": "Sertifikayı İndir",
    "wiz.readyTitle": "Sertifikanız hazır 🎉",
    /* dashboard */
    "dash.title": "Sertifikalarım", "dash.new": "Yeni Sertifika",
    "dash.total": "Toplam sertifika", "dash.active": "Aktif", "dash.expiring": "Yakında dolacak", "dash.expired": "Süresi dolan",
    /* admin */
    "admin.title": "Başvuru Yönetimi", "admin.total": "Toplam başvuru", "admin.today": "Bugün gelen",
    "admin.pending": "Doğrulama bekleyen", "admin.expiring": "Yakında dolacak",
    /* reports */
    "reports.title": "Raporlar", "reports.csv": "CSV indir", "reports.range": "Tarih aralığı",
    "reports.sent": "Gönderilen e-posta", "reports.openRate": "Açılma oranı",
    /* blog admin */
    "blogadmin.title": "Blog Yönetimi", "blogadmin.sub": "SEO odaklı içeriklerinizi oluşturun ve yönetin",
    "blogadmin.new": "Yeni Yazı", "blogadmin.cats": "Blog kategorileri",
    /* settings */
    "settings.title": "Site Ayarları", "settings.sub": "Sitenin genelini, sertifika akışını ve dilleri buradan yönetin",
    "nf.title": "Sayfa bulunamadı", "nf.code": "404",
    "nf.sub": "Aradığınız sayfa taşınmış, silinmiş ya da hiç var olmamış olabilir.",
    "nf.home": "Anasayfaya dön", "nf.wizard": "Ücretsiz sertifika al", "nf.blog": "Bloga göz at",
  },
  en: {
    "common.free": "Free", "common.days90": "90 days", "common.back": "Back", "common.next": "Continue",
    "common.save": "Save", "common.cancel": "Cancel", "common.delete": "Delete", "common.edit": "Edit",
    "common.download": "Download", "common.optional": "optional", "common.search": "Search…", "common.close": "Close",
    "nav.home": "Home", "nav.wizard": "Get Certificate", "nav.blog": "Blog", "nav.dashboard": "Dashboard",
    "nav.login": "Sign in", "nav.register": "Sign up free", "nav.logout": "Sign out",
    "footer.certificate": "Get Certificate", "footer.blog": "Blog", "footer.privacy": "Privacy", "footer.terms": "Terms",
    "footer.dashboard": "Dashboard", "footer.copy": "© 2026 90 Day Free SSL · Powered by Let's Encrypt",
    "admintabs.apps": "Applications", "admintabs.reports": "Reports", "admintabs.blog": "Blog", "admintabs.settings": "Settings",
    "landing.eyebrow": "100% free · no credit card",
    "landing.heroTitleHtml": "Secure your site <span class='hl'>in minutes</span>.",
    "landing.heroText": "Create a free 90-day SSL certificate powered by Let's Encrypt. Verify via DNS or HTTP and download every file (CRT, KEY, PFX) in a single ZIP.",
    "landing.cta1": "Get a free certificate", "landing.cta2": "View my dashboard",
    "landing.check1": "Valid in all browsers", "landing.check2": "Unlimited free renewals", "landing.check3": "Wildcard & www support",
    "landing.howEyebrow": "How it works", "landing.howTitle": "Ready in three steps",
    "landing.step1t": "Enter details", "landing.step1b": "Enter your domain and email. www and owner details are optional.",
    "landing.step2t": "Verify via DNS or HTTP", "landing.step2b": "Add the records or upload the file, then verify in one click.",
    "landing.step3t": "Download the ZIP", "landing.step3b": "Get CRT, KEY, CA, fullchain and the encrypted PFX in one bundle.",
    "landing.start": "Get Started",
    "landing.cardTitle": "TLS / SSL Certificate", "landing.cardDomain": "Domain", "landing.cardStatus": "Status",
    "landing.cardActive": "Active", "landing.cardValidity": "Validity", "landing.cardLeft": "78 days left",
    "landing.cardRemindT": "Reminder scheduled", "landing.cardRemindS": "Email 7 days before",
    "auth.loginTitle": "Welcome back", "auth.loginSub": "Sign in to manage your certificates.",
    "auth.regTitle": "Create a free account", "auth.regSub": "Track all your certificates from one dashboard.",
    "auth.email": "Email", "auth.password": "Password", "auth.login": "Sign in", "auth.register": "Create account",
    "auth.forgot": "Forgot password",
    "auth.noAccount": "Don't have an account? ", "auth.haveAccount": "Already have an account? ",
    "auth.doRegister": "Sign up free", "auth.doLogin": "Sign in",
    "auth.guest1": "You can also ", "auth.guest2": "create a certificate without signing up",
    "auth.fpTitle": "Forgot your password?", "auth.fpSub": "Enter your account email and we'll send you a password reset link.",
    "auth.fpSend": "Send reset link", "auth.fpBack": "Back to sign in",
    "auth.sentTitle": "Link sent", "auth.sentBody": "if an account exists, we've sent a password reset link. Check your inbox (and spam folder).",
    "auth.sentNote": "The link is valid for 30 minutes. If no email arrives, try again in a few minutes.",
    "auth.resend": "Resend",
    "wiz.step1": "Details", "wiz.step2": "Verify", "wiz.step3": "Download",
    "wiz.eyebrow": "Free · 90 days · Let's Encrypt", "wiz.title": "Create your free SSL certificate",
    "wiz.domain": "Domain", "wiz.domainHint": "Enter it without www. or https:// in front.",
    "wiz.wwwInc": "Include the www subdomain too", "wiz.email": "Email address",
    "wiz.emailHint": "Certificate and renewal reminders are sent to this address.",
    "wiz.remindTitle": "Remind me before expiry", "wiz.remindSub": "We'll email you 30, 7 and 1 day before.",
    "wiz.toVerify": "Continue to verification",
    "wiz.chooseMethod": "Choose a verification method",
    "wiz.chooseMethodSub": "Use one method to prove the domain is yours. Both are free; pick whichever you prefer.",
    "wiz.dnsName": "Verify via DNS", "wiz.dnsTag": "Recommended",
    "wiz.dnsDesc": "Add a TXT record to your DNS panel. No server access needed, supports wildcards.",
    "wiz.httpName": "Verify via HTTP (file)",
    "wiz.httpDesc": "Upload a file to your server. Ideal if you don't have DNS access.",
    "wiz.verifyDo": "Complete verification", "wiz.verifying": "Verifying…", "wiz.toDownload": "Download certificate",
    "wiz.readyTitle": "Your certificate is ready 🎉",
    "dash.title": "My certificates", "dash.new": "New certificate",
    "dash.total": "Total certificates", "dash.active": "Active", "dash.expiring": "Expiring soon", "dash.expired": "Expired",
    "admin.title": "Application Management", "admin.total": "Total applications", "admin.today": "Received today",
    "admin.pending": "Awaiting verification", "admin.expiring": "Expiring soon",
    "reports.title": "Reports", "reports.csv": "Export CSV", "reports.range": "Date range",
    "reports.sent": "Emails sent", "reports.openRate": "Open rate",
    "blogadmin.title": "Blog Management", "blogadmin.sub": "Create and manage SEO-focused content",
    "blogadmin.new": "New Post", "blogadmin.cats": "Blog categories",
    "settings.title": "Site Settings", "settings.sub": "Manage the site, certificate flow and languages from here",
    "nf.title": "Page not found", "nf.code": "404",
    "nf.sub": "The page you're looking for may have moved, been deleted, or never existed.",
    "nf.home": "Back to home", "nf.wizard": "Get a free certificate", "nf.blog": "Browse the blog",
  },
};

const DEFAULT_LANGS = [
  { code: "tr", name: "Türkçe", flag: "🇹🇷", def: true },
  { code: "en", name: "English", flag: "🇬🇧", def: false },
];

/* ---- persistence ---- */
function i18nEnabled() { try { const v = localStorage.getItem("ssl_i18n_enabled"); return v === null ? true : v === "true"; } catch (e) { return true; } }
function setI18nEnabled(b) {
  try { localStorage.setItem("ssl_i18n_enabled", b ? "true" : "false"); } catch (e) {}
  if (window.sslApi) window.sslApi.put("admin/i18n", { enabled: b });
}
function getLangs() {
  try { const s = JSON.parse(localStorage.getItem("ssl_i18n_langs") || "null"); return Array.isArray(s) && s.length ? s : DEFAULT_LANGS.slice(); }
  catch (e) { return DEFAULT_LANGS.slice(); }
}
function setLangs(arr) {
  try { localStorage.setItem("ssl_i18n_langs", JSON.stringify(arr)); } catch (e) {}
  if (window.sslApi) window.sslApi.put("admin/i18n/languages",
    (arr || []).map(function (l, i) { return { code: l.code, name: l.name, flag: l.flag, default: !!l.def, enabled: true, sort: i }; }));
}
function defaultLangCode() { const l = getLangs().find(x => x.def) || getLangs()[0]; return l ? l.code : "tr"; }
function getLang() {
  try {
    if (!i18nEnabled()) return "tr";
    const codes = getLangs().map(l => l.code);
    const cur = localStorage.getItem("ssl_lang");
    if (cur && codes.includes(cur)) return cur;            // 1) kullanıcının açık seçimi
    var nav = ((navigator.language || navigator.userLanguage || "") + "").slice(0, 2).toLowerCase();
    if (nav && codes.includes(nav)) return nav;            // 2) tarayıcı dili (eklediklerimiz arasındaysa)
    if (codes.includes("en")) return "en";                 // 3) değilse İngilizce
    return defaultLangCode();                              // 4) son çare varsayılan
  } catch (e) {}
  return "en";
}
function setLang(code) { try { localStorage.setItem("ssl_lang", code); } catch (e) {} window.location.reload(); }

/* string overrides: { code: { key: value } } */
function getOverrides() { try { return JSON.parse(localStorage.getItem("ssl_i18n_strings") || "{}") || {}; } catch (e) { return {}; } }
function setOverrides(o) {
  try { localStorage.setItem("ssl_i18n_strings", JSON.stringify(o)); } catch (e) {}
  if (window.sslApi && o) {
    Object.keys(o).forEach(function (lang) { window.sslApi.put("admin/i18n/strings", { lang: lang, entries: o[lang] || {} }); });
  }
}
function getStrings(code) {
  const base = DICT[code] || {};               // built-in for this lang (may be empty for new langs)
  const ov = getOverrides()[code] || {};
  return { ...DICT.tr, ...base, ...ov };        // tr as ultimate template, then built-in, then admin edits
}
function allKeys() {
  // DICT.tr (yerleşik) + DB override'ındaki tüm anahtarlar (bileşenlerden çıkarılan 386 ek anahtar dahil).
  const set = {};
  Object.keys(DICT.tr).forEach(function (k) { set[k] = 1; });
  try {
    const ov = getOverrides();
    Object.keys(ov).forEach(function (c) { Object.keys(ov[c] || {}).forEach(function (k) { set[k] = 1; }); });
  } catch (e) {}
  return Object.keys(set);
}

/* current language resolved once at load */
const CUR_LANG = getLang();
const STR = getStrings(CUR_LANG);
function t(key) { return (STR[key] !== undefined ? STR[key] : (DICT.tr[key] !== undefined ? DICT.tr[key] : key)); }

/* key → human label groups for the settings editor */
const STRING_GROUPS = [
  ["common", "Genel / Ortak"], ["nav", "Üst menü"], ["footer", "Alt bilgi"], ["admintabs", "Admin sekmeleri"],
  ["landing", "Anasayfa"], ["auth", "Giriş / Kayıt"], ["wiz", "Sertifika sihirbazı"],
  ["dash", "Müşteri paneli"], ["admin", "Admin"], ["reports", "Raporlar"],
  ["blogui", "Blog (genel)"], ["blogadmin", "Blog yönetimi"],
  ["settings", "Ayarlar"],
  ["email", "E-posta şablonları"],
  ["nf", "404 sayfası"],
];

Object.assign(window, {
  DICT, DEFAULT_LANGS, t, getLang, setLang, getLangs, setLangs, defaultLangCode,
  i18nEnabled, setI18nEnabled, getOverrides, setOverrides, getStrings, allKeys,
  STRING_GROUPS, CUR_LANG,
});
