/* global React */
// ============================================================
// SEO Head Manager — per-route meta + JSON-LD
// ============================================================
const { useEffect: useEffectS } = React;

const SITE = "https://sinuxgroup.com";

// Route → SEO metadata
window.SEO_BY_ROUTE = {
  "/": {
    title: "Sinux Group — Building the Future Through Scalable Ventures",
    description: "Sinux Group is a diversified Malaysian holding company operating across technology consulting, digital growth, and strategic investment. Building, scaling, and supporting high-growth ventures globally.",
    keywords: "Sinux Group, technology consulting, digital growth, holding company, Malaysia, AI consulting, venture capital, business growth",
    canonical: "/",
    ogImage: "/assets/og-group.png",
    schema: "organization",
  },
  "/consulting": {
    title: "Sinux Consulting — Technology Consulting & Digital Growth Solutions | Malaysia",
    description: "End-to-end technology consulting and AI-powered digital growth solutions. Subscription websites, ReviewFlow QR review management, SinuxMod for Discord communities, and full-scale platform delivery. Trusted by businesses worldwide.",
    keywords: "Sinux Consulting, technology consulting, digital growth, AI consulting, website subscription, ReviewFlow, SinuxMod, Switchboard, Malaysia tech consulting, AI agent marketplace",
    canonical: "/consulting",
    ogImage: "/assets/og-consulting.png",
    schema: "localbusiness",
  },
  "/consulting/digital-growth/websites": {
    title: "Website Subscription & Signature Build Services | Sinux Consulting",
    description: "Subscription websites from $299/month with monthly SEO, hosting, and unlimited updates. Or commission a Signature Build — a fully custom website project with ongoing care plan. Built for growing businesses.",
    keywords: "website subscription, SEO website, Malaysia website design, custom website, signature build, local SEO, GEO optimization, AI search optimization, monthly website plan",
    canonical: "/consulting/digital-growth/websites",
    ogImage: "/assets/og-websites.png",
    schema: "service",
    serviceName: "Website Subscription & Signature Build",
    serviceType: "Web Development & SEO",
  },
  "/consulting/tech-consulting": {
    title: "Technology Consulting Services | Advisory, MVP, Full Suite Execution | Sinux",
    description: "3-tier technology consulting model — Advisory & Planning, MVP/POC Development, Full Suite Execution. AI-ready product builds for founders, startups, and enterprises. From concept to scaled deployment.",
    keywords: "technology consulting, MVP development, software architecture, AI consulting, BRD FSD, MVP POC, tech advisory, system design, enterprise software, Sinux",
    canonical: "/consulting/tech-consulting",
    ogImage: "/assets/og-tech.png",
    schema: "service",
    serviceName: "Technology Consulting",
    serviceType: "Software Consulting & Development",
  },
  "/consulting/contact": {
    title: "Contact Sinux Consulting — Start Your Project",
    description: "Get in touch with Sinux Consulting for technology consulting, digital growth, websites, or AI-powered product builds. We respond within one business day.",
    canonical: "/consulting/contact",
    schema: "contact",
  },
  "/capital": {
    title: "Sinux Capital — Strategic Investments & Venture Capital",
    description: "Sinux Capital manages investment portfolios and strategic venture activities — from active market participation to business acquisition. Patient capital. Concentrated conviction. Built for the long horizon.",
    keywords: "Sinux Capital, venture capital, investments, business acquisition, strategic partnerships, growth capital, Malaysia VC, long-term investing",
    canonical: "/capital",
    ogImage: "/assets/og-capital.png",
    schema: "organization",
  },
  "/capital/contact": {
    title: "Contact Sinux Capital — Private Inquiries",
    description: "Contact Sinux Capital directly for partnership inquiries, co-investment opportunities, or business acquisition discussions. Private engagement worldwide.",
    canonical: "/capital/contact",
    schema: "contact",
  },
  "/contact": {
    title: "Contact Sinux Group — Get in Touch",
    description: "Contact the Sinux Group leadership for general inquiries, partnerships, investments, or press. Based in Kuala Lumpur, Malaysia — serving clients globally.",
    canonical: "/contact",
    schema: "contact",
  },
  "/reviewflow": {
    title: "ReviewFlow — QR-Powered Review Management for Local Businesses",
    description: "Smart QR-powered review management for local businesses. Positive customer reviews are guided to Google. Critical feedback stays private for internal action. Used by clinics, restaurants, salons, and service businesses across Malaysia.",
    keywords: "ReviewFlow, QR review management, Google reviews, reputation management, review automation, local business reviews, Malaysia SaaS, customer feedback tool",
    canonical: "/reviewflow",
    ogImage: "/assets/og-reviewflow.png",
    schema: "product",
    productName: "ReviewFlow",
    productCategory: "Reputation Management Software",
  },
  "/sinuxmod": {
    title: "SinuxMod — AI Discord Ticket Moderation for Paid Communities",
    description: "AI-powered Discord bot that reads ticket channels, answers from your knowledge base, escalates edge cases, and closes resolved tickets — autonomously. 24/7 moderation for paid trading, gaming, and creator communities.",
    keywords: "SinuxMod, Discord bot, AI moderation, ticket bot, Discord community management, AI customer support, paid community automation",
    canonical: "/sinuxmod",
    ogImage: "/assets/og-sinuxmod.png",
    schema: "product",
    productName: "SinuxMod",
    productCategory: "AI Discord Moderation Bot",
  },
  "/switchboard": {
    title: "Switchboard — AI Business Manager for Service Operators",
    description: "Captures every lead, responds across email, SMS, and call, books appointments around your real calendar, remembers every customer. Built for landscapers, cleaners, trades, and home services.",
    keywords: "Switchboard, AI receptionist, lead response, service business CRM, AI scheduling, landscaping software, home services automation, AI business manager",
    canonical: "/switchboard",
    ogImage: "/assets/og-switchboard.png",
    schema: "product",
    productName: "Switchboard",
    productCategory: "AI Business Operations Platform",
  },
  "/privacy": {
    title: "Privacy Policy | Sinux Consulting",
    description: "Sinux Consulting privacy policy — how we collect, use, and protect your data when you use our website or services.",
    canonical: "/privacy",
    schema: "webpage",
  },
  "/terms": {
    title: "Terms & Conditions | Sinux Consulting",
    description: "Sinux Consulting terms and conditions — governing the supply of services, digital deliverables, and maintenance agreements.",
    canonical: "/terms",
    schema: "webpage",
  },
};

