/* global React */
/* =============================================================================
   SEO HEAD SYNC
   - Per-route updates: <title>, meta description, canonical, Open Graph,
     Twitter card, and a per-page JSON-LD block (BreadcrumbList + Product/
     SoftwareApplication on AORBIT pages, BlogPosting placeholder on /blog).
   - The Organization JSON-LD is rendered statically in the HTML <head>
     (so it's visible to no-JS crawlers).
   - Per-page JSON-LD is injected into <script id="ld-page"> on route change.

   Usage (mounted once in App):
     <SEOHead route={route} />
   ============================================================================= */

const SITE_BASE = "https://doblier.io";
const SITE_NAME = "Doblier";
const DEFAULT_OG = `${SITE_BASE}/site/assets/og-default.png`;

/* Per-route SEO config. Title is appended " | Doblier" except for the home page. */
const ROUTE_SEO = {
  "/": {
    title: "Doblier — Enterprise AI Infrastructure",
    description: "Doblier builds private AI infrastructure that absorbs change. AORBIT — the autonomous enterprise intelligence suite. Production-grade. Banking-scale. Zero exfiltration.",
    breadcrumb: [{ name: "Home", url: "/" }],
    appendBrand: false,
  },
  "/aorbit": {
    title: "AORBIT — Autonomous Enterprise Intelligence Suite",
    description: "AORBIT is the autonomous enterprise intelligence suite from Doblier. Three layers — Foundation, Intelligence, Frontier — running inside your perimeter with zero data exfiltration.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "AORBIT", url: "/aorbit" }],
    productSchema: true,
  },
  "/aorbit/foundation": {
    title: "AORBIT 01 Foundation — Private AI Infrastructure",
    description: "Private AI Foundation. On-premise LLMs on NVIDIA GPUs, inside your network, behind your firewall. Zero API calls to external providers.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "AORBIT", url: "/aorbit" }, { name: "01 Foundation", url: "/aorbit/foundation" }],
    productSchema: true,
  },
  "/aorbit/intelligence": {
    title: "AORBIT 02 Intelligence — Multi-LLM Orchestration & AIOps",
    description: "Turn alert noise into action. Multi-LLM orchestration, RAG, governed routing, and AI-powered operations intelligence — built for banking-scale production.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "AORBIT", url: "/aorbit" }, { name: "02 Intelligence", url: "/aorbit/intelligence" }],
    productSchema: true,
  },
  "/aorbit/frontier": {
    title: "AORBIT 03 Frontier — Agentic Finance, Private Infrastructure",
    description: "Agentic finance for regulated institutions. Treasury, payments, and compliance — running on private infrastructure, no external API calls.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "AORBIT", url: "/aorbit" }, { name: "03 Frontier", url: "/aorbit/frontier" }],
    productSchema: true,
  },
  "/aorbit/architecture": {
    title: "AORBIT Architecture — The Five-Layer Reference",
    description: "The AORBIT five-layer reference architecture. From infrastructure through governance — the architecture that lets enterprise AI ship to production.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "AORBIT", url: "/aorbit" }, { name: "Architecture", url: "/aorbit/architecture" }],
    productSchema: true,
  },
  "/why-doblier/architecture-gap": {
    title: "The Architecture Gap — Why Enterprise AI Fails in Production",
    description: "The named gap between AI capability and enterprise architecture. 12-page research report covering the $401B infrastructure problem and the framework for closing it.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Why Doblier", url: "/why-doblier/architecture-gap" }, { name: "The Architecture Gap", url: "/why-doblier/architecture-gap" }],
  },
  "/why-doblier/data-sovereignty": {
    title: "Data Sovereignty — Build AI Where Your Data Lives",
    description: "Zero exfiltration by architecture. AORBIT runs where your data lives — meeting SAMA, GDPR, PCI DSS, and PDPL natively, not through contracts.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Why Doblier", url: "/why-doblier/architecture-gap" }, { name: "Data Sovereignty", url: "/why-doblier/data-sovereignty" }],
  },
  "/why-doblier/case-studies": {
    title: "Case Studies — Production Private AI Across 20+ Banks",
    description: "Anonymized case studies from 20+ banking engagements across four continents. Production-grade private AI deployments — not POCs.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Why Doblier", url: "/why-doblier/architecture-gap" }, { name: "Case Studies", url: "/why-doblier/case-studies" }],
  },
  "/why-doblier/security": {
    title: "Security & Trust — Security as Architecture, Not a Feature",
    description: "Security designed into every AORBIT layer. SOC 2, ISO 27001, GDPR, PCI DSS, SAMA, PDPL. Detailed compliance documentation available under NDA.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Why Doblier", url: "/why-doblier/architecture-gap" }, { name: "Security & Trust", url: "/why-doblier/security" }],
  },
  "/industries/banking": {
    title: "AI Infrastructure for Banking & Finance",
    description: "Private. Compliant. In production. Doblier has deployed AI inside 20+ banks across four continents — meeting SAMA, PCI DSS, and core banking requirements natively.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Industries", url: "/industries/banking" }, { name: "Banking & Finance", url: "/industries/banking" }],
  },
  "/industries/digital-assets": {
    title: "Compliant AI for Digital Assets & Agentic Finance",
    description: "What the market builds in public, you run in private. AORBIT Frontier for regulated digital-asset operations — agentic AI inside your perimeter.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Industries", url: "/industries/banking" }, { name: "Digital Assets", url: "/industries/digital-assets" }],
  },
  "/industries/government": {
    title: "Sovereign AI for Government & Public Sector",
    description: "AORBIT inside national boundaries, under national control. Sovereign AI infrastructure for regulated public-sector deployments — no foreign cloud dependency.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Industries", url: "/industries/banking" }, { name: "Government", url: "/industries/government" }],
  },
  "/services/augmentation": {
    title: "Resource Augmentation — AI, Cloud, DevOps Specialists",
    description: "Access AI, Cloud, and DevOps practitioners who've delivered at banking scale. Not recruiters — engineers who understand regulated environments.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Services", url: "/services/augmentation" }, { name: "Resource Augmentation", url: "/services/augmentation" }],
  },
  "/services/training": {
    title: "Corporate Training — Production-Grade Enterprise AI",
    description: "Training designed by practitioners who build enterprise AI. Your team learns from engineers who have deployed private LLMs in production.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Services", url: "/services/augmentation" }, { name: "Corporate Training", url: "/services/training" }],
  },
  "/services/research": {
    title: "Applied Research — Research That Ships to Production",
    description: "Applied R&D bridging academic AI and production deployment. Every research initiative at Doblier maps to a production deployment path.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Services", url: "/services/augmentation" }, { name: "Applied Research", url: "/services/research" }],
  },
  "/company/about": {
    title: "About Doblier — The AI Infrastructure Company",
    description: "Founded in 2019. Headquartered in California. Operating globally. We build the AI infrastructure enterprises trust — production-grade, banking-scale.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Company", url: "/company/about" }, { name: "About", url: "/company/about" }],
  },
  "/company/careers": {
    title: "Careers at Doblier — Build the AI Infrastructure the World Trusts",
    description: "Build production AI systems that run inside the world's banks. Real architecture, real scale. Senior engineering, security, and product roles.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Company", url: "/company/about" }, { name: "Careers", url: "/company/careers" }],
  },
  "/talk-to-an-architect": {
    title: "Talk to an Architect — Doblier",
    description: "A conversation with someone who has deployed private AI inside banks. Not a sales pitch. Typical response within 1 business day.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Contact", url: "/contact/architect" }, { name: "Talk to an Architect", url: "/contact/architect" }],
  },
  "/contact/architect": {
    title: "Talk to an Architect — Doblier",
    description: "A conversation with someone who has deployed private AI inside banks. Not a sales pitch. Typical response within 1 business day.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Contact", url: "/contact/architect" }, { name: "Talk to an Architect", url: "/contact/architect" }],
  },
  "/contact/demo": {
    title: "See AORBIT in Action — 45-Minute Walkthrough",
    description: "Live AORBIT walkthrough with an architect. Not a recorded webinar. We map AORBIT to your infrastructure and show what production private AI looks like.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Contact", url: "/contact/architect" }, { name: "See AORBIT in Action", url: "/contact/demo" }],
  },
  "/resources/blog": {
    title: "Doblier Insights — Coming Soon",
    description: "Architecture, private AI, and enterprise intelligence. Field notes from production deployments. First posts publish within 2 weeks of launch.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Resources", url: "/resources/whitepapers" }, { name: "Blog", url: "/resources/blog" }],
  },
  "/resources/whitepapers": {
    title: "Whitepapers & Research — Doblier",
    description: "In-depth analysis on enterprise AI architecture, private deployment, and the challenges that matter in production. The Architecture Gap and more.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Resources", url: "/resources/whitepapers" }, { name: "Whitepapers", url: "/resources/whitepapers" }],
  },
  "/privacy": {
    title: "Privacy Policy — Doblier",
    description: "How Doblier collects, uses, and protects your information when you visit doblier.io or engage our team. Written in plain language.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Legal", url: "/privacy" }, { name: "Privacy Policy", url: "/privacy" }],
    noindex: false,
  },
  "/terms": {
    title: "Terms of Use — Doblier",
    description: "The rules of engagement for visiting doblier.io. Separate commercial agreements govern AORBIT deployments and services engagements.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Legal", url: "/privacy" }, { name: "Terms of Use", url: "/terms" }],
  },
  "/cookies": {
    title: "Cookie Policy — Doblier",
    description: "How Doblier uses cookies on doblier.io. Manage your preferences. 12-month consent storage.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Legal", url: "/privacy" }, { name: "Cookie Policy", url: "/cookies" }],
  },
  "/accessibility": {
    title: "Accessibility Statement — Doblier",
    description: "Accessibility is part of architecture, not a checklist tacked on at the end. How doblier.io supports assistive technology users.",
    breadcrumb: [{ name: "Home", url: "/" }, { name: "Legal", url: "/privacy" }, { name: "Accessibility", url: "/accessibility" }],
  },
};

