import { Helmet } from 'react-helmet-async';
import { useEffect, useState } from 'react';
import api from '../../services/api';
import { assetUrl } from '../../utils/url';
import { usePublicSettings } from '../../hooks/usePublicSettings';

interface SEOData {
  site_title?: string;
  site_description?: string;
  meta_keywords?: string;
  default_og_image_url?: string;
  twitter_handle?: string;
  canonical_base_url?: string;
  additional_meta?: string; // raw HTML strings not injected for safety here
  enable_indexing?: boolean;
}

export default function DefaultSEO() {
  const [seo, setSeo] = useState<SEOData | null>(null);
  const [social, setSocial] = useState<{ facebook?: string; instagram?: string; youtube?: string } | null>(null);
  const { data: publicSettings } = usePublicSettings();

  useEffect(() => {
    let mounted = true;
    api.get<SEOData>('/seo')
      .then(res => { if (mounted) setSeo(res.data as any); })
      .catch(() => {});
    // Socials can come from settings (hook). Set when available
    // We still keep axios SEO fetch above for dedicated SEO fields
    return () => { mounted = false; };
  }, []);

  // Keep socials in sync when settings load
  useEffect(() => {
    if (!publicSettings) return;
    setSocial({
      facebook: publicSettings.facebook_url,
      instagram: publicSettings.instagram_url,
      youtube: publicSettings.youtube_url,
    });
  }, [publicSettings]);

  const fallbackClubName = publicSettings?.club_name;
  const title = (seo?.site_title && seo.site_title.trim()) || (fallbackClubName && fallbackClubName.trim()) || 'MyClub';
  const desc = (seo?.site_description && seo.site_description.trim()) || (fallbackClubName ? `Official ${fallbackClubName} Website` : 'Official MyClub Website');
  const keywords = seo?.meta_keywords || '';
  const rawOg = seo?.default_og_image_url || publicSettings?.club_logo_url || '/logo512.png';
  const ogImg = assetUrl(rawOg) || rawOg;
  const twitter = seo?.twitter_handle || '';
  const origin = seo?.canonical_base_url || (typeof window !== 'undefined' ? window.location.origin : '');
  const sameAs: string[] = [];
  if (twitter) {
    const handle = twitter.startsWith('@') ? twitter.slice(1) : twitter;
    sameAs.push(`https://twitter.com/${handle}`);
  }
  if (social?.facebook) sameAs.push(social.facebook);
  if (social?.instagram) sameAs.push(social.instagram);
  if (social?.youtube) sameAs.push(social.youtube);

  // robots
  const robots = seo?.enable_indexing === false ? 'noindex, nofollow' : 'index, follow';

  // Ensure document title updates as soon as we have a computed title
  useEffect(() => {
    if (typeof document !== 'undefined' && title) {
      document.title = title;
    }
  }, [title]);

  return (
    <Helmet defaultTitle={title} titleTemplate={`%s | ${fallbackClubName || title}`}>
      <title>{title}</title>
      <meta name="description" content={desc} />
      {keywords && <meta name="keywords" content={keywords} />}
      <meta name="robots" content={robots} />
      {/* Favicon and app icons based on club logo */}
      {publicSettings?.club_logo_url && (
        <>
          <link rel="icon" href={assetUrl(publicSettings.club_logo_url)} />
          <link rel="shortcut icon" href={assetUrl(publicSettings.club_logo_url)} />
          <link rel="apple-touch-icon" href={assetUrl(publicSettings.club_logo_url)} />
        </>
      )}
      {/* Open Graph */}
      <meta property="og:type" content="website" />
      <meta property="og:title" content={title} />
      <meta property="og:description" content={desc} />
      <meta property="og:image" content={ogImg} />
      {/* Twitter */}
      <meta name="twitter:card" content="summary_large_image" />
      {twitter && <meta name="twitter:site" content={twitter} />}
      <meta name="twitter:title" content={title} />
      <meta name="twitter:description" content={desc} />
      <meta name="twitter:image" content={ogImg} />
      {/* Canonical (best-effort: base only; pages can override) */}
      {seo?.canonical_base_url && <link rel="canonical" href={seo.canonical_base_url} />}
      {/* JSON-LD: WebSite + SearchAction */}
      {origin && (
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'WebSite',
            url: origin,
            name: title,
            potentialAction: {
              '@type': 'SearchAction',
              target: `${origin}/blog?q={search_term_string}`,
              'query-input': 'required name=search_term_string'
            }
          })}
        </script>
      )}
      {/* JSON-LD: Organization */}
      {origin && (
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'Organization',
            url: origin,
            name: title,
            logo: ogImg,
            sameAs: sameAs.length ? sameAs : undefined,
          })}
        </script>
      )}
    </Helmet>
  );
}