// ============================================================
// Apply SEO for current route
// ============================================================
function applySEO(route) {
  const meta = window.SEO_BY_ROUTE[route] || window.SEO_BY_ROUTE["/"];
  const canonical = SITE + (meta.canonical || route);
  const ogImage = meta.ogImage ? SITE + meta.ogImage : SITE + "/assets/og-group.png";

  // Title
  document.title = meta.title;

  // Helper to set/update meta tag
  const setMeta = (selector, content) => {
    let el = document.head.querySelector(selector);
    if (!el) {
      el = document.createElement("meta");
      const attrMatch = selector.match(/\[(\w+)="([^"]+)"\]/);
      if (attrMatch) el.setAttribute(attrMatch[1], attrMatch[2]);
      document.head.appendChild(el);
    }
    el.setAttribute("content", content);
  };

  setMeta('meta[name="description"]', meta.description);
  if (meta.keywords) setMeta('meta[name="keywords"]', meta.keywords);

  // Open Graph
  setMeta('meta[property="og:type"]', "website");
  setMeta('meta[property="og:url"]', canonical);
  setMeta('meta[property="og:title"]', meta.title);
  setMeta('meta[property="og:description"]', meta.description);
  setMeta('meta[property="og:image"]', ogImage);
  setMeta('meta[property="og:site_name"]', "Sinux Group");
  setMeta('meta[property="og:locale"]', "en_US");

  // Twitter
  setMeta('meta[name="twitter:card"]', "summary_large_image");
  setMeta('meta[name="twitter:title"]', meta.title);
  setMeta('meta[name="twitter:description"]', meta.description);
  setMeta('meta[name="twitter:image"]', ogImage);

  // Canonical
  let canon = document.head.querySelector("link[rel='canonical']");
  if (!canon) {
    canon = document.createElement("link");
    canon.rel = "canonical";
    document.head.appendChild(canon);
  }
  canon.href = canonical;

  // Robots
  setMeta('meta[name="robots"]', "index, follow, max-image-preview:large");
  setMeta('meta[name="googlebot"]', "index, follow");

  // Inject structured data
  injectStructuredData(route, meta);
}