function setMeta(id, content) {
  const el = document.getElementById(id);
  if (!el) return;
  if (el.tagName === "TITLE") el.textContent = content;
  else if (el.tagName === "LINK") el.setAttribute("href", content);
  else el.setAttribute("content", content);
}

function setHeadAttr(selector, attr, value) {
  const el = document.querySelector(selector);
  if (el) el.setAttribute(attr, value);
}

function injectPageSchema(route, cfg) {
  const slot = document.getElementById("ld-page");
  if (!slot) return;
  const url = SITE_BASE + route;
  const schemas = [];

  // BreadcrumbList — on every non-home page
  if (cfg.breadcrumb && cfg.breadcrumb.length > 1) {
    schemas.push({
      "@context": "https://schema.org",
      "@type": "BreadcrumbList",
      itemListElement: cfg.breadcrumb.map((b, i) => ({
        "@type": "ListItem",
        position: i + 1,
        name: b.name,
        item: SITE_BASE + b.url,
      })),
    });
  }

  // SoftwareApplication — on AORBIT pages
  if (cfg.productSchema) {
    schemas.push({
      "@context": "https://schema.org",
      "@type": "SoftwareApplication",
      name: "AORBIT",
      alternateName: "Autonomous Enterprise Intelligence Suite",
      applicationCategory: "BusinessApplication",
      applicationSubCategory: "Enterprise AI Infrastructure",
      operatingSystem: "Linux",
      url: SITE_BASE + "/aorbit",
      description: "AORBIT is the autonomous enterprise intelligence suite from Doblier. Three layers — Foundation, Intelligence, Frontier — running inside your perimeter with zero data exfiltration.",
      offers: { "@type": "Offer", availability: "https://schema.org/InStock", priceCurrency: "USD" },
      publisher: { "@type": "Organization", name: "Doblier Inc.", url: SITE_BASE },
    });
  }

  // WebPage — generic fallback for every route
  schemas.push({
    "@context": "https://schema.org",
    "@type": "WebPage",
    url,
    name: cfg.title,
    description: cfg.description,
    isPartOf: { "@type": "WebSite", url: SITE_BASE, name: SITE_NAME },
    inLanguage: "en",
  });

  slot.textContent = JSON.stringify(schemas.length === 1 ? schemas[0] : schemas);
}

