"use client";

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import {
  HTML_LANG,
  OG_LOCALE,
  SELECT_LANGUAGE_PATH,
  SITE_URL,
  detectLocale,
  getAlternates,
} from '@/config/i18nRoutes';

interface PageMeta {
  title?: string;
  description?: string;
  canonical?: string;
  image?: string;
  imageWidth?: string;
  imageHeight?: string;
  type?: 'website' | 'article';
  robots?: string;
}

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

const upsertCanonical = (href: string) => {
  let el = document.head.querySelector<HTMLLinkElement>('link[rel="canonical"]');
  if (!el) {
    el = document.createElement('link');
    el.rel = 'canonical';
    document.head.appendChild(el);
  }
  el.href = href;
};

const HREFLANG_ATTR = 'data-i18n-hreflang';

const setHreflangLinks = (links: { hreflang: string; href: string }[]) => {
  document.head.querySelectorAll(`link[${HREFLANG_ATTR}]`).forEach((el) => el.remove());
  links.forEach(({ hreflang, href }) => {
    const el = document.createElement('link');
    el.rel = 'alternate';
    el.setAttribute('hreflang', hreflang);
    el.href = href;
    el.setAttribute(HREFLANG_ATTR, '');
    document.head.appendChild(el);
  });
};

export const usePageMeta = ({
  title,
  description,
  canonical,
  image,
  imageWidth,
  imageHeight,
  type = 'website',
  robots,
}: PageMeta) => {
  const pathname = usePathname() || '/';

  useEffect(() => {
    const prevTitle = document.title;
    if (title) document.title = title;
    if (description) {
      upsertMeta('description', description);
      upsertMeta('og:description', description, 'property');
      upsertMeta('twitter:description', description);
    }
    if (title) {
      upsertMeta('og:title', title, 'property');
      upsertMeta('twitter:title', title);
    }
    upsertMeta('og:type', type, 'property');

    const locale = detectLocale(pathname);
    document.documentElement.lang = HTML_LANG[locale];
    upsertMeta('og:locale', OG_LOCALE[locale], 'property');

    const alternates = getAlternates(pathname);
    if (alternates) {
      setHreflangLinks([
        { hreflang: 'fr', href: SITE_URL + alternates.fr },
        { hreflang: 'en', href: SITE_URL + alternates.en },
        { hreflang: 'es', href: SITE_URL + alternates.es },
        { hreflang: 'x-default', href: SITE_URL + SELECT_LANGUAGE_PATH },
      ]);
    } else {
      setHreflangLinks([]);
    }

    if (canonical) {
      upsertCanonical(canonical);
      upsertMeta('og:url', canonical, 'property');
    }
    if (image) {
      upsertMeta('og:image', image, 'property');
      upsertMeta('twitter:image', image);
      upsertMeta('twitter:card', 'summary_large_image');
      if (imageWidth) upsertMeta('og:image:width', imageWidth, 'property');
      if (imageHeight) upsertMeta('og:image:height', imageHeight, 'property');
    }
    if (robots) upsertMeta('robots', robots);

    return () => {
      document.title = prevTitle;
    };
  }, [canonical, description, image, imageHeight, imageWidth, pathname, robots, title, type]);
};

export const useJsonLd = (id: string, data: unknown | unknown[]) => {
  useEffect(() => {
    const script = document.createElement('script');
    script.type = 'application/ld+json';
    script.id = id;
    script.text = JSON.stringify(data);

    const existing = document.getElementById(id);
    if (existing) existing.remove();
    document.head.appendChild(script);

    return () => {
      script.remove();
    };
  }, [id, data]);
};
