import { useEffect } from "react";
import { useLocation } from "react-router-dom";

/**
 * Development-only hook that asserts there are no duplicate SEO tags on each route change.
 * This helps catch issues where multiple components render the same meta tags.
 * 
 * Runs only in development mode (process.env.NODE_ENV !== "production").
 */
export function useSEODevAssertion() {
  const location = useLocation();

  useEffect(() => {
    // Only run in development
    if (import.meta.env.PROD) return;

    // Small delay to ensure DOM has updated after route change
    const timeoutId = setTimeout(() => {
      const report: string[] = [];
      let hasError = false;

      // Define tags to check
      const singleTags = [
        { selector: "title", name: "title" },
        { selector: 'meta[name="description"]', name: "description" },
        { selector: 'link[rel="canonical"]', name: "canonical" },
        { selector: 'meta[property="og:title"]', name: "og:title" },
        { selector: 'meta[property="og:description"]', name: "og:description" },
        { selector: 'meta[property="og:image"]', name: "og:image" },
        { selector: 'meta[name="twitter:title"]', name: "twitter:title" },
        { selector: 'meta[name="twitter:description"]', name: "twitter:description" },
        { selector: 'meta[name="twitter:image"]', name: "twitter:image" },
      ];

      singleTags.forEach(({ selector, name }) => {
        const elements = document.querySelectorAll(selector);
        if (elements.length > 1) {
          hasError = true;
          report.push(`❌ ${name}: ${elements.length} found (expected 1)`);
        } else if (elements.length === 1) {
          report.push(`✓ ${name}: 1`);
        } else {
          report.push(`⚠️ ${name}: 0 (missing)`);
        }
      });

      // Check for canonical pointing to /solutions/* (should never happen)
      const canonical = document.querySelector('link[rel="canonical"]') as HTMLLinkElement;
      if (canonical && canonical.href.includes("/solutions/")) {
        hasError = true;
        report.push(`❌ canonical contains /solutions/ path: ${canonical.href}`);
      }
      
      // Check for canonical pointing to legacy locale paths (should never happen)
      const legacyLocalePaths = ["/ar", "/ar-sa", "/ua", "/uk", "/ru", "/en-gb", "/en-us", "/sv-se", "/de", "/fr", "/es"];
      if (canonical) {
        for (const localePath of legacyLocalePaths) {
          if (canonical.href.includes(localePath + "/") || canonical.href.endsWith(localePath)) {
            hasError = true;
            report.push(`❌ canonical contains legacy locale path "${localePath}": ${canonical.href}`);
          }
        }
      }
      
      // Check for canonical pointing to suteki.se (should never happen - it redirects to sutekistudios.com)
      if (canonical && canonical.href.includes("suteki.se")) {
        hasError = true;
        report.push(`❌ canonical contains suteki.se (should be sutekistudios.com): ${canonical.href}`);
      }
      
      // Check hreflang tags - should have exactly sv, en, and x-default
      const hreflangSv = document.querySelectorAll('link[hreflang="sv"]');
      const hreflangEn = document.querySelectorAll('link[hreflang="en"]');
      const hreflangXDefault = document.querySelectorAll('link[hreflang="x-default"]');
      const hreflangAr = document.querySelectorAll('link[hreflang="ar"], link[hreflang="ar-sa"]');
      
      if (hreflangSv.length === 1) {
        report.push(`✓ hreflang="sv": 1`);
      } else if (hreflangSv.length > 1) {
        hasError = true;
        report.push(`❌ hreflang="sv": ${hreflangSv.length} found (expected 1)`);
      } else {
        report.push(`⚠️ hreflang="sv": 0 (missing)`);
      }
      
      if (hreflangEn.length === 1) {
        report.push(`✓ hreflang="en": 1`);
      } else if (hreflangEn.length > 1) {
        hasError = true;
        report.push(`❌ hreflang="en": ${hreflangEn.length} found (expected 1)`);
      } else {
        report.push(`⚠️ hreflang="en": 0 (missing)`);
      }
      
      if (hreflangXDefault.length === 1) {
        report.push(`✓ hreflang="x-default": 1`);
      } else if (hreflangXDefault.length > 1) {
        hasError = true;
        report.push(`❌ hreflang="x-default": ${hreflangXDefault.length} found (expected 1)`);
      } else {
        report.push(`⚠️ hreflang="x-default": 0 (missing)`);
      }
      
      // Arabic hreflang should NEVER exist
      if (hreflangAr.length > 0) {
        hasError = true;
        report.push(`❌ hreflang="ar" or "ar-sa": ${hreflangAr.length} found (should be 0 - Arabic is deprecated)`);
      }

      if (hasError) {
        console.error(
          `%c[SEO Assertion Failed] ${location.pathname}`,
          "color: red; font-weight: bold;",
          "\n" + report.join("\n")
        );
      } else {
        console.log(
          `%c[SEO Check Passed] ${location.pathname}`,
          "color: green;",
          "\n" + report.join("\n")
        );
      }
    }, 100);

    return () => clearTimeout(timeoutId);
  }, [location.pathname]);
}
