import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { runtimeConfigValue } from "../config/runtime-config";
import { pluginRegistry } from "../plugins/plugin-registry";

const DEFAULT_DESCRIPTION =
  "Free privacy-first tools for files, images, PDFs, text, and code. Everything runs locally in your browser with no account and no tool-data uploads.";

const PAGE_METADATA: Record<string, { title: string; description: string }> = {
  "/": {
    title: "Plimi - Free Private Browser Tools",
    description: DEFAULT_DESCRIPTION,
  },
  "/tools": {
    title: "Free Private Online Tools | Plimi",
    description:
      "Browse free browser-based utilities for images, PDFs, text, developer tasks, and privacy. Tools run locally without uploading your data.",
  },
  "/how-it-works": {
    title: "How Plimi Processes Files Locally",
    description:
      "Learn how Plimi uses browser APIs, Web Workers, WebAssembly, and local libraries to process files without uploading tool data.",
  },
  "/contribute": {
    title: "Contribute a Browser Tool to Plimi",
    description:
      "Learn how to build, test, and contribute a typed, privacy-first browser utility to the open-source Plimi tool collection.",
  },
  "/privacy": {
    title: "Privacy and Legal Information | Plimi",
    description:
      "Read how Plimi processes tool inputs locally, handles optional analytics, stores preferences, and protects your privacy.",
  },
};

function setNamedMeta(name: string, content: string) {
  let element = document.head.querySelector<HTMLMetaElement>(
    `meta[name="${name}"]`,
  );
  if (!element) {
    element = document.createElement("meta");
    element.name = name;
    document.head.appendChild(element);
  }
  element.content = content;
}

function setPropertyMeta(property: string, content: string) {
  let element = document.head.querySelector<HTMLMetaElement>(
    `meta[property="${property}"]`,
  );
  if (!element) {
    element = document.createElement("meta");
    element.setAttribute("property", property);
    document.head.appendChild(element);
  }
  element.content = content;
}

function setCanonical(href: string) {
  let element = document.head.querySelector<HTMLLinkElement>(
    'link[rel="canonical"]',
  );
  if (!element) {
    element = document.createElement("link");
    element.rel = "canonical";
    document.head.appendChild(element);
  }
  element.href = href;
}

export function SeoManager() {
  const { pathname } = useLocation();

  useEffect(() => {
    const siteUrl = runtimeConfigValue(
      "VITE_SITE_URL",
      window.location.origin,
    ).replace(/\/+$/, "");
    const toolId = pathname.startsWith("/tools/")
      ? pathname.slice("/tools/".length).replace(/\/+$/, "")
      : null;
    const plugin = toolId
      ? pluginRegistry.find((item) => item.manifest.id === toolId)
      : undefined;
    const page = PAGE_METADATA[pathname];
    const title = plugin
      ? `${plugin.manifest.name} - Free Private Online Tool | Plimi`
      : page?.title ?? "Page Not Found | Plimi";
    const description = plugin
      ? `${plugin.manifest.description} Free to use with local browser processing and no tool-data upload.`
      : page?.description ?? DEFAULT_DESCRIPTION;
    const canonicalPath = pathname === "/" ? "/tools" : pathname;
    const canonicalUrl = `${siteUrl}${canonicalPath}`;
    const isNotFound = !plugin && !page;

    document.title = title;
    setNamedMeta("description", description);
    setNamedMeta(
      "robots",
      isNotFound ? "noindex, nofollow" : "index, follow",
    );
    setNamedMeta("twitter:card", "summary");
    setNamedMeta("twitter:title", title);
    setNamedMeta("twitter:description", description);
    setPropertyMeta("og:type", "website");
    setPropertyMeta("og:site_name", "Plimi");
    setPropertyMeta("og:locale", "en_US");
    setPropertyMeta("og:title", title);
    setPropertyMeta("og:description", description);
    setPropertyMeta("og:url", canonicalUrl);
    setCanonical(canonicalUrl);

    document.head
      .querySelectorAll('script[type="application/ld+json"][data-plimi-seo]')
      .forEach((element) => element.remove());

    if (isNotFound) return;

    let structuredData;
    if (plugin) {
      structuredData = {
          "@context": "https://schema.org",
          "@type": "WebApplication",
          name: plugin.manifest.name,
          description: plugin.manifest.description,
          url: canonicalUrl,
          applicationCategory: `${plugin.manifest.category} utility`,
          applicationSubCategory: plugin.manifest.tags?.join(", "),
          browserRequirements: "Requires a modern web browser",
          operatingSystem: "Any",
          isAccessibleForFree: true,
          offers: {
            "@type": "Offer",
            price: "0",
            priceCurrency: "USD",
          },
          featureList: [
            "Runs locally in the browser",
            "No account required",
            "No tool-data upload",
            ...(plugin.manifest.offlineReady ? ["Offline-ready"] : []),
          ],
          publisher: {
            "@type": "Organization",
            name: "Plimi",
            url: `${siteUrl}/tools`,
          },
        };
    } else if (pathname === "/" || pathname === "/tools") {
      structuredData = {
          "@context": "https://schema.org",
          "@type": "ItemList",
          name: "Plimi private browser tools",
          url: `${siteUrl}/tools`,
          description,
          numberOfItems: pluginRegistry.length,
          itemListElement: pluginRegistry.map((item, index) => ({
            "@type": "ListItem",
            position: index + 1,
            url: `${siteUrl}/tools/${item.manifest.id}`,
            name: item.manifest.name,
          })),
        };
    } else {
      structuredData = {
        "@context": "https://schema.org",
        "@type": "WebPage",
        name: title,
        url: canonicalUrl,
        description,
        isPartOf: {
          "@type": "WebSite",
          name: "Plimi",
          url: `${siteUrl}/tools`,
        },
      };
    }

    const script = document.createElement("script");
    script.type = "application/ld+json";
    script.dataset.plimiSeo = "";
    script.text = JSON.stringify(structuredData);
    document.head.appendChild(script);
  }, [pathname]);

  return null;
}