// ============================================================
// JSON-LD Structured Data
// ============================================================
function injectStructuredData(route, meta) {
  // Remove old dynamic schemas
  document.querySelectorAll("script[data-seo-jsonld]").forEach((el) => el.remove());

  const graph = [];

  // Always include the parent Organization
  graph.push(orgSchema());

  // Always include WebSite with SearchAction
  graph.push(websiteSchema());

  // BreadcrumbList per route
  graph.push(breadcrumbSchema(route));

  // Per-route specifics
  if (meta.schema === "localbusiness") {
    graph.push(localBusinessSchema());
  }
  if (meta.schema === "product") {
    graph.push(productSchema(meta));
  }
  if (meta.schema === "service") {
    graph.push(serviceSchema(meta));
  }

  // FAQ-rich pages
  const faq = faqSchemaForRoute(route);
  if (faq) graph.push(faq);

  // Inject
  const tag = document.createElement("script");
  tag.type = "application/ld+json";
  tag.setAttribute("data-seo-jsonld", "true");
  tag.textContent = JSON.stringify({ "@context": "https://schema.org", "@graph": graph });
  document.head.appendChild(tag);
}

function orgSchema() {
  return {
    "@type": "Organization",
    "@id": SITE + "/#org",
    name: "Sinux Group",
    alternateName: ["Sinux", "Sinux Industries"],
    url: SITE,
    logo: SITE + "/assets/logo-group.png",
    description: "Sinux Group is a diversified Malaysian holding company operating across technology consulting, digital growth, and strategic investment.",
    foundingDate: "2025",
    address: {
      "@type": "PostalAddress",
      addressLocality: "Kuala Lumpur",
      addressCountry: "MY",
    },
    contactPoint: [
      {
        "@type": "ContactPoint",
        telephone: "+60-12-618-7256",
        contactType: "customer service",
        areaServed: ["MY", "US"],
        availableLanguage: ["English", "Malay"],
        email: "info@sinuxgroup.com",
      },
      {
        "@type": "ContactPoint",
        telephone: "+1-229-374-6725",
        contactType: "sales",
        areaServed: "US",
        availableLanguage: "English",
      },
    ],
    sameAs: [
      "https://www.linkedin.com/company/sinuxindustries/",
      "https://www.instagram.com/sinuxconsulting/",
    ],
    subOrganization: [
      {
        "@type": "Organization",
        "@id": SITE + "/consulting#org",
        name: "Sinux Consulting",
        url: SITE + "/consulting",
        description: "Technology consulting and digital growth solutions powered by AI.",
        identifier: { "@type": "PropertyValue", propertyID: "SSM", value: "202503207573" },
      },
      {
        "@type": "Organization",
        "@id": SITE + "/capital#org",
        name: "Sinux Capital",
        url: SITE + "/capital",
        description: "Strategic investments and venture capital.",
      },
    ],
  };
}

function websiteSchema() {
  return {
    "@type": "WebSite",
    "@id": SITE + "/#website",
    url: SITE,
    name: "Sinux Group",
    publisher: { "@id": SITE + "/#org" },
    inLanguage: "en",
    potentialAction: {
      "@type": "SearchAction",
      target: SITE + "/?q={search_term_string}",
      "query-input": "required name=search_term_string",
    },
  };
}

