// ---------- Centralized SEO helpers (meta, OG, Twitter, JSON-LD) ----------
// All canonical URLs use clean paths (/alternativa/slug) — those are the URLs
// indexed by Google. The SPA itself navigates with hash routes for static hosting,
// but redirects/server rewrites should map clean URLs to the SPA at deploy time.

const SITE_URL = "https://alternativegratis.it";
const SITE_NAME = "AlternativeGratis.it";
const DEFAULT_OG_IMAGE = "https://alternativegratis.it/og-default.png";

function _setMetaName(name, content) {
  if (content == null || content === '') return;
  let m = document.head.querySelector(`meta[name="${name}"]`);
  if (!m) { m = document.createElement('meta'); m.setAttribute('name', name); document.head.appendChild(m); }
  m.setAttribute('content', content);
}

function _setMetaProp(prop, content) {
  if (content == null || content === '') return;
  let m = document.head.querySelector(`meta[property="${prop}"]`);
  if (!m) { m = document.createElement('meta'); m.setAttribute('property', prop); document.head.appendChild(m); }
  m.setAttribute('content', content);
}

function _setLink(rel, href) {
  let l = document.head.querySelector(`link[rel="${rel}"]`);
  if (!l) { l = document.createElement('link'); l.setAttribute('rel', rel); document.head.appendChild(l); }
  l.setAttribute('href', href);
}

// Apply the full set of meta tags for a page in one call.
// opts: { title, description, path, type='website', image, keywords, robots }
function applyPageSEO(opts) {
  const {
    title,
    description,
    path = '/',
    type = 'website',
    image = DEFAULT_OG_IMAGE,
    keywords,
    robots = 'index,follow,max-image-preview:large,max-snippet:-1',
  } = opts || {};
  const url = SITE_URL + (path.startsWith('/') ? path : '/' + path);

  document.title = title;
  _setMetaName('description', description);
  _setMetaName('robots', robots);
  if (keywords) _setMetaName('keywords', keywords);

  // Canonical
  _setLink('canonical', url);

  // Open Graph
  _setMetaProp('og:title', title);
  _setMetaProp('og:description', description);
  _setMetaProp('og:url', url);
  _setMetaProp('og:type', type);
  _setMetaProp('og:site_name', SITE_NAME);
  _setMetaProp('og:locale', 'it_IT');
  _setMetaProp('og:image', image);

  // Twitter
  _setMetaName('twitter:card', 'summary_large_image');
  _setMetaName('twitter:title', title);
  _setMetaName('twitter:description', description);
  _setMetaName('twitter:image', image);
}

// JSON-LD: replace any prior dynamic schemas, then inject the supplied list.
function setSchemas(schemas) {
  document.head.querySelectorAll('script[data-schema="dynamic"]').forEach(s => s.remove());
  for (const s of (schemas || [])) {
    const el = document.createElement('script');
    el.type = 'application/ld+json';
    el.setAttribute('data-schema', 'dynamic');
    el.textContent = JSON.stringify(s);
    document.head.appendChild(el);
  }
}

// ---------- Schema builders ----------

function breadcrumbSchema(items) {
  // items: [{name, path}]
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": items.map((it, i) => ({
      "@type": "ListItem",
      "position": i + 1,
      "name": it.name,
      "item": SITE_URL + (it.path.startsWith('/') ? it.path : '/' + it.path),
    })),
  };
}

function websiteSchema() {
  return {
    "@context": "https://schema.org",
    "@type": "WebSite",
    "name": SITE_NAME,
    "url": SITE_URL + "/",
    "inLanguage": "it-IT",
    "description": "Directory italiana delle migliori alternative gratuite e open source ai software a pagamento.",
    "potentialAction": {
      "@type": "SearchAction",
      "target": { "@type": "EntryPoint", "urlTemplate": SITE_URL + "/software?q={search_term_string}" },
      "query-input": "required name=search_term_string",
    },
  };
}

function organizationSchema() {
  return {
    "@context": "https://schema.org",
    "@type": "Organization",
    "name": SITE_NAME,
    "url": SITE_URL + "/",
    "email": "ciao@alternativegratis.it",
    "description": "Recensioni indipendenti di alternative gratuite e open source ai software a pagamento, in italiano.",
  };
}

function softwareApplicationSchema(sw, opts = {}) {
  const url = SITE_URL + `/alternativa/${sw.slug}`;
  return {
    "@context": "https://schema.org",
    "@type": "SoftwareApplication",
    "name": sw.nome,
    "applicationCategory": sw.categoria,
    "operatingSystem": (sw.piattaforme || []).join(', '),
    "url": sw.sito_ufficiale,
    "description": sw.descrizione_it,
    "offers": opts.paidOffer ? {
      "@type": "Offer",
      "price": opts.paidOffer.price,
      "priceCurrency": opts.paidOffer.currency || "EUR",
      "url": sw.sito_ufficiale,
    } : undefined,
    "mainEntityOfPage": url,
  };
}

function freeAlternativeSchema(alt, parentCategoria) {
  return {
    "@type": "SoftwareApplication",
    "name": alt.nome,
    "applicationCategory": parentCategoria,
    "operatingSystem": (alt.piattaforme || []).join(', '),
    "url": alt.sito_ufficiale,
    "description": alt.descrizione_it,
    "offers": { "@type": "Offer", "price": "0", "priceCurrency": "EUR" },
    "aggregateRating": alt.valutazione ? {
      "@type": "AggregateRating",
      "ratingValue": alt.valutazione.toFixed(1),
      "bestRating": "5",
      "ratingCount": "1",
    } : undefined,
  };
}

function alternativesItemList(sw, alts) {
  return {
    "@context": "https://schema.org",
    "@type": "ItemList",
    "name": `Alternative gratuite a ${sw.nome}`,
    "description": `Le ${alts.length} migliori alternative gratis e open source a ${sw.nome}, testate e confrontate.`,
    "numberOfItems": alts.length,
    "itemListElement": alts.map((a, i) => ({
      "@type": "ListItem",
      "position": i + 1,
      "item": freeAlternativeSchema(a, sw.categoria),
    })),
  };
}

function faqPageSchema(faqs) {
  return {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "mainEntity": faqs.map(f => ({
      "@type": "Question",
      "name": f.q,
      "acceptedAnswer": { "@type": "Answer", "text": f.a },
    })),
  };
}

function categoryItemList(category, softwareList) {
  return {
    "@context": "https://schema.org",
    "@type": "ItemList",
    "name": `Software in ${category.name}`,
    "numberOfItems": softwareList.length,
    "itemListElement": softwareList.map((s, i) => ({
      "@type": "ListItem",
      "position": i + 1,
      "url": SITE_URL + `/alternativa/${s.slug}`,
      "name": `Alternative gratis a ${s.nome}`,
    })),
  };
}

function collectionPageSchema(name, description, path) {
  return {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    "name": name,
    "description": description,
    "url": SITE_URL + path,
    "inLanguage": "it-IT",
    "isPartOf": { "@type": "WebSite", "name": SITE_NAME, "url": SITE_URL + "/" },
  };
}

Object.assign(window, {
  SITE_URL, SITE_NAME,
  applyPageSEO, setSchemas,
  breadcrumbSchema, websiteSchema, organizationSchema,
  softwareApplicationSchema, alternativesItemList, faqPageSchema,
  categoryItemList, collectionPageSchema,
});
