// @design-system: primitives/SeoHead
// Registered at /design-system#seohead-primitive - Phase 3 (Agent 3E) will render the gallery.

import type { Locale } from '@/lib/i18n';
import type { LaunchState } from '@/server/env';
import { captureCaught } from '@/lib/observability';
import { JsonLd } from '../JsonLd';

/** Supported hreflang locales */
const HREFLANG_LOCALES: Locale[] = ['he', 'en'];

/** BCP 47 region-qualified hreflang codes for output */
const HREFLANG_BCP47: Record<Locale, string> = { he: 'he-IL', en: 'en-IL' };

/** Props for the SeoHead component */
export interface SeoHeadProps {
  /** Page title - used in `<title>` and `og:title`. */
  title: string;
  /** Page description - used in `<meta name="description">` and `og:description`. */
  description?: string;
  /** Canonical URL - used in `<link rel="canonical">` and `og:url`. */
  canonical?: string;
  /**
   * OG image URL - MUST be WebP (Facebook/WhatsApp don't support AVIF).
   * Provide a full absolute URL.
   */
  ogImage?: string;
  /** Alt text for the OG image (required for accessibility). */
  ogImageAlt?: string;
  /**
   * OG image width in pixels. Defaults to 1200 when ogImage is provided.
   */
  ogImageWidth?: number;
  /**
   * OG image height in pixels. Defaults to 630 when ogImage is provided.
   */
  ogImageHeight?: number;
  /**
   * OG type. Defaults to 'website'. Use 'product' for deal/product pages,
   * 'article' for blog/editorial pages.
   */
  ogType?: 'website' | 'product' | 'article';
  /** Current page locale - drives `og:locale` and hreflang. */
  locale?: Locale;
  /**
   * JSON-LD structured data.
   * Rendered via the `<JsonLd>` sub-component with HTML escaping.
   */
  jsonLd?: Record<string, unknown>;
  /** When true, adds `<meta name="robots" content="noindex, nofollow">`. */
  noindex?: boolean;
  launchState?: LaunchState;
  /**
   * GEO meta tags for location-based SEO.
   * ISO 3166-2 region code, e.g. "IL" for Israel.
   */
  geoRegion?: string;
  /** Human-readable place name, e.g. "Israel". */
  geoPlaceName?: string;
  /** Decimal latitude;longitude, e.g. "31.0461;34.8516". */
  geoPosition?: string;
  /** WGS84 ICBM-style coordinates (same as geoPosition, different tag name). */
  icbm?: string;
  /**
   * Base URL for generating hreflang alternates.
   * e.g. `https://multideal.co.il`
   */
  baseUrl?: string;
  /**
   * Locale-specific path map for hreflang alternates.
   * If not provided, canonical is used for all locales.
   */
  alternates?: Partial<Record<Locale, string>>;
  /**
   * Arbitrary locale alternates for deal detail pages (Plan 3).
   * Accepts any locale code including 'x-default'.
   * When provided, these are emitted INSTEAD of the standard he/en hreflang tags
   * so deal detail pages can have per-translation hreflang coverage.
   *
   * @example
   * localeAlternates={[
   *   { locale: 'he', url: 'https://multideal.co.il/he/deals/pizza' },
   *   { locale: 'en', url: 'https://multideal.co.il/en/deals/pizza' },
   *   { locale: 'x-default', url: 'https://multideal.co.il/he/deals/pizza' },
   * ]}
   */
  localeAlternates?: Array<{ locale: string; url: string }>;
  /**
   * Twitter @handle for the site, used for `<meta name="twitter:site">`.
   * Defaults to `@multideal`.
   */
  twitterSite?: string;
  /**
   * When true, suppresses all hreflang alternate link tags.
   * Use on canonical surfaces where hreflang is intentionally omitted
   * (e.g. `/deal/[id]` per flowmap §10 audit).
   */
  suppressHreflang?: boolean;
}

/**
 * Multideal SeoHead - renders all required SEO meta tags.
 *
 * Emits: `<title>`, description, canonical, OG tags (WebP), Twitter card,
 * hreflang he/en/x-default, robots noindex.
 *
 * Use inside Astro `<head>` or a React island that renders into `<head>`.
 *
 * @example
 * ```astro
 * ---
 * import { SeoHead } from '@/components/ui/primitives/SeoHead';
 * ---
 * <SeoHead
 *   title="Multideal - Not a Big Deal"
 *   description="Discover deals at a discount"
 *   canonical="https://multideal.co.il/"
 *   locale="he"
 * />
 * ```
 */