function SEOHead({ route }) {
  React.useEffect(() => {
    // Remove SEO-fallback content once React is in charge — keeps the DOM
    // clean for visitors but lets crawlers see the directory on first paint.
    const fb = document.getElementById("seo-fallback");
    if (fb && fb.parentNode) fb.parentNode.removeChild(fb);

    // Resolve config: exact match, then trimmed-trailing-slash, then fallback.
    const clean = (route || "/").replace(/\/+$/, "") || "/";
    const cfg = ROUTE_SEO[clean] || ROUTE_SEO["/"];

    const fullTitle = cfg.appendBrand === false ? cfg.title : `${cfg.title} | ${SITE_NAME}`;
    const url = SITE_BASE + clean;

    // Title + description
    document.title = fullTitle;
    setHeadAttr('meta[name="description"]', "content", cfg.description);

    // Canonical + robots
    setMeta("meta-canonical", url);
    setHeadAttr('meta[name="robots"]', "content",
      cfg.noindex ? "noindex, nofollow" : "index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1");

    // Open Graph
    setMeta("meta-og-title", fullTitle);
    setMeta("meta-og-description", cfg.description);
    setMeta("meta-og-url", url);
    setMeta("meta-og-image", cfg.ogImage || DEFAULT_OG);
    setMeta("meta-og-type", cfg.ogType || "website");

    // Twitter
    setMeta("meta-tw-title", fullTitle);
    setMeta("meta-tw-description", cfg.description);
    setMeta("meta-tw-image", cfg.ogImage || DEFAULT_OG);

    // Per-page JSON-LD
    injectPageSchema(clean, cfg);
  }, [route]);

  return null;
}

window.SEOHead = SEOHead;
/* Expose the route config so Breadcrumbs (and any future consumer) can read it. */
window.__getRouteSEO = function (route) {
  const clean = (route || "/").replace(/\/+$/, "") || "/";
  return ROUTE_SEO[clean] || null;
};
