import React from 'react';
import { Helmet } from 'react-helmet-async';
import { useSEO } from '@/hooks/useSEO';
import { SEOHead } from './SEOHead';

export const DynamicSEO: React.FC = () => {
  const { globalSettings, pageSEO, loading } = useSEO();

  if (loading) return null;

  // Yardımcı fonksiyon: Eğer kullanıcı tüm meta tag'i yapıştırdıysa sadece content değerini al
  const extractContent = (value: string) => {
    if (!value) return '';
    // Eğer tüm meta tag yapıştırıldıysa: <meta name="..." content="VALUE" />
    const contentMatch = value.match(/content=["']([^"']+)["']/i);
    if (contentMatch) return contentMatch[1];
    
    // Eğer sadece değer yapıştırıldıysa, her ihtimale karşı temizle
    return value.trim().replace(/^['"]|['"]$/g, '');
  };

  // Yardımcı fonksiyon: Eğer kullanıcı tüm script'i yapıştırdıysa sadece ID'yi al
  const extractGAId = (value: string) => {
    if (!value) return '';
    // GA4 ID: G-XXXXXXXXXX, UA ID: UA-XXXXXXXXX-X
    const idMatch = value.match(/(G-[A-Z0-9]+|UA-[0-9]+-[0-9]+)/i);
    if (idMatch) return idMatch[1].toUpperCase();
    
    return value.trim();
  };

  const gaId = extractGAId(globalSettings?.google_analytics_id || '');
  const verificationCode = extractContent(globalSettings?.google_search_console_verification || '');

  const finalTitle = pageSEO?.page_title || globalSettings?.site_name || 'Trip Planner';
  const finalDescription = pageSEO?.meta_description || globalSettings?.site_description || undefined;
  const finalKeywords = pageSEO?.meta_keywords || globalSettings?.site_keywords || undefined;
  const finalOgImage = pageSEO?.og_image || globalSettings?.default_og_image || undefined;

  return (
    <>
      <SEOHead
        title={finalTitle}
        description={finalDescription}
        keywords={finalKeywords}
        ogTitle={pageSEO?.og_title || finalTitle}
        ogDescription={pageSEO?.og_description || finalDescription}
        ogImage={finalOgImage}
        ogType={pageSEO?.og_type || 'website'}
        twitterCard={pageSEO?.twitter_card || 'summary_large_image'}
        twitterTitle={pageSEO?.twitter_title || pageSEO?.og_title || finalTitle}
        twitterDescription={pageSEO?.twitter_description || pageSEO?.og_description || finalDescription}
        twitterImage={pageSEO?.twitter_image || finalOgImage}
        canonicalUrl={pageSEO?.canonical_url || undefined}
        noindex={pageSEO?.noindex}
        nofollow={pageSEO?.nofollow}
        structuredData={pageSEO?.structured_data as any}
      />
      
      {/* Google Analytics & Console Verification */}
      <Helmet>
        {gaId && (
          <script async src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`} />
        )}
        {gaId && (
          <script dangerouslySetInnerHTML={{ __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${gaId}');
          ` }} />
        )}
        {verificationCode && (
          <meta name="google-site-verification" content={verificationCode} />
        )}
        {globalSettings?.facebook_app_id && (
          <meta property="fb:app_id" content={globalSettings.facebook_app_id.trim()} />
        )}
        {globalSettings?.twitter_handle && (
          <meta name="twitter:site" content={globalSettings.twitter_handle.trim()} />
        )}
      </Helmet>
    </>
  );
};