function localBusinessSchema() {
  return {
    "@type": "ProfessionalService",
    "@id": SITE + "/consulting#localbusiness",
    name: "Sinux Consulting",
    image: SITE + "/assets/logo-consulting.png",
    url: SITE + "/consulting",
    telephone: "+60-12-618-7256",
    email: "info@sinuxconsulting.com",
    priceRange: "$$",
    address: {
      "@type": "PostalAddress",
      addressLocality: "Kuala Lumpur",
      addressCountry: "MY",
    },
    geo: {
      "@type": "GeoCoordinates",
      latitude: 3.1390,
      longitude: 101.6869,
    },
    openingHoursSpecification: [
      {
        "@type": "OpeningHoursSpecification",
        dayOfWeek: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
        opens: "10:00",
        closes: "21:00",
      },
    ],
    areaServed: [
      { "@type": "Country", name: "Malaysia" },
      { "@type": "Country", name: "United States" },
      { "@type": "Place", name: "Global" },
    ],
    identifier: { "@type": "PropertyValue", propertyID: "SSM", value: "202503207573" },
    sameAs: [
      "https://www.linkedin.com/company/sinuxindustries/",
      "https://www.instagram.com/sinuxconsulting/",
    ],
    hasOfferCatalog: {
      "@type": "OfferCatalog",
      name: "Sinux Consulting Services",
      itemListElement: [
        {
          "@type": "OfferCatalog",
          name: "Digital Growth",
          itemListElement: [
            { "@type": "Offer", itemOffered: { "@type": "Service", name: "Website Subscription", url: SITE + "/consulting/digital-growth/websites" } },
            { "@type": "Offer", itemOffered: { "@type": "Service", name: "Signature Website Build", url: SITE + "/consulting/digital-growth/websites" } },
            { "@type": "Offer", itemOffered: { "@type": "SoftwareApplication", name: "ReviewFlow", url: SITE + "/reviewflow" } },
            { "@type": "Offer", itemOffered: { "@type": "SoftwareApplication", name: "SinuxMod", url: SITE + "/sinuxmod" } },
            { "@type": "Offer", itemOffered: { "@type": "SoftwareApplication", name: "Switchboard", url: SITE + "/switchboard" } },
          ],
        },
        {
          "@type": "OfferCatalog",
          name: "Technology Consulting",
          itemListElement: [
            { "@type": "Offer", itemOffered: { "@type": "Service", name: "Advisory & Planning" } },
            { "@type": "Offer", itemOffered: { "@type": "Service", name: "MVP / POC Development" } },
            { "@type": "Offer", itemOffered: { "@type": "Service", name: "Full Suite Execution" } },
          ],
        },
      ],
    },
  };
}

function serviceSchema(meta) {
  return {
    "@type": "Service",
    "@id": SITE + meta.canonical + "#service",
    serviceType: meta.serviceType,
    name: meta.serviceName,
    description: meta.description,
    provider: { "@id": SITE + "/consulting#localbusiness" },
    url: SITE + meta.canonical,
    areaServed: [{ "@type": "Country", name: "Malaysia" }, { "@type": "Country", name: "United States" }],
  };
}

function productSchema(meta) {
  return {
    "@type": "SoftwareApplication",
    "@id": SITE + meta.canonical + "#product",
    name: meta.productName,
    applicationCategory: meta.productCategory,
    operatingSystem: "Web",
    description: meta.description,
    url: SITE + meta.canonical,
    publisher: { "@id": SITE + "/consulting#localbusiness" },
    offers: {
      "@type": "Offer",
      priceSpecification: {
        "@type": "PriceSpecification",
        priceCurrency: meta.productName === "SinuxMod" ? "USD" : "MYR",
        price: meta.productName === "SinuxMod" ? "100" : meta.productName === "ReviewFlow" ? "999" : "0",
        valueAddedTaxIncluded: false,
      },
      availability: meta.productName === "Switchboard" ? "https://schema.org/PreOrder" : "https://schema.org/InStock",
    },
  };
}

function breadcrumbSchema(route) {
  const parts = route.split("/").filter(Boolean);
  const items = [{ "@type": "ListItem", position: 1, name: "Home", item: SITE + "/" }];
  let acc = "";
  parts.forEach((p, i) => {
    acc += "/" + p;
    const label = p
      .replace(/-/g, " ")
      .replace(/\b\w/g, (c) => c.toUpperCase());
    items.push({ "@type": "ListItem", position: i + 2, name: label, item: SITE + acc });
  });
  return { "@type": "BreadcrumbList", itemListElement: items };
}

