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

interface SEOProps {
  title?: string
  description?: string
  keywords?: string
  image?: string
  imageAlt?: string
  path?: string
  type?: "website" | "article" | "product"
  article?: {
    publishedAt?: string
    modifiedAt?: string
    author?: string
    section?: string
    tags?: string[]
  }
  noindex?: boolean
}

const DEFAULT_TITLE = "Subscription Hero | Buy Premium Subscriptions Up to 96% Off"
const DEFAULT_DESC = "Buy premium subscriptions — Netflix, Spotify, ChatGPT+, Canva Pro & more. Instant delivery. 24H money-back guarantee."
const DEFAULT_KEYWORDS = "buy ChatGPT Plus, Canva Pro subscription, Netflix Premium cheap, Spotify Premium account, premium subscriptions online, software activation keys, AI tools subscriptions, digital products marketplace, cheap premium accounts, VPN subscriptions"
const DEFAULT_IMAGE_ALT = "Subscription Hero - Premium digital subscriptions marketplace with up to 96% off"
const SITE_URL = "https://subscriptionhero.pro"
const OG_IMAGE = "/hero-bg.jpg"

// Language/region variants for hreflang
const HREFLANG_VARIANTS = [
  { lang: "en-us", region: "US" },
  { lang: "en-gb", region: "GB" },
  { lang: "en-in", region: "IN" },
  { lang: "en-ca", region: "CA" },
  { lang: "en-au", region: "AU" },
  { lang: "en-de", region: "DE" },
  { lang: "en-ae", region: "AE" },
]

export function SEO({
  title = DEFAULT_TITLE,
  description = DEFAULT_DESC,
  keywords = DEFAULT_KEYWORDS,
  image = OG_IMAGE,
  imageAlt = DEFAULT_IMAGE_ALT,
  path = "",
  type = "website",
  article,
  noindex = false,
}: SEOProps) {
  const location = useLocation()
  const fullTitle = title.includes("Subscription Hero") ? title : `${title} | Subscription Hero`
  const url = `${SITE_URL}${path || location.pathname}`

  useEffect(() => {
    // Update title
    document.title = fullTitle

    // Helper to update or create meta tag
    const setMeta = (name: string, content: string, attr: "name" | "property" = "name") => {
      let tag = document.querySelector(`meta[${attr}="${name}"]`)
      if (!tag) {
        tag = document.createElement("meta")
        tag.setAttribute(attr, name)
        document.head.appendChild(tag)
      }
      tag.setAttribute("content", content)
    }

    // ===== BASIC META TAGS =====
    setMeta("description", description)
    setMeta("keywords", keywords)
    setMeta("author", "Subscription Hero")
    setMeta("robots", noindex ? "noindex, nofollow" : "index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1")
    setMeta("googlebot", noindex ? "noindex, nofollow" : "index, follow")
    setMeta("bingbot", noindex ? "noindex, nofollow" : "index, follow")

    // ===== CANONICAL URL =====
    let canonical = document.querySelector('link[rel="canonical"]') as HTMLLinkElement | null
    if (!canonical) {
      canonical = document.createElement("link")
      canonical.rel = "canonical"
      document.head.appendChild(canonical)
    }
    canonical.href = url

    // ===== HREFLANG TAGS =====
    // Remove old hreflang tags first
    document.querySelectorAll('link[rel="alternate"][hreflang]').forEach(el => el.remove())
    // Add new hreflang tags
    HREFLANG_VARIANTS.forEach(({ lang }) => {
      const link = document.createElement("link")
      link.rel = "alternate"
      link.hreflang = lang
      link.href = url
      document.head.appendChild(link)
    })
    // Add x-default
    const defaultLink = document.createElement("link")
    defaultLink.rel = "alternate"
    defaultLink.hreflang = "x-default"
    defaultLink.href = url
    document.head.appendChild(defaultLink)

    // ===== OPEN GRAPH =====
    setMeta("og:title", fullTitle, "property")
    setMeta("og:description", description, "property")
    setMeta("og:type", type, "property")
    setMeta("og:url", url, "property")
    setMeta("og:image", `${SITE_URL}${image}`, "property")
    setMeta("og:image:width", "1200", "property")
    setMeta("og:image:height", "630", "property")
    setMeta("og:image:alt", imageAlt, "property")
    setMeta("og:site_name", "Subscription Hero", "property")
    setMeta("og:locale", "en_US", "property")

    // ===== TWITTER CARDS =====
    setMeta("twitter:card", "summary_large_image")
    setMeta("twitter:title", fullTitle)
    setMeta("twitter:description", description)
    setMeta("twitter:image", `${SITE_URL}${image}`)
    setMeta("twitter:image:alt", imageAlt)
    setMeta("twitter:site", "@subscriptionhero")
    setMeta("twitter:creator", "@subscriptionhero")

    // ===== ARTICLE-SPECIFIC META =====
    if (type === "article" && article) {
      setMeta("article:published_time", article.publishedAt || new Date().toISOString(), "property")
      setMeta("article:modified_time", article.modifiedAt || article.publishedAt || new Date().toISOString(), "property")
      setMeta("article:author", article.author || "Subscription Hero", "property")
      setMeta("article:publisher", "https://www.facebook.com/subscriptionhero", "property")
      setMeta("article:section", article.section || "Technology", "property")
      if (article.tags) {
        // Remove old article tags
        document.querySelectorAll('meta[property^="article:tag"]').forEach(el => el.remove())
        article.tags.slice(0, 5).forEach(tag => {
          const meta = document.createElement("meta")
          meta.setAttribute("property", "article:tag")
          meta.setAttribute("content", tag)
          document.head.appendChild(meta)
        })
      }
    }

    // ===== VIEWPORT & MOBILE =====
    setMeta("viewport", "width=device-width, initial-scale=1.0, maximum-scale=5.0")
    setMeta("theme-color", "#0a0a0a")
    setMeta("msapplication-TileColor", "#0a0a0a")
    setMeta("apple-mobile-web-app-capable", "yes")
    setMeta("apple-mobile-web-app-status-bar-style", "black-translucent")
    setMeta("apple-mobile-web-app-title", "Subscription Hero")
    setMeta("application-name", "Subscription Hero")

    // ===== LANGUAGE =====
    document.documentElement.lang = "en"

    // Cleanup: remove old article tags when navigating away from article
    return () => {
      if (type !== "article") {
        document.querySelectorAll('meta[property^="article:"]').forEach(el => el.remove())
      }
    }
  }, [fullTitle, description, keywords, image, imageAlt, url, type, article, noindex])

  return null
}
