/* SPA SEO helper — keeps document.title and meta tags in sync with the
   current route. Googlebot does execute JS, but having strong static
   defaults in index.html plus per-route updates is the belt-and-braces
   approach. */

const DEFAULT_TITLE = "Larissa Fine Art — Original Oil Paintings from Rural Ontario";
const DEFAULT_DESC = "Original oil paintings by Larissa — landscapes, florals and still life from a small studio in Highlands, Ontario. One-of-one works, hand-signed in oil, shipped worldwide.";

function setMeta(name, value, attr = "name") {
  if (!value) 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", value);
}

function setCanonical(href) {
  let el = document.head.querySelector('link[rel="canonical"]');
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", "canonical");
    document.head.appendChild(el);
  }
  el.setAttribute("href", href);
}

function setJsonLd(id, json) {
  let el = document.getElementById(id);
  if (!el) {
    el = document.createElement("script");
    el.type = "application/ld+json";
    el.id = id;
    document.head.appendChild(el);
  }
  el.textContent = json ? JSON.stringify(json) : "";
  if (!json) el.remove();
}

function applySeo({ title, description, canonical, image, jsonLd, noindex }) {
  document.title = title || DEFAULT_TITLE;
  setMeta("description", description || DEFAULT_DESC);
  setMeta("og:title", title || DEFAULT_TITLE, "property");
  setMeta("og:description", description || DEFAULT_DESC, "property");
  setMeta("twitter:title", title || DEFAULT_TITLE);
  setMeta("twitter:description", description || DEFAULT_DESC);
  if (image) {
    setMeta("og:image", image, "property");
    setMeta("twitter:image", image);
  }
  if (canonical) {
    setCanonical(canonical);
    setMeta("og:url", canonical, "property");
  }
  setMeta(
    "robots",
    noindex ? "noindex,nofollow" : "index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1"
  );
  setJsonLd("lf-route-jsonld", jsonLd || null);
}

function useSeo(opts) {
  // opts is { title, description, canonical, image, jsonLd } or null to reset
  useEffect(() => {
    applySeo(opts || {});
    return () => applySeo({}); // reset to defaults on unmount
  }, [opts && opts.canonical, opts && opts.title]);
}

window.useSeo = useSeo;
window.lfSeoDefault = { title: DEFAULT_TITLE, description: DEFAULT_DESC };
