/* Shared blog components: nav, language toggle, view-counter hook, SEO. */

/* ---------- Language: persisted via localStorage + ?lang URL param ---------- */

function getInitialLang() {
  const url = new URL(window.location.href);
  const q = url.searchParams.get("lang");
  if (q === "en" || q === "ar") return q;
  const stored = localStorage.getItem("innoveev:lang");
  if (stored === "en" || stored === "ar") return stored;
  return "en";
}

function useLang() {
  const [lang, setLangState] = React.useState(getInitialLang);
  const setLang = React.useCallback((next) => {
    setLangState(next);
    localStorage.setItem("innoveev:lang", next);
    const url = new URL(window.location.href);
    url.searchParams.set("lang", next);
    window.history.replaceState({}, "", url.toString());
  }, []);

  // Sync html lang/dir + body class
  React.useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === "ar" ? "rtl" : "ltr";
    document.body.classList.toggle("rtl", lang === "ar");
  }, [lang]);

  return [lang, setLang];
}

const T = {
  en: {
    siteTagline: "Software studio building the next wave of digital products",
    nav: { services: "Services", work: "Work", blog: "Blog", studio: "Studio", faq: "FAQ", contact: "Contact sales" },
    blog: {
      eyebrow: "The Innoveev Journal",
      title: "Field notes from a product studio.",
      subtitle: "Engineering, design and AI insights from the team shipping software across four time zones.",
      allTopics: "All topics",
      featured: "Featured",
      latest: "Latest",
      readMore: "Read article",
      minRead: "min read",
      views: "views",
      view: "view",
      publishedOn: "Published",
      author: "Author",
      shareArticle: "Share article",
      copyLink: "Copy link",
      linkCopied: "Link copied",
      tableOfContents: "On this page",
      relatedReading: "Related reading",
      keepReading: "Keep reading",
      back: "All articles",
      newsletter: "Subscribe to field notes",
      newsletterDesc: "One email per fortnight. Engineering, design, and what's actually shipping.",
      subscribe: "Subscribe",
      emailPlaceholder: "you@company.com",
      langLabel: "Read in Arabic",
      langSwitchTo: "العربية",
    },
  },
  ar: {
    siteTagline: "استوديو برمجيات يبني الموجة القادمة من المنتجات الرقمية",
    nav: { services: "خدماتنا", work: "أعمالنا", blog: "المدوّنة", studio: "الاستوديو", faq: "الأسئلة", contact: "تواصل مع المبيعات" },
    blog: {
      eyebrow: "مجلّة Innoveev",
      title: "ملاحظات من استوديو منتجات.",
      subtitle: "رؤى هندسيّة وتصميميّة ومن عالم الذكاء الاصطناعي من الفريق الذي يشحن البرمجيّات عبر أربع مناطق زمنية.",
      allTopics: "كل المواضيع",
      featured: "مميّز",
      latest: "الأحدث",
      readMore: "اقرأ المقال",
      minRead: "دقيقة قراءة",
      views: "مشاهدة",
      view: "مشاهدة",
      publishedOn: "نُشر في",
      author: "الكاتب",
      shareArticle: "شارك المقال",
      copyLink: "انسخ الرابط",
      linkCopied: "تم النسخ",
      tableOfContents: "في هذه الصفحة",
      relatedReading: "قراءات ذات صلة",
      keepReading: "تابع القراءة",
      back: "كل المقالات",
      newsletter: "اشترك في ملاحظاتنا",
      newsletterDesc: "بريد واحد كل أسبوعين. هندسة، تصميم، وما يُشحَن فعلاً.",
      subscribe: "اشترك",
      emailPlaceholder: "you@company.com",
      langLabel: "اقرأ بالإنجليزية",
      langSwitchTo: "English",
    },
  },
};

/* ---------- View counter ---------- */

