import { useEffect } from "react";
import { getRuntimeCanonicalUrl, rebaseSameSiteSchemaUrls } from "@/lib/seoUrls";

interface SEOHeadProps {
  title: string;
  description: string;
  canonicalUrl?: string;
  schemaType?: "Organization" | "RealEstateAgent" | "FAQPage" | "WebSite";
  keywords?: string[];
  schema?: Record<string, unknown>;
}

export function buildDefaultSchema(schemaType: SEOHeadProps["schemaType"], origin: string): Record<string, unknown> {
  if (schemaType === "Organization") {
    return {
      "@context": "https://schema.org",
      "@type": "Organization",
      "name": "Original Home Buyers",
      "@id": `${origin}/#organization`,
      "url": `${origin}/`,
      "telephone": "+1-240-410-5636",
      "email": "info@originalhomebuyers.com"
    };
  }

  if (schemaType === "FAQPage") {
    return {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "How does Home Buyers Nationwide calculate my cash offer?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "We evaluate local comparable market sales, the current physical condition of the property, estimated repair costs, and your preferred closing timeline to present a fair, no-obligation cash offer."
          }
        },
        {
          "@type": "Question",
          "name": "Are there any fees, commissions, or closing costs?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "No. When you sell directly to Home Buyers Nationwide, you pay $0 in real estate agent commissions and we cover standard closing costs."
          }
        },
        {
          "@type": "Question",
          "name": "Do I need to clean or make repairs before selling?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Not at all. We buy houses 100% as-is. Leave deferred maintenance, roof repairs, or unwanted belongings behind and we will handle them."
          }
        }
      ]
    };
  }

  return {};
}

export default function SEOHead({ title, description, canonicalUrl, schemaType = "Organization", keywords, schema }: SEOHeadProps) {
  useEffect(() => {
    document.title = title;
    
    // Update meta description
    let metaDesc = document.querySelector('meta[name="description"]');
    if (!metaDesc) {
      metaDesc = document.createElement("meta");
      metaDesc.setAttribute("name", "description");
      document.head.appendChild(metaDesc);
    }
    metaDesc.setAttribute("content", description);

    // Update canonical
    let canonical = document.querySelector('link[rel="canonical"]');
    if (!canonical) {
      canonical = document.createElement("link");
      canonical.setAttribute("rel", "canonical");
      document.head.appendChild(canonical);
    }
    const runtimeCanonicalUrl = getRuntimeCanonicalUrl(canonicalUrl);
    canonical.setAttribute("href", runtimeCanonicalUrl);

    let metaKeywords = document.querySelector('meta[name="keywords"]');
    if (keywords?.length) {
      if (!metaKeywords) {
        metaKeywords = document.createElement("meta");
        metaKeywords.setAttribute("name", "keywords");
        document.head.appendChild(metaKeywords);
      }
      metaKeywords.setAttribute("content", keywords.join(", "));
    } else if (metaKeywords) {
      metaKeywords.remove();
    }

    // Inject JSON-LD Schema
    const existingSchema = document.querySelector('script[type="application/ld+json"][data-seo-schema="true"]');
    if (existingSchema) {
      existingSchema.remove();
    }

    const script = document.createElement("script");
    script.setAttribute("type", "application/ld+json");
    script.setAttribute("data-seo-schema", "true");

    const schemaData: Record<string, unknown> = schema || buildDefaultSchema(schemaType, window.location.origin);

    if (Object.keys(schemaData).length) {
      script.textContent = JSON.stringify(rebaseSameSiteSchemaUrls(schemaData, window.location.origin));
      document.head.appendChild(script);
    }
  }, [title, description, canonicalUrl, schemaType, keywords, schema]);

  return null;
}
