/* Core: i18n, router, quote store, SEO, shared UI */
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

/* ---------------- i18n ---------------- */
function translate(lang, key, vars) {
  let s = (window.I18N[lang] && window.I18N[lang][key]) ?? window.I18N.tr[key] ?? key;
  if (vars) Object.keys(vars).forEach(k => { s = s.split("{" + k + "}").join(vars[k]); });
  return s;
}

/* ---------------- router (hash simulates /tr/urunler/...) ---------------- */
function parseHash() {
  const raw = (location.hash || "").replace(/^#\/?/, "");
  const qi0 = raw.indexOf("?");
  const parts = (qi0 > -1 ? raw.slice(0, qi0) : raw).split("/").filter(Boolean);
  let lang = parts[0];
  if (!window.LANGS.includes(lang)) lang = localStorage.getItem("ms_lang") || "tr";
  const seg = parts[1] || "";
  const slug = parts[2] || null;
  const routes = window.ROUTES[lang];
  let page = Object.keys(routes).find(k => routes[k] === seg);
  if (page === undefined) page = seg ? "notfound" : "home";
  let catId = null;
  if (page === "products" && slug) {
    catId = Object.keys(window.SEO_CONTENT[lang].cats).find(k => window.SEO_CONTENT[lang].cats[k].slug === slug);
    page = catId ? "category" : "product";
  }
  const q = {};
  const qi = raw.indexOf("?");
  if (qi > -1) new URLSearchParams(raw.slice(qi + 1)).forEach((v, k) => (q[k] = v));
  return { lang, page, slug: catId || slug, q };
}
function pathFor(lang, page, slug) {
  const r = window.ROUTES[lang];
  if (page === "product") return `/${lang}/${r.products}/${slug}`;
  if (page === "category") return `/${lang}/${r.products}/${window.SEO_CONTENT[lang].cats[slug].slug}`;
  const seg = r[page] ?? "";
  return `/${lang}/${seg}${seg ? "" : ""}`.replace(/\/$/, "/");
}
function hrefFor(lang, page, slug, query) {
  return "#" + pathFor(lang, page, slug) + (query ? "?" + query : "");
}
function go(lang, page, slug, query) {
  location.hash = hrefFor(lang, page, slug, query);
}

const Ctx = createContext(null);
const useApp = () => useContext(Ctx);

/* ---------------- quote store ---------------- */
function useQuoteStore() {
  const [items, setItems] = useState(() => {
    try { return JSON.parse(localStorage.getItem("ms_quote") || "[]"); } catch (e) { return []; }
  });
  useEffect(() => { localStorage.setItem("ms_quote", JSON.stringify(items)); }, [items]);
  const has = id => items.some(i => i.id === id);
  const add = id => setItems(xs => (xs.some(i => i.id === id) ? xs : [...xs, { id, qty: "", unit: "m2", note: "" }]));
  const remove = id => setItems(xs => xs.filter(i => i.id !== id));
  const update = (id, patch) => setItems(xs => xs.map(i => (i.id === id ? { ...i, ...patch } : i)));
  const clear = () => setItems([]);
  return { items, has, add, remove, update, clear };
}

/* ---------------- SEO head management ---------------- */
function useSeo(route, t) {
  useEffect(() => {
    const { lang, page, slug } = route;
    const product = page === "product" ? window.PRODUCTS.find(p => p.id === slug) : null;
    const key = page === "product" ? "products" : page;
    let title = translate(lang, `seo.${key}.t`);
    let desc = translate(lang, `seo.${key}.d`);
    if (product) {
      title = `${product.name} — ${translate(lang, "cat." + product.cat)} | Meriç Seramik`;
      desc = translate(lang, "d.desc", productDescVars(lang, product));
    }
    if (page === "category") {
      const cc = window.SEO_CONTENT[lang].cats[slug];
      title = `${cc.h1} — Edirne | Meriç Seramik`;
      desc = cc.intro;
    }
    if (page === "notfound") title = translate(lang, "nf.title") + " — Meriç Seramik";
    document.title = title;
    document.documentElement.lang = lang;
    setMeta("description", desc);
    setMeta("og:title", title, true);
    setMeta("og:description", desc, true);
    setMeta("og:locale", { tr: "tr_TR", en: "en_GB", bg: "bg_BG", el: "el_GR" }[lang], true);
    // canonical + hreflang (each language version is its own canonical URL)
    document.querySelectorAll('link[data-seo]').forEach(n => n.remove());
    const base = window.SITE.baseUrl;
    addLink("canonical", base + pathFor(lang, page, slug));
    window.LANGS.forEach(l => addLink("alternate", base + pathFor(l, page, slug), l));
    addLink("alternate", base + pathFor("tr", page, slug), "x-default");
    // JSON-LD: only on-screen, verified info (name, city, Instagram). Products are demo → no Product schema.
    const ld = [{
      "@context": "https://schema.org", "@type": "Store", name: "Meriç Seramik",
      address: { "@type": "PostalAddress", streetAddress: window.SITE.addressParts.street, postalCode: window.SITE.addressParts.postal, addressLocality: window.SITE.addressParts.locality, addressRegion: window.SITE.addressParts.region, addressCountry: "TR" },
      telephone: window.SITE.phone || undefined,
      openingHoursSpecification: (window.SITE.hours || []).map(r => ({ "@type": "OpeningHoursSpecification", dayOfWeek: r.schema, opens: r.open, closes: r.close })),
      sameAs: [window.SITE.instagram], hasMap: "https://maps.google.com/?cid=" + window.SITE.mapsCid, url: base + pathFor(lang, "home")
    }];
    const crumbs = breadcrumbFor(route);
    if (crumbs.length > 1) ld.push({
      "@context": "https://schema.org", "@type": "BreadcrumbList",
      itemListElement: crumbs.map((c, i) => ({ "@type": "ListItem", position: i + 1, name: c.label, item: base + c.path }))
    });
    const faqs = faqsFor(route);
    if (faqs.length) ld.push({
      "@context": "https://schema.org", "@type": "FAQPage",
      mainEntity: faqs.map(([q, a]) => ({ "@type": "Question", name: q, acceptedAnswer: { "@type": "Answer", text: a } }))
    });
    let s = document.getElementById("ld-json");
    if (!s) { s = document.createElement("script"); s.type = "application/ld+json"; s.id = "ld-json"; document.head.appendChild(s); }
    s.textContent = JSON.stringify(ld);
  }, [route.lang, route.page, route.slug]);
}
/* Single source of FAQ data per page — rendered on screen AND emitted as FAQPage JSON-LD */
function faqsFor(route) {
  const { lang, page, slug } = route;
  const S = window.SEO_CONTENT[lang];
  if (page === "home") return [1, 2, 3, 4, 5].map(n => [translate(lang, `faq.q${n}`), translate(lang, `faq.a${n}`)]).concat(S.homeFaq);
  if (page === "category") return S.cats[slug].faq;
  if (page === "product") {
    const p = window.PRODUCTS.find(x => x.id === slug);
    if (!p) return [];
    const v = { name: p.name, size: p.size, usage: p.usage.map(u => translate(lang, "v." + u).toLowerCase()).join(", ") };
    const fill = s => Object.keys(v).reduce((acc, k) => acc.split("{" + k + "}").join(v[k]), s);
    return S.productFaq.map(([q, a]) => [fill(q), fill(a)]);
  }
  return [];
}
function setMeta(name, content, prop) {
  const attr = prop ? "property" : "name";
  let m = document.querySelector(`meta[${attr}="${name}"]`);
  if (!m) { m = document.createElement("meta"); m.setAttribute(attr, name); document.head.appendChild(m); }
  m.setAttribute("content", content);
}
function addLink(rel, href, hreflang) {
  const l = document.createElement("link");
  l.rel = rel; l.href = href; l.dataset.seo = "1";
  if (hreflang) l.hreflang = hreflang;
  document.head.appendChild(l);
}
function breadcrumbFor(route) {
  const { lang, page, slug } = route;
  const c = [{ label: translate(lang, "nav.home"), path: pathFor(lang, "home"), page: "home" }];
  const map = { products: "nav.products", inspiration: "nav.inspiration", about: "nav.about", contact: "nav.contact", quote: "q.title", privacy: "pv.title", admin: "foot.admin" };
  if (page === "product") {
    c.push({ label: translate(lang, "nav.products"), path: pathFor(lang, "products"), page: "products" });
    const p = window.PRODUCTS.find(x => x.id === slug);
    if (p) {
      c.push({ label: window.SEO_CONTENT[lang].cats[p.cat].h1, path: pathFor(lang, "category", p.cat), page: "category" });
      c.push({ label: p.name, path: pathFor(lang, "product", slug) });
    }
  } else if (page === "category") {
    c.push({ label: translate(lang, "nav.products"), path: pathFor(lang, "products"), page: "products" });
    c.push({ label: window.SEO_CONTENT[lang].cats[slug].h1, path: pathFor(lang, "category", slug) });
  } else if (map[page]) c.push({ label: translate(lang, map[page]), path: pathFor(lang, page), page });
  return c;
}
function productDescVars(lang, p) {
  const t = k => translate(lang, k);
  return {
    look: t("v." + p.look), surface: t("v." + p.surface).toLowerCase(), size: p.size,
    cat: t("cat." + p.cat).toLowerCase(), usage: p.usage.map(u => t("v." + u).toLowerCase()).join(", ")
  };
}

/* ---------------- icons (simple strokes only) ---------------- */
const Ico = {
  arrow: (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  left: (s = 18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg>,
  right: (s = 18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg>,
  close: (s = 20) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>,
  menu: (s = 20) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><path d="M4 8h16M4 16h16"/></svg>,
  plus: (s = 14) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>,
  globe: (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14.5 0 18M12 3c-3 3.5-3 14.5 0 18"/></svg>,
  list: (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><rect x="4" y="4" width="7" height="7"/><rect x="13" y="13" width="7" height="7"/><path d="M14 7h6M4 17h6"/></svg>,
  filter: (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><path d="M4 6h16M7 12h10M10 18h4"/></svg>,
  chat: (s = 15) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true"><path d="M4 19l1.5-4A8 8 0 1 1 9 19.5z"/></svg>,
  info: (s = 18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7.5v.5"/></svg>,
  check: (s = 18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>,
  pin: (s = 16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><path d="M12 21s-6-5.5-6-11a6 6 0 0 1 12 0c0 5.5-6 11-6 11z"/><circle cx="12" cy="10" r="2"/></svg>,
  zoom: (s = 18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true"><circle cx="11" cy="11" r="6"/><path d="M20 20l-4.5-4.5M11 8v6M8 11h6"/></svg>
};

/* ---------------- shared bits ---------------- */
function Link({ page, slug, query, className, children, ...rest }) {
  const { route } = useApp();
  return <a href={hrefFor(route.lang, page, slug, query)} className={className}
    aria-current={route.page === page ? "page" : undefined} {...rest}>{children}</a>;
}

function Pending({ children }) {
  const { t } = useApp();
  return <em className="pending">{children || t("pending")}</em>;
}

function Crumbs() {
  const { route } = useApp();
  const c = breadcrumbFor(route);
  return (
    <nav aria-label="Breadcrumb">
      <ol className="crumbs">
        {c.map((x, i) => (
          <li key={i}>{i < c.length - 1 ? <a href={"#" + x.path}>{x.label}</a> : <span aria-current="page">{x.label}</span>}</li>
        ))}
      </ol>
    </nav>
  );
}

function PageHead({ title, lead, children }) {
  return (
    <header className="page-head">
      <div className="wrap">
        <Crumbs />
        <h1 className="h-1">{title}</h1>
        {lead && <p className="lead">{lead}</p>}
        {children}
      </div>
    </header>
  );
}

function AddButton({ product, className = "", full }) {
  const { t, quote, toast } = useApp();
  const added = quote.has(product.id);
  return (
    <button type="button" className={`btn ${added ? "is-added" : "btn-primary"} ${full ? "btn-block" : ""} ${className}`}
      aria-pressed={added}
      onClick={() => {
        if (added) { quote.remove(product.id); toast(t("toast.removed", { name: product.name })); }
        else { quote.add(product.id); toast(t("toast.added", { name: product.name }), true); }
      }}>
      {added ? t("card.added") : <>{Ico.plus()} {t("card.add")}</>}
    </button>
  );
}

function ProductCard({ p, forceSpec }) {
  const { t, route, specVariant } = useApp();
  const showSpec = forceSpec || specVariant !== "off";
  return (
    <article className="card">
      <a className="card-img spec-host" href={hrefFor(route.lang, "product", p.id)} aria-label={p.name} tabIndex={-1}>
        <img src={p.img[0]} alt="" loading="lazy" />
        {p.img[1] && <img className="alt" src={p.img[1]} alt="" loading="lazy" />}
        {!p.custom && <span className="tag-demo">{t("demo.badge")}</span>}
        {showSpec && <SpecCard p={p} variant={specVariant === "off" ? "panel" : specVariant} size="sm" inLink fields={{ model: false, size: true, type: true, look: true, badges: true }} />}
      </a>
      <div className="card-body">
        <span className="card-code">{p.code}</span>
        <h3><a href={hrefFor(route.lang, "product", p.id)}>{p.name}</a></h3>
        <p className="card-spec">{showSpec ? t("v." + p.surface) + " · " + t("cat." + p.cat) : p.size + " cm · " + t("v." + p.surface) + " · " + t("v." + p.look)}</p>
        <p className="card-price">{t("price.note")}</p>
        <div className="card-actions">
          <a className="btn btn-line btn-sm" href={hrefFor(route.lang, "product", p.id)}>{t("card.view")}</a>
          <AddButton product={p} className="btn-sm" />
        </div>
      </div>
    </article>
  );
}

/* WhatsApp: real wa.me when number exists, otherwise demo modal with prepared message */
function waUrl(msg) {
  const n = window.SITE.whatsapp;
  return n ? `https://wa.me/${n}?text=${encodeURIComponent(msg)}` : null;
}

function FaqList({ items, openFirst = true }) {
  return (
    <div className="faq-list">
      {items.map(([q, a], i) => (
        <details key={q} className="faq-item" open={openFirst && i === 0}>
          <summary><span>{q}</span><span className="pm" aria-hidden="true">{Ico.plus()}</span></summary>
          <p>{a}</p>
        </details>
      ))}
    </div>
  );
}

function LogoMark({ id = "logo-mark" }) {
  return (
    <span className="brand-mark" aria-hidden="true">
      <img src="img/logo.png" alt="" width="50" height="50" />
    </span>
  );
}

Object.assign(window, {
  translate, parseHash, pathFor, faqsFor, hrefFor, go, Ctx, useApp, useQuoteStore, useSeo, breadcrumbFor, productDescVars,
  Ico, Link, Pending, FaqList, Crumbs, PageHead, AddButton, ProductCard, waUrl, LogoMark
});