function useViewCount(slug, opts = {}) {
  const { increment = false } = opts;
  const key = `innoveev:views:${slug}`;
  const [count, setCount] = React.useState(() => {
    const v = parseInt(localStorage.getItem(key) || "0", 10);
    return Number.isFinite(v) ? v : 0;
  });
  React.useEffect(() => {
    if (!increment) return;
    // Throttle increments to once per slug per 30s in the same browser
    const session = sessionStorage.getItem(`innoveev:viewed:${slug}`);
    if (session) return;
    const seedKey = `innoveev:seeded:${slug}`;
    let next = count + 1;
    if (!localStorage.getItem(seedKey)) {
      // Seed with a believable starting count (40–520) the first time someone
      // visits a post in this browser — pure UI sugar; in production you'd read
      // a real count from Postgres via your /actions/blog.ts endpoint.
      const seed = 40 + Math.floor(Math.random() * 480);
      next = seed + 1;
      localStorage.setItem(seedKey, "1");
    }
    localStorage.setItem(key, String(next));
    sessionStorage.setItem(`innoveev:viewed:${slug}`, "1");
    setCount(next);
  }, [slug, increment]);
  return count;
}

/* ---------- Shared UI: Nav, Brand, Footer ---------- */

function BlogBrand() {
  return (
    <a href="index.html" className="brand" aria-label="Innoveev home">
      <span className="brand-mark" aria-hidden="true"></span>
      <span>Innoveev</span>
    </a>
  );
}

function LangToggle({ lang, onChange }) {
  const t = T[lang].blog;
  const next = lang === "en" ? "ar" : "en";
  return (
    <button
      type="button"
      className="lang-toggle"
      onClick={() => onChange(next)}
      aria-label={t.langLabel}
    >
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
        <circle cx="8" cy="8" r="6.25" />
        <path d="M1.75 8h12.5M8 1.75c2 2.2 3 4.6 3 6.25s-1 4.05-3 6.25M8 1.75c-2 2.2-3 4.6-3 6.25s1 4.05 3 6.25" />
      </svg>
      <span>{t.langSwitchTo}</span>
    </button>
  );
}

/* BlogNav and BlogFooter have been removed — all pages use the unified
   <Nav /> and <Footer /> from components/nav.jsx and components/closer.jsx. */

/* Reuse Arrow from primitives; if not loaded define a fallback */
if (typeof window.Arrow === "undefined") {
  window.Arrow = function Arrow({ size = 14 }) {
    return (
      <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
        <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  };
}

/* ---------- SEO helpers — update meta tags client-side ---------- */
/* (In production these belong in the server response. For the prototype
    we update them on navigation so view-source still has good defaults.) */

function setMeta(name, content, attr = "name") {
  if (!content) return;
  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, attrs = {}) {
  let el = document.head.querySelector(`link[rel="${rel}"]${attrs.hreflang ? `[hreflang="${attrs.hreflang}"]` : ""}`);
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", rel);
    Object.entries(attrs).forEach(([k, v]) => el.setAttribute(k, v));
    document.head.appendChild(el);
  }
  el.setAttribute("href", href);
}

function injectJsonLd(id, payload) {
  const existing = document.getElementById(id);
  if (existing) existing.remove();
  const script = document.createElement("script");
  script.id = id;
  script.type = "application/ld+json";
  script.textContent = JSON.stringify(payload);
  document.head.appendChild(script);
}

function applySEO({ title, description, keywords = [], canonical, image, type = "website", lang, publishedAt, author, hreflangs = {} }) {
  document.title = title;
  setMeta("description", description);
  if (keywords.length) setMeta("keywords", keywords.join(", "));

  // Open Graph
  setMeta("og:title", title, "property");
  setMeta("og:description", description, "property");
  setMeta("og:type", type, "property");
  if (canonical) setMeta("og:url", canonical, "property");
  if (image) setMeta("og:image", image, "property");
  setMeta("og:locale", lang === "ar" ? "ar_AE" : "en_US", "property");
  setMeta("og:site_name", "Innoveev", "property");

  // Twitter
  setMeta("twitter:card", "summary_large_image");
  setMeta("twitter:title", title);
  setMeta("twitter:description", description);
  if (image) setMeta("twitter:image", image);

  // Canonical + hreflang
  if (canonical) setLink("canonical", canonical);
  Object.entries(hreflangs).forEach(([code, href]) => setLink("alternate", href, { hreflang: code }));
}

Object.assign(window, {
  useLang, T, useViewCount,
  BlogBrand, LangToggle,
  applySEO, injectJsonLd,
});
