import { useEffect } from "react";
import { useLanguage } from "@/contexts/LanguageContext";

const SITE_URL = "https://www.alzarfze.com";
const LOGO_URL = `${SITE_URL}/images/kHSmOkFIzSbmDqbQ.png`;

// Social platforms require absolute URLs for OG/Twitter images.
// Relative paths (/images/...) are promoted to absolute against SITE_URL.
function toAbsolute(url: string): string {
  if (!url) return LOGO_URL;
  if (url.startsWith("http://") || url.startsWith("https://")) return url;
  return `${SITE_URL}${url.startsWith("/") ? "" : "/"}${url}`;
}

interface BreadcrumbItem {
  name: string;
  url: string;
}

interface SEOHeadProps {
  title: string;
  description: string;
  canonical?: string;
  keywords?: string;
  ogImage?: string;
  ogType?: string;
  breadcrumbs?: BreadcrumbItem[];
  noindex?: boolean;
}

export default function SEOHead({
  title,
  description,
  canonical,
  keywords,
  ogImage,
  ogType = "website",
  breadcrumbs,
  noindex = false,
}: SEOHeadProps) {
  const { lang } = useLanguage();

  useEffect(() => {
    document.title = title;

    // Set html lang attribute based on current language
    document.documentElement.lang = lang === "ar" ? "ar" : "en";
    document.documentElement.dir = lang === "ar" ? "rtl" : "ltr";

    const setMeta = (name: string, content: string, attr = "name") => {
      let el = document.querySelector(`meta[${attr}="${name}"]`) as HTMLMetaElement | null;
      if (!el) {
        el = document.createElement("meta");
        el.setAttribute(attr, name);
        document.head.appendChild(el);
      }
      el.content = content;
    };

    const setLink = (rel: string, href: string, attrs?: Record<string, string>) => {
      const selector = attrs
        ? `link[rel="${rel}"][hreflang="${attrs.hreflang || ""}"]`
        : `link[rel="${rel}"]`;
      let el = document.querySelector(selector) as HTMLLinkElement | null;
      if (!el) {
        el = document.createElement("link");
        el.rel = rel;
        if (attrs) {
          Object.entries(attrs).forEach(([k, v]) => el!.setAttribute(k, v));
        }
        document.head.appendChild(el);
      }
      el.href = href;
    };

    // Primary meta tags
    setMeta("description", description);
    if (keywords) setMeta("keywords", keywords);
    setMeta("robots", noindex ? "noindex, nofollow" : "index, follow");

    // Open Graph
    setMeta("og:title", title, "property");
    setMeta("og:description", description, "property");
    setMeta("og:type", ogType, "property");
    setMeta("og:site_name", "Alzar FZE", "property");
    setMeta("og:locale", lang === "ar" ? "ar_AE" : "en_US", "property");
    setMeta("og:image", toAbsolute(ogImage || LOGO_URL), "property");
    if (canonical) {
      setMeta("og:url", canonical, "property");
    }

    // Twitter Card
    setMeta("twitter:card", "summary_large_image");
    setMeta("twitter:title", title);
    setMeta("twitter:description", description);
    setMeta("twitter:image", toAbsolute(ogImage || LOGO_URL));

    // Canonical URL
    if (canonical) {
      setLink("canonical", canonical);
    }

    // Hreflang tags for bilingual support
    if (canonical) {
      setLink("alternate", canonical, { hreflang: "en" });
      setLink("alternate", canonical, { hreflang: "ar" });
      setLink("alternate", canonical, { hreflang: "x-default" });
    }

    // Breadcrumb structured data
    if (breadcrumbs && breadcrumbs.length > 0) {
      const existingBreadcrumb = document.querySelector('script[data-type="breadcrumb"]');
      if (existingBreadcrumb) existingBreadcrumb.remove();

      const breadcrumbSchema = {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        itemListElement: breadcrumbs.map((item, index) => ({
          "@type": "ListItem",
          position: index + 1,
          name: item.name,
          item: item.url,
        })),
      };

      const script = document.createElement("script");
      script.type = "application/ld+json";
      script.setAttribute("data-type", "breadcrumb");
      script.textContent = JSON.stringify(breadcrumbSchema);
      document.head.appendChild(script);

      return () => {
        script.remove();
      };
    }
  }, [title, description, canonical, keywords, ogImage, ogType, breadcrumbs, noindex, lang]);

  return null;
}