export function SeoHead({
  title,
  description,
  canonical,
  ogImage,
  ogImageAlt,
  ogImageWidth,
  ogImageHeight,
  ogType = 'website',
  locale = 'he',
  jsonLd,
  noindex = false,
  launchState = 'live',
  baseUrl: _baseUrl,
  alternates,
  localeAlternates,
  suppressHreflang = false,
  geoRegion,
  geoPlaceName,
  geoPosition,
  icbm,
  twitterSite = '@multideal',
}: SeoHeadProps) {
  // Build hreflang URLs.
  // Per-locale URLs are derived by toggling the `?lang=` param on the canonical URL,
  // so each emitted alternate links to a distinct, locale-specific URL.
  const getLocaleUrl = (loc: Locale): string | undefined => {
    if (alternates?.[loc]) return alternates[loc];
    if (!canonical) return undefined;
    try {
      const u = new URL(canonical);
      u.searchParams.set('lang', loc);
      return u.toString();
    } catch (err) {
      // Non-absolute canonical — log and fall back to canonical as-is
      captureCaught(err, {
        scope: 'components.ui.primitives.SeoHead.getLocaleUrl',
        severity: 'info',
      });
      return canonical;
    }
  };

  const defaultUrl = getLocaleUrl('he') ?? canonical;

  return (
    <>
      {/*
        Critical font preloads - locale-conditional.
        - Hebrew (he): preload Heebo hebrew + latin subsets (Heebo is the active UI font).
        - English (en): preload Inter latin variable subset (Inter is the active UI font).
        Vendored woff2 files live under apps/web/public/fonts/.
      */}
      {locale === 'he' && (
        <>
          <link
            rel="preload"
            href="/fonts/heebo-hebrew-wght-normal.woff2"
            as="font"
            type="font/woff2"
            crossOrigin="anonymous"
          />
          <link
            rel="preload"
            href="/fonts/heebo-latin-wght-normal.woff2"
            as="font"
            type="font/woff2"
            crossOrigin="anonymous"
          />
        </>
      )}
      {locale === 'en' && (
        <link
          rel="preload"
          href="/fonts/inter-latin-wght-normal.woff2"
          as="font"
          type="font/woff2"
          crossOrigin="anonymous"
        />
      )}

      {/* Favicon */}
      <link rel="icon" href="/favicon.ico" sizes="48x48" />
      <link rel="icon" href="/icons/icon-192.png" type="image/png" sizes="192x192" />
      <link rel="apple-touch-icon" href="/icons/icon-192.png" />

      {/* Primary */}
      <title>{title}</title>
      {description && <meta name="description" content={description} />}
      {canonical && <link rel="canonical" href={canonical} />}
      <meta
        name="robots"
        content={noindex || launchState === 'prelaunch' ? 'noindex, nofollow' : 'index, follow'}
      />

      {/* Open Graph */}
      <meta property="og:site_name" content="Multideal" />
      <meta property="og:title" content={title} />
      {description && <meta property="og:description" content={description} />}
      {canonical && <meta property="og:url" content={canonical} />}
      <meta property="og:type" content={ogType} />
      <meta property="og:locale" content={locale === 'he' ? 'he_IL' : 'en_US'} />
      {ogImage && <meta property="og:image" content={ogImage} />}
      {ogImage && <meta property="og:image:type" content="image/webp" />}
      {ogImage && <meta property="og:image:width" content={String(ogImageWidth ?? 1200)} />}
      {ogImage && <meta property="og:image:height" content={String(ogImageHeight ?? 630)} />}
      {ogImageAlt && <meta property="og:image:alt" content={ogImageAlt} />}

      {/* Twitter Card */}
      <meta name="twitter:card" content="summary_large_image" />
      {twitterSite && <meta name="twitter:site" content={twitterSite} />}
      <meta name="twitter:title" content={title} />
      {description && <meta name="twitter:description" content={description} />}
      {ogImage && <meta name="twitter:image" content={ogImage} />}
      {ogImageAlt && <meta name="twitter:image:alt" content={ogImageAlt} />}

      {/* Hreflang — localeAlternates (Plan 3: per-translation deal pages) takes precedence */}
      {!suppressHreflang &&
        (localeAlternates && localeAlternates.length > 0 ? (
          localeAlternates.map((a) => (
            <link key={a.locale} rel="alternate" hrefLang={a.locale} href={a.url} />
          ))
        ) : (
          <>
            {HREFLANG_LOCALES.map((loc) => {
              const url = getLocaleUrl(loc);
              return url ? (
                <link key={loc} rel="alternate" hrefLang={HREFLANG_BCP47[loc]} href={url} />
              ) : null;
            })}
            {defaultUrl && <link rel="alternate" hrefLang="x-default" href={defaultUrl} />}
          </>
        ))}

      {/* GEO meta tags - location-based SEO */}
      {geoRegion && <meta name="geo.region" content={geoRegion} />}
      {geoPlaceName && <meta name="geo.placename" content={geoPlaceName} />}
      {geoPosition && <meta name="geo.position" content={geoPosition} />}
      {icbm && <meta name="ICBM" content={icbm} />}

      {/* JSON-LD */}
      {jsonLd && <JsonLd data={jsonLd} />}
    </>
  );
}
