import { Helmet } from "react-helmet-async";
import { useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { resolveGermanHreflangPath, resolveHreflangPair } from "@/lib/hreflang";

const PRODUCTION_DOMAIN = "https://sutekistudios.com";
const DEFAULT_OG_IMAGE = "/assets/photos/team-studio.jpg";

// Admin/protected paths that should NOT be indexed
const NOINDEX_PATHS = [
  "/auth",
  "/login",
  "/dashboard",
  "/admin",
];

// Legacy locale prefixes that should NEVER appear in canonical/hreflang
// These are deprecated paths that redirect to homepage
const LEGACY_LOCALE_PREFIXES = [
  "/ar", "/ar-sa", "/ua", "/uk", "/ru",
  "/en-gb", "/en-us", "/sv-se",
  "/de", "/fr", "/es",
];

function shouldIndex(pathname: string): boolean {
  return !NOINDEX_PATHS.some(path => pathname.startsWith(path));
}

/**
 * Check if a path starts with a legacy locale prefix.
 * These paths should never be in canonical URLs.
 */
function isLegacyLocalePath(pathname: string): boolean {
  return LEGACY_LOCALE_PREFIXES.some(prefix => 
    pathname === prefix || pathname.startsWith(prefix + "/")
  );
}

interface HreflangOverride {
  sv: string;
  en: string;
  xDefault: string;
}

interface SEOHeadProps {
  title: string;
  description: string;
  /** Optional OG image path (relative to domain, e.g., "/og/ai.jpg") */
  ogImage?: string;
  /** Alt text for OG image (accessibility & SEO) */
  ogImageAlt?: string;
  /** OG image width in pixels */
  ogImageWidth?: number;
  /** OG image height in pixels */
  ogImageHeight?: number;
  /** OG locale (e.g., "sv_SE", "en_US") */
  ogLocale?: string;
  /** Override OG title (defaults to page title) */
  ogTitle?: string;
  /** Override OG description (defaults to page description) */
  ogDescription?: string;
  /** Override Twitter title (defaults to ogTitle or page title) */
  twitterTitle?: string;
  /** Override Twitter description (defaults to ogDescription or page description) */
  twitterDescription?: string;
  /** Override noIndex for specific pages */
  noIndex?: boolean;
  /** Override hreflang URLs for pages with separate language versions */
  hreflangOverrides?: HreflangOverride;
  /** Force html lang attribute (overrides i18n detection) */
  forceLang?: "sv" | "en";
  /** Open Graph type (defaults to "website"). Use "article" for news/blog posts. */
  ogType?: "website" | "article";
}

/**
 * Unified SEO head component that renders exactly ONE of each required meta tag:
 * - <title>
 * - <meta name="description">
 * - <link rel="canonical">
 * - <meta property="og:*">
 * - <meta name="twitter:*">
 * - <meta name="robots">
 * 
 * This component should be used instead of separate Helmet + CanonicalTag calls
 * to prevent duplicate meta tags.
 */
export function SEOHead({ 
  title, 
  description, 
  ogImage, 
  ogImageAlt,
  ogImageWidth,
  ogImageHeight,
  ogLocale,
  ogTitle,
  ogDescription,
  twitterTitle,
  twitterDescription,
  noIndex,
  hreflangOverrides,
  forceLang,
  ogType,
}: SEOHeadProps) {
  const location = useLocation();
  const { i18n } = useTranslation();
  
  // Get current language for html lang attribute
  const currentLang = forceLang || (i18n.language === "sv" ? "sv" : "en");
  
  // Build canonical URL: production domain + current path
  // Ensure no trailing slash except for root
  let path = location.pathname === "/" ? "/" : location.pathname.replace(/\/$/, "");
  
  // SAFETY: Canonical must NEVER point to /solutions/* paths
  // These are legacy redirect paths - normalize to final URL
  if (path.startsWith("/solutions/")) {
    const legacyMappings: Record<string, string> = {
      "/solutions/vr": "/vr",
      "/solutions/ai": "/ai",
      "/solutions/hologram": "/hologram",
      "/solutions/holobox": "/holobox",
      "/solutions/holospin": "/holospin",
      "/solutions/holonet": "/holonet",
      "/solutions/invisible-screen": "/invisible-screen",
    };
    path = legacyMappings[path] || path.replace("/solutions/", "/");
    console.warn(`[SEOHead] Canonical normalized from legacy path: ${location.pathname} → ${path}`);
  }
  
  // SAFETY: Canonical must NEVER point to legacy locale paths
  // These should redirect immediately, but add protection in case SEOHead runs
  if (isLegacyLocalePath(path)) {
    path = "/";
    console.warn(`[SEOHead] Canonical normalized from legacy locale path: ${location.pathname} → /`);
  }
  
  const canonicalUrl = `${PRODUCTION_DOMAIN}${path}`;
  
  // Build hreflang URLs.
  // Emitted ONLY when a real Swedish/English equivalent exists — either passed
  // explicitly via hreflangOverrides or resolved from the central pair map.
  // Pages without a counterpart get no alternate links at all.
  const pair = hreflangOverrides
    ? { sv: hreflangOverrides.sv, en: hreflangOverrides.en }
    : resolveHreflangPair(path);
  const xDefaultPath = hreflangOverrides?.xDefault ?? pair?.sv;
  const hreflangSv = pair ? `${PRODUCTION_DOMAIN}${pair.sv}` : null;
  const hreflangEn = pair ? `${PRODUCTION_DOMAIN}${pair.en}` : null;
  const germanPath = resolveGermanHreflangPath(path);
  const hreflangDe = germanPath ? `${PRODUCTION_DOMAIN}${germanPath}` : null;
  const hreflangDefault = xDefaultPath ? `${PRODUCTION_DOMAIN}${xDefaultPath}` : null;

  
  // Determine if page should be indexed
  const isIndexable = !noIndex && shouldIndex(location.pathname);
  const robotsContent = isIndexable ? "index,follow" : "noindex,nofollow";
  
  // Build full OG image URL
  const ogImageUrl = ogImage 
    ? (ogImage.startsWith("http") ? ogImage : `${PRODUCTION_DOMAIN}${ogImage}`)
    : `${PRODUCTION_DOMAIN}${DEFAULT_OG_IMAGE}`;

  // Compute final OG/Twitter values with fallbacks
  const finalOgTitle = ogTitle || title;
  const finalOgDescription = ogDescription || description;
  const finalTwitterTitle = twitterTitle || finalOgTitle;
  const finalTwitterDescription = twitterDescription || finalOgDescription;

  return (
    <Helmet>
      {/* Dynamic HTML lang attribute */}
      <html lang={currentLang} />
      
      {/* Primary Meta Tags */}
      <title>{title}</title>
      <meta name="description" content={description} />
      
      {/* Canonical URL - self-referencing only, always sutekistudios.com */}
      <link rel="canonical" href={canonicalUrl} />
      
      {/*
        Reciprocal hreflang: emitted only when the page has a true equivalent in
        the other language (central map in src/lib/hreflang.ts).
        Swedish = sv-SE, international English = en, x-default = Swedish URL.
        A page without a counterpart gets no alternate links.
      */}
      {hreflangSv && <link rel="alternate" hrefLang="sv-SE" href={hreflangSv} />}
      {hreflangEn && <link rel="alternate" hrefLang="en" href={hreflangEn} />}
      {hreflangDe && <link rel="alternate" hrefLang="de" href={hreflangDe} />}
      {hreflangDefault && <link rel="alternate" hrefLang="x-default" href={hreflangDefault} />}

      
      {/* Robots directive */}
      <meta name="robots" content={robotsContent} />
      
      {/* Open Graph / Facebook */}
      <meta property="og:type" content={ogType || "website"} />
      <meta property="og:url" content={canonicalUrl} />
      <meta property="og:title" content={finalOgTitle} />
      <meta property="og:description" content={finalOgDescription} />
      <meta property="og:image" content={ogImageUrl} />
      <meta property="og:site_name" content="Suteki Studios" />
      {ogImageWidth && <meta property="og:image:width" content={String(ogImageWidth)} />}
      {ogImageHeight && <meta property="og:image:height" content={String(ogImageHeight)} />}
      {ogImageAlt && <meta property="og:image:alt" content={ogImageAlt} />}
      {ogLocale && <meta property="og:locale" content={ogLocale} />}
      
      {/* Twitter */}
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:url" content={canonicalUrl} />
      <meta name="twitter:title" content={finalTwitterTitle} />
      <meta name="twitter:description" content={finalTwitterDescription} />
      <meta name="twitter:image" content={ogImageUrl} />
      {ogImageAlt && <meta name="twitter:image:alt" content={ogImageAlt} />}
    </Helmet>
  );
}