function faqSchemaForRoute(route) {
  const faqs = {
    "/consulting/digital-growth/websites": [
      ["How long does it take to launch?", "2–3 weeks after design approval and content submission."],
      ["What's included in unlimited updates?", "Text, images, pages, pricing changes — anything content-related. If it lives on your site, we'll update it."],
      ["What's the difference between Basic and Pro Growth?", "Pro adds active SEO management, Google Business Profile optimization, AI search optimization (GEO), and 2 blog posts/month."],
      ["What is the Signature Build + Care Plan?", "A bespoke, project-scoped website engagement with a fixed quote — ideal for businesses that want a completely custom build rather than a subscription template."],
      ["Do I need to sign a contract?", "Pro subscriptions are on a 12-month commitment. Month-to-month available at a higher rate."],
      ["Can I upgrade?", "Yes, anytime — contact us and we'll migrate you with zero downtime."],
    ],
    "/consulting/tech-consulting": [
      ["What exactly does Sinux Technology Consulting include?", "Our consulting covers the entire product journey — from defining your business goals to delivering a market-ready solution. Strategy, architecture, build, deployment and handover."],
      ["How is this different from hiring a development agency?", "Traditional development agencies jump straight into coding. At Sinux, we start with consulting — aligning strategy, business goals, and tech roadmap before a single line of code is written."],
      ["Do I need to have a technical background to work with you?", "No. Our consultants translate complex technology into simple, actionable insights for founders, investors, and business teams."],
      ["Can I start small, like with an MVP or just the advisory phase?", "Yes. Many clients begin with Tier 1 (Advisory & Planning) or Tier 2 (MVP Development) before moving into full execution."],
    ],
    "/reviewflow": [
      ["Does ReviewFlow remove or block bad reviews?", "No. ReviewFlow does not remove or hide any reviews. It gives you a structured way to collect private feedback first — so you can resolve issues with the customer directly before they decide to post publicly. Customers are always free to leave any review they want on Google."],
      ["Can customers still leave bad Google reviews?", "Yes, always. ReviewFlow doesn't restrict anyone. It simply offers a better first step — and businesses that respond to private feedback well typically see fewer public negative reviews over time."],
      ["Do I need a website to use ReviewFlow?", "No. ReviewFlow works as a standalone QR / review link. It pairs well with a Sinux Consulting website if you want both, but it's not required."],
      ["Can I use it for multiple branches?", "Yes. You can create branch-specific QRs and links, and the dashboard will show you which location is generating the most feedback."],
      ["Who owns the data?", "You do. All reviews, customer feedback, and analytics in your dashboard are yours. Sinux Consulting hosts the platform and provides support, but the data belongs to your business."],
    ],
    "/sinuxmod": [
      ["Does it replace my mod team?", "No. SinuxMod handles the repetitive 80% — the same 5 questions you've answered a hundred times. Your mods handle the 20% that actually needs them."],
      ["Which AI does it use?", "Claude Haiku for fast classification and responses. We chose it for speed (< 2s avg response), accuracy, and cost."],
      ["Can it learn from corrections?", "Yes. When a mod corrects a bot answer, you can click 'Add to KB' and the corrected answer becomes the new source of truth — immediately, no redeploy needed."],
      ["How does pricing scale?", "$100 per 10,000 community members per month. Linear and predictable. Above 100k members we move to custom pricing."],
      ["Is my server's data private?", "Yes. Your KB, rules, and ticket history are isolated per server. We do not train shared models on your data."],
    ],
  };
  const list = faqs[route];
  if (!list) return null;
  return {
    "@type": "FAQPage",
    mainEntity: list.map(([q, a]) => ({
      "@type": "Question",
      name: q,
      acceptedAnswer: { "@type": "Answer", text: a },
    })),
  };
}

window.applySEO = applySEO;
