// SEO / AEO / GEO – JSON-LD structured data injector
// Updates <script type="application/ld+json"> blocks based on current route so
// crawlers + LLM cite engines (ChatGPT, Perplexity, Gemini, AI overviews) can
// extract clean facts from each page state of the SPA.

function setSchema(id, payload) {
  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.stringify(payload, null, 2);
}

function removeSchema(id) {
  const el = document.getElementById(id);
  if (el) el.remove();
}

const ORG_SCHEMA = {
  "@context": "https://schema.org",
  "@type": "ProfessionalService",
  "name": "Migronis",
  "alternateName": "Migronis Citizenship",
  "url": "https://migronis.com",
  "logo": "https://cdn.migronis.com/img/headerLogo.svg",
  "description": "Licensed citizenship and residency by investment agent. Since 2012, Migronis has guided 2,400+ families through investment migration programs. 20 vetted programs across the Caribbean, EU, USA, Latin America and the Pacific.",
  "foundingDate": "2012",
  "founder": {
    "@type": "Person",
    "name": "Anatoliy Letaev",
    "jobTitle": "Founder",
    "nationality": "Ukraine",
    "sameAs": [
      "https://www.linkedin.com/in/anatoliy-lyetayev/",
      "https://www.youtube.com/channel/UC_ANX1heIr3xVKAYBv5GsrQ",
      "https://www.facebook.com/anatoliy.letaev"
    ]
  },
  "areaServed": ["Worldwide", "Caribbean", "European Union", "MENA", "North America", "Pacific"],
  "serviceType": ["Citizenship by Investment", "Residency by Investment", "Second Passport", "Golden Visa"],
  "location": [
    {
      "@type": "Place",
      "name": "Migronis Estoril Office",
      "address": { "@type": "PostalAddress", "streetAddress": "Av. Sabóia 486", "addressLocality": "Estoril", "addressCountry": "PT" }
    },
    {
      "@type": "Place",
      "name": "Migronis Csomád Office",
      "address": { "@type": "PostalAddress", "streetAddress": "Verebeshegy u. 11", "addressLocality": "Csomád", "addressCountry": "HU" }
    }
  ],
  "award": [
    "Global Law Experts Awards 2021 – One of The Best Citizenship-for-Investment Companies",
    "UGLOBAL TOP-25 Immigration Companies Worldwide",
    "Global Law Experts Awards 2020 – One of The Best Citizenship-for-Investment Companies"
  ],
  "sameAs": [
    "https://www.instagram.com/migronis",
    "https://www.facebook.com/migronis.en",
    "https://x.com/migronis_global",
    "https://www.linkedin.com/company/migronis-global/"
  ],
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "4.9",
    "reviewCount": "187",
    "bestRating": "5"
  }
};

const WEBSITE_SCHEMA = {
  "@context": "https://schema.org",
  "@type": "WebSite",
  "name": "Migronis",
  "url": "https://migronis.com",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "https://migronis.com/search?q={search_term_string}",
    "query-input": "required name=search_term_string"
  }
};

function serviceSchema(p, isCBI) {
  const cur = p.currency === 'USD' ? 'USD' : 'EUR';
  return {
    "@context": "https://schema.org",
    "@type": "Service",
    "serviceType": isCBI ? "Citizenship by Investment" : "Residency by Investment",
    "name": p.country + (isCBI ? " citizenship by investment" : " residency by investment"),
    "provider": { "@type": "ProfessionalService", "name": "Migronis", "url": "https://migronis.com" },
    "areaServed": p.country,
    "description": p.tagline.en + ". " + p.highlights.en.join('. ') + ".",
    "offers": {
      "@type": "Offer",
      "price": p.minInvest,
      "priceCurrency": cur,
      "url": "https://migronis.com/" + (isCBI ? "citizenship" : "residency") + "/" + p.id,
      "availability": "https://schema.org/InStock",
      "description": `From ${cur} ${p.minInvest.toLocaleString()} via ${p.route}`
    },
    "additionalProperty": [
      { "@type": "PropertyValue", "name": "Minimum investment", "value": `${cur} ${p.minInvest.toLocaleString()}` },
      { "@type": "PropertyValue", "name": "Timeline", "value": p.term },
      { "@type": "PropertyValue", "name": "Visa-free countries", "value": String(p.visaFree) },
      { "@type": "PropertyValue", "name": "Tax regime", "value": p.tax },
      { "@type": "PropertyValue", "name": "Investment route", "value": p.route },
    ]
  };
}

function faqSchema(items) {
  return {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "mainEntity": items.map((it) => ({
      "@type": "Question",
      "name": it.q.en,
      "acceptedAnswer": { "@type": "Answer", "text": it.a.en }
    }))
  };
}

function breadcrumbSchema(items) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": items.map((it, i) => ({
      "@type": "ListItem", "position": i + 1, "name": it.name, "item": it.url
    }))
  };
}

