import { useEffect } from "react";
import { DEFAULT_OG_IMAGE, SITE_NAME, toAbsoluteUrl } from "@/lib/seo";

interface HeadProps {
  title?: string;
  description?: string;
  image?: string;
  url?: string;
  canonical?: string;
  robots?: string;
  noindex?: boolean;
  type?: "website" | "article" | "profile";
  schema?: Record<string, unknown> | Record<string, unknown>[];
}

const MANAGED_META_KEY = "data-seo-managed";
const MANAGED_LINK_KEY = "data-seo-managed-link";

const setMetaTag = (selectorKey: "name" | "property", key: string, content: string) => {
  let element = document.querySelector(`meta[${selectorKey}="${key}"]`) as HTMLMetaElement | null;
  if (!element) {
    element = document.createElement("meta");
    element.setAttribute(selectorKey, key);
    document.head.appendChild(element);
  }
  element.setAttribute("content", content);
  element.setAttribute(MANAGED_META_KEY, "true");
};

const setCanonicalLink = (href: string) => {
  let canonical = document.querySelector("link[rel='canonical']") as HTMLLinkElement | null;
  if (!canonical) {
    canonical = document.createElement("link");
    canonical.setAttribute("rel", "canonical");
    document.head.appendChild(canonical);
  }
  canonical.setAttribute("href", href);
  canonical.setAttribute(MANAGED_LINK_KEY, "true");
};

const getBaseTitle = (title?: string) => {
  if (!title) return SITE_NAME;
  if (title.includes(SITE_NAME)) return title;
  return `${title} | ${SITE_NAME}`;
};

export function useHead({ title, description, image, url, canonical, robots, noindex, type, schema }: HeadProps) {
  useEffect(() => {
    const finalTitle = getBaseTitle(title);
    document.title = finalTitle;

    const path = window.location.pathname;
    const finalCanonical = canonical || url || path;
    const finalUrl = finalCanonical || url;
    const finalImage = image ? toAbsoluteUrl(image) : toAbsoluteUrl(DEFAULT_OG_IMAGE);
    const finalType = type || "website";
    const robotsValue = robots || (noindex ? "noindex,nofollow" : "index,follow");
    const finalDescription = description || "Every action is a command. Every command is versioned, auditable, and composable. The platform where humans and AI agents engineer together.";

    setMetaTag("name", "viewport", "width=device-width, initial-scale=1");
    setMetaTag("name", "robots", robotsValue);
    setMetaTag("property", "og:title", finalTitle);
    setMetaTag("name", "description", finalDescription);
    setMetaTag("property", "og:description", finalDescription);
    setMetaTag("property", "og:type", finalType);

    if (finalImage) setMetaTag("property", "og:image", finalImage);
    if (finalUrl) setMetaTag("property", "og:url", toAbsoluteUrl(finalUrl));
    if (finalCanonical) setCanonicalLink(toAbsoluteUrl(finalCanonical));

    if (schema) {
      const script = document.createElement("script");
      script.setAttribute("type", "application/ld+json");
      script.textContent = JSON.stringify(schema);
      document.head.appendChild(script);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [title, description, image, url, canonical, robots, noindex, type]);
}
