import { useEffect } from "react"
import type { BlogPost } from "@/data/blogData"
import type { Product } from "@/data/products"

interface SchemaMarkupProps {
  type: "Organization" | "Website" | "BlogPosting" | "Product" | "FAQPage" | "BreadcrumbList" | "ItemList"
  data?: BlogPost | Product | Record<string, unknown>
}

const SITE_URL = "https://subscriptionhero.pro"

function addJsonLd(schema: Record<string, unknown>) {
  const id = "schema-" + schema["@type"]
  let script = document.getElementById(id) as HTMLScriptElement | null
  if (!script) {
    script = document.createElement("script")
    script.type = "application/ld+json"
    script.id = id
    document.head.appendChild(script)
  }
  script.textContent = JSON.stringify(schema)
}

export function SchemaMarkup({ type, data }: SchemaMarkupProps) {
  useEffect(() => {
    // Always add Organization + Website schemas
    addJsonLd({
      "@context": "https://schema.org",
      "@type": "Organization",
      "@id": `${SITE_URL}/#organization`,
      name: "Subscription Hero",
      alternateName: "SubscriptionHero",
      url: SITE_URL,
      logo: {
        "@type": "ImageObject",
        url: `${SITE_URL}/hero-bg.jpg`,
        width: 1200,
        height: 630,
      },
      description: "Buy cheap premium subscriptions for Netflix, Spotify, ChatGPT Plus, Canva Pro, Adobe Creative Cloud & 75+ more tools at up to 96% off. Instant delivery. 24H money-back guarantee.",
      email: "support@subscriptionhero.pro",
      telephone: "+91-703-814-6526",
      sameAs: [
        "https://wa.me/917038146526",
        "https://t.me/mfatool",
      ],
      address: {
        "@type": "PostalAddress",
        addressCountry: "IN",
      },
      contactPoint: {
        "@type": "ContactPoint",
        telephone: "+91-703-814-6526",
        contactType: "customer service",
        availableLanguage: ["English"],
        areaServed: "Worldwide",
      },
    })

    addJsonLd({
      "@context": "https://schema.org",
      "@type": "WebSite",
      "@id": `${SITE_URL}/#website`,
      url: SITE_URL,
      name: "Subscription Hero",
      description: "Premium digital subscriptions marketplace with up to 96% off",
      publisher: { "@id": `${SITE_URL}/#organization` },
      potentialAction: {
        "@type": "SearchAction",
        target: {
          "@type": "EntryPoint",
          urlTemplate: `${SITE_URL}/shop?search={search_term_string}`,
        },
        "query-input": "required name=search_term_string",
      },
    })

    // Page-specific schema
    if (type === "BlogPosting" && data) {
      const post = data as BlogPost
      addJsonLd({
        "@context": "https://schema.org",
        "@type": "BlogPosting",
        "@id": `${SITE_URL}/blog/${post.slug}/#article`,
        headline: post.title,
        description: post.excerpt,
        image: `${SITE_URL}${post.image}`,
        datePublished: post.publishedAt,
        dateModified: post.publishedAt,
        author: {
          "@type": "Organization",
          name: post.author,
          url: SITE_URL,
        },
        publisher: { "@id": `${SITE_URL}/#organization` },
        mainEntityOfPage: {
          "@type": "WebPage",
          "@id": `${SITE_URL}/blog/${post.slug}`,
        },
        articleSection: post.category,
        keywords: post.tags.join(", "),
        inLanguage: "en-US",
      })

      // Breadcrumbs for blog post
      addJsonLd({
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        itemListElement: [
          { "@type": "ListItem", position: 1, name: "Home", item: SITE_URL },
          { "@type": "ListItem", position: 2, name: "Blog", item: `${SITE_URL}/blog` },
          { "@type": "ListItem", position: 3, name: post.title },
        ],
      })
    }

    if (type === "FAQPage") {
      addJsonLd({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: [
          {
            "@type": "Question",
            name: "Are the subscriptions genuine and legal?",
            acceptedAnswer: {
              "@type": "Answer",
              text: "Yes. We provide 100% authentic subscriptions through official channels. All licenses are genuine with zero ban risk. We have served 10,000+ customers since 2023 with a 99.8% success rate.",
            },
          },
          {
            "@type": "Question",
            name: "How fast will I receive my subscription?",
            acceptedAnswer: {
              "@type": "Answer",
              text: "Instant delivery! Most orders are fulfilled within 2 to 10 minutes via WhatsApp or email. You will receive clear setup instructions and direct access credentials.",
            },
          },
          {
            "@type": "Question",
            name: "What payment methods do you accept?",
            acceptedAnswer: {
              "@type": "Answer",
              text: "We accept UPI (Google Pay, PhonePe, Paytm), PayPal for international orders, and Cryptocurrency (Bitcoin, Ethereum, USDT). All payments are secure and encrypted.",
            },
          },
          {
            "@type": "Question",
            name: "Can I get a refund if something doesn't work?",
            acceptedAnswer: {
              "@type": "Answer",
              text: "Absolutely! We offer a 24-hour money-back guarantee. If we cannot resolve any issue within 24 hours, you get a full refund with no questions asked.",
            },
          },
          {
            "@type": "Question",
            name: "Will my subscription work on multiple devices?",
            acceptedAnswer: {
              "@type": "Answer",
              text: "Yes, most subscriptions support multi-device access. After purchase, you will receive detailed instructions on how to activate on all your devices.",
            },
          },
        ],
      })
    }

    if (type === "Product" && data) {
      const product = data as Product
      addJsonLd({
        "@context": "https://schema.org",
        "@type": "Product",
        name: product.name,
        description: product.shortDesc,
        image: `${SITE_URL}${product.image}`,
        brand: { "@type": "Brand", name: product.category },
        offers: {
          "@type": "Offer",
          url: `${SITE_URL}/product/${product.slug}`,
          priceCurrency: "USD",
          price: product.price.toString(),
          priceValidUntil: "2026-12-31",
          availability: product.inStock ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
          seller: { "@type": "Organization", name: "Subscription Hero" },
        },
        aggregateRating: {
          "@type": "AggregateRating",
          ratingValue: String(product.rating ?? 5),
          reviewCount: String(product.reviewCount ?? 10),
          bestRating: "5",
        },
      })

      // Breadcrumbs for product
      addJsonLd({
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        itemListElement: [
          { "@type": "ListItem", position: 1, name: "Home", item: SITE_URL },
          { "@type": "ListItem", position: 2, name: "Shop", item: `${SITE_URL}/shop` },
          { "@type": "ListItem", position: 3, name: product.name },
        ],
      })
    }
  }, [type, data])

  return null
}
