import React from 'react';

const DEFAULT_LEARNITIVE_PUBLIC_ORIGIN = 'https://www.learnitive.com';

function activePublicOrigin() {
  if (typeof window === 'undefined') return DEFAULT_LEARNITIVE_PUBLIC_ORIGIN;
  return window.location.origin;
}

function isCanonicalProductionHost() {
  if (typeof window === 'undefined') return true;
  return window.location.hostname === 'www.learnitive.com';
}

export type PageMetadata = {
  title: string;
  description: string;
  pathname: string;
  noIndex?: boolean;
  robots?: 'index,follow' | 'noindex,follow' | 'noindex,nofollow';
  image?: string | null;
  type?: 'website' | 'article';
  publishedTime?: string | null;
  modifiedTime?: string | null;
  author?: string | null;
  tags?: string[];
  imageWidth?: number | null;
  imageHeight?: number | null;
  enabled?: boolean;
};

export function upsertMeta(selector: string, attributes: Record<string, string>) {
  let element = document.head.querySelector<HTMLMetaElement>(selector);
  if (!element) {
    element = document.createElement('meta');
    document.head.appendChild(element);
  }
  for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
}

export function usePageMetadata(metadata: PageMetadata) {
  const { title, description, pathname, noIndex = false, robots, image, type = 'website', publishedTime, modifiedTime, author, tags = [], imageWidth, imageHeight, enabled = true } = metadata;
  const tagsKey = tags.join('\u0000');
  React.useEffect(() => {
    if (!enabled) return;
    const fullTitle = title.includes('Learnitive') ? title : `${title} | Learnitive`;
    const publicOrigin = activePublicOrigin();
    const canonical = new URL(pathname, `${publicOrigin}/`).toString();
    const socialImage = new URL(image || '/learnitive-og.webp', `${publicOrigin}/`).toString();
    const imageAlt = image ? `${title} — Learnitive` : 'Learnitive — Learn. Research. Create. Your all-in-one knowledge workspace.';
    document.title = fullTitle;
    upsertMeta('meta[name="description"]', { name: 'description', content: description });
    const robotsValue = !isCanonicalProductionHost()
      ? 'noindex,nofollow,noarchive'
      : robots === 'noindex,follow'
        ? 'noindex,follow,max-image-preview:large'
        : robots === 'noindex,nofollow' || noIndex
          ? 'noindex,nofollow,noarchive'
          : 'index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1';
    upsertMeta('meta[name="robots"]', { name: 'robots', content: robotsValue });
    upsertMeta('meta[property="og:site_name"]', { property: 'og:site_name', content: 'Learnitive' });
    upsertMeta('meta[property="og:locale"]', { property: 'og:locale', content: 'en_US' });
    upsertMeta('meta[property="og:title"]', { property: 'og:title', content: fullTitle });
    upsertMeta('meta[property="og:description"]', { property: 'og:description', content: description });
    upsertMeta('meta[property="og:url"]', { property: 'og:url', content: canonical });
    upsertMeta('meta[property="og:type"]', { property: 'og:type', content: type });
    upsertMeta('meta[property="og:image"]', { property: 'og:image', content: socialImage });
    upsertMeta('meta[property="og:image:secure_url"]', { property: 'og:image:secure_url', content: socialImage });
    upsertMeta('meta[property="og:image:alt"]', { property: 'og:image:alt', content: imageAlt });
    const width = image ? imageWidth : 1731;
    const height = image ? imageHeight : 909;
    if (width) upsertMeta('meta[property="og:image:width"]', { property: 'og:image:width', content: String(width) });
    else document.head.querySelector('meta[property="og:image:width"]')?.remove();
    if (height) upsertMeta('meta[property="og:image:height"]', { property: 'og:image:height', content: String(height) });
    else document.head.querySelector('meta[property="og:image:height"]')?.remove();
    upsertMeta('meta[name="twitter:card"]', { name: 'twitter:card', content: 'summary_large_image' });
    upsertMeta('meta[name="twitter:title"]', { name: 'twitter:title', content: fullTitle });
    upsertMeta('meta[name="twitter:description"]', { name: 'twitter:description', content: description });
    upsertMeta('meta[name="twitter:image"]', { name: 'twitter:image', content: socialImage });
    upsertMeta('meta[name="twitter:image:alt"]', { name: 'twitter:image:alt', content: imageAlt });
    if (type === 'article' && publishedTime) upsertMeta('meta[property="article:published_time"]', { property: 'article:published_time', content: publishedTime });
    else document.head.querySelector('meta[property="article:published_time"]')?.remove();
    if (type === 'article' && modifiedTime) upsertMeta('meta[property="article:modified_time"]', { property: 'article:modified_time', content: modifiedTime });
    else document.head.querySelector('meta[property="article:modified_time"]')?.remove();
    if (type === 'article' && author) upsertMeta('meta[property="article:author"]', { property: 'article:author', content: author });
    else document.head.querySelector('meta[property="article:author"]')?.remove();
    document.head.querySelectorAll('meta[property="article:tag"][data-interactive-dynamic="true"]').forEach((node) => { node.remove(); });
    if (type === 'article') for (const tag of tags) {
      const node = document.createElement('meta');
      node.setAttribute('property', 'article:tag');
      node.setAttribute('content', tag);
      node.dataset.interactiveDynamic = 'true';
      document.head.appendChild(node);
    }
    let link = document.head.querySelector<HTMLLinkElement>('link[rel="canonical"]');
    if (!link) { link = document.createElement('link'); link.rel = 'canonical'; document.head.appendChild(link); }
    link.href = canonical;
    if (!document.head.querySelector('link[rel="alternate"][type="application/rss+xml"]')) {
      const rss = document.createElement('link'); rss.rel = 'alternate'; rss.type = 'application/rss+xml'; rss.title = 'Learnitive Blog RSS'; rss.href = '/blog/rss.xml'; document.head.appendChild(rss);
    }
  }, [author, description, enabled, image, imageHeight, imageWidth, modifiedTime, noIndex, pathname, publishedTime, robots, tagsKey, title, type]);
}