function offerCatalogSchema(programs, isCBI) {
  return {
    "@context": "https://schema.org",
    "@type": "OfferCatalog",
    "name": isCBI ? "Citizenship-by-Investment programs" : "Residency-by-Investment programs",
    "itemListElement": programs.map((p) => ({
      "@type": "Offer",
      "name": p.country,
      "price": p.minInvest,
      "priceCurrency": p.currency,
      "description": p.tagline.en,
      "url": "https://migronis.com/" + (isCBI ? "citizenship" : "residency") + "/" + p.id,
    }))
  };
}

function SchemaInjector({ route, lang }) {
  React.useEffect(() => {
    // Always inject Organization + WebSite + Catalogs
    setSchema('ld-organization', ORG_SCHEMA);
    setSchema('ld-website', WEBSITE_SCHEMA);
    setSchema('ld-faq', faqSchema(window.MIGRONIS_DATA.faq));
    setSchema('ld-catalog-cbi', offerCatalogSchema(window.MIGRONIS_DATA.citizenship, true));
    setSchema('ld-catalog-rbi', offerCatalogSchema(window.MIGRONIS_DATA.residency, false));

    // Route-specific
    if (route.name === 'program' && route.id) {
      const all = [...window.MIGRONIS_DATA.citizenship, ...window.MIGRONIS_DATA.residency];
      const p = all.find((x) => x.id === route.id);
      if (p) {
        const isCBI = window.MIGRONIS_DATA.citizenship.includes(p);
        setSchema('ld-service', serviceSchema(p, isCBI));
        setSchema('ld-breadcrumbs', breadcrumbSchema([
          { name: 'Home', url: 'https://migronis.com/' },
          { name: isCBI ? 'Citizenship' : 'Residency', url: 'https://migronis.com/' + (isCBI ? 'citizenship' : 'residency') },
          { name: p.country, url: 'https://migronis.com/' + (isCBI ? 'citizenship' : 'residency') + '/' + p.id },
        ]));
        // Update document title for the route
        document.title = `${p.country} ${isCBI ? 'Citizenship' : 'Residency'} by Investment · Migronis`;
        const desc = document.querySelector('meta[name="description"]');
        if (desc) desc.content = `${p.country}: from ${p.currency === 'USD' ? '$' : '€'}${(p.minInvest/1000).toFixed(0)}k, ${p.term}, ${p.visaFree} visa-free destinations. ${p.tagline.en}. Apply with Migronis – licensed agent since 2012.`;
      }
    } else {
      removeSchema('ld-service');
      if (route.name === 'home') {
        removeSchema('ld-breadcrumbs');
        document.title = 'Migronis – Citizenship & Residency by Investment · 20 programs since 2012';
      } else if (route.name === 'citizenship') {
        document.title = 'Citizenship by Investment – 9 programs · Migronis';
        setSchema('ld-breadcrumbs', breadcrumbSchema([
          { name: 'Home', url: 'https://migronis.com/' },
          { name: 'Citizenship', url: 'https://migronis.com/citizenship' },
        ]));
        const desc = document.querySelector('meta[name="description"]');
        if (desc) desc.content = '9 citizenship-by-investment programs from $90k. Grenada, Saint Kitts, Antigua, Dominica, Saint Lucia, Türkiye, São Tomé and Príncipe, Vanuatu, Nauru. Hereditary second passport. Apply with Migronis, licensed agent since 2012.';
      } else if (route.name === 'residency') {
        document.title = 'Residency by Investment – 11 programs · Migronis';
        setSchema('ld-breadcrumbs', breadcrumbSchema([
          { name: 'Home', url: 'https://migronis.com/' },
          { name: 'Residency', url: 'https://migronis.com/residency' },
        ]));
        const desc = document.querySelector('meta[name="description"]');
        if (desc) desc.content = '11 residency-by-investment programs. Portugal Golden Visa, Portugal HQA, Spain DNV, Greece, Cyprus, Hungary, USA EB-5, USA E-2, Costa Rica, Uruguay, Brazil. Path to EU citizenship / US Green Card. Migronis – licensed agent since 2012.';
      } else if (route.name === 'compare') {
        removeSchema('ld-breadcrumbs');
        document.title = 'Compare investment migration programs · Migronis';
      } else if (route.name === 'about') {
        removeSchema('ld-breadcrumbs');
        document.title = 'About Migronis · Licensed CBI/RBI agent since 2012';
      } else if (route.name === 'apply') {
        removeSchema('ld-breadcrumbs');
        document.title = 'Application · Migronis';
      } else if (route.name === 'dashboard') {
        removeSchema('ld-breadcrumbs');
        document.title = 'Dashboard · Migronis';
      }
    }
  }, [route.name, route.id, lang]);

  return null;
}

window.SchemaInjector = SchemaInjector;
