/**
 * WelcomeHead — JSON-LD schema + OG/Twitter meta tags for the homepage (DEBT-005 extraction).
 *
 * Extracted from Welcome.tsx verbatim (move not rewrite). The Head component and all
 * structured-data scripts live here so Welcome.tsx stays under the 300-LOC limit.
 */
import { Head } from '@inertiajs/react';

import { features } from '@/Components/marketing/WelcomePageData';
import { softwareApplicationBase, buildOffer } from '@/lib/schema';

interface PricingTierRef {
  name: string;
  price: string;
}

interface TestimonialRef {
  rating?: number;
  source?: string | null;
  source_url?: string | null;
}

/** R3SEO-011: minimum attributable reviews before emitting aggregateRating. */
const AGGREGATE_RATING_MIN_COUNT = 5;

export interface WelcomeHeadProps {
  appName: string;
  appUrl: string;
  /** @deprecated Pass pricingTiers instead; highPrice is now derived from that array. */
  teamPrice?: number;
  pricingTiers: PricingTierRef[];
  testimonials: TestimonialRef[];
}

export function WelcomeHead({
  appName,
  appUrl,
  // F5SEO-004: teamPrice ignored — highPrice derived from pricingTiers so the
  // AggregateOffer schema stays accurate as tiers change without a separate prop.
  teamPrice: _teamPrice,
  pricingTiers,
  testimonials,
}: WelcomeHeadProps) {
  // F4SEO-004: normalize homepage URL to consistently include a trailing slash so
  // canonical and og:url always resolve to the same URL regardless of how APP_URL
  // is configured (with or without trailing slash).
  const canonicalUrl = appUrl.replace(/\/$/, '') + '/';

  return (
    <Head title={`${appName} — WordPress SEO Recovery & ROI Proof`}>
      <link rel="canonical" href={canonicalUrl} />
      <meta
        name="description"
        content="Find WordPress pages hit by Google updates, rewrite with AI, prove what fixed your traffic. Real GSC data, not estimates."
      />
      <meta
        property="og:title"
        content={`${appName} — See which pages lost traffic. Fix them. Prove it worked.`}
      />
      <meta
        property="og:description"
        content="Diagnose GSC traffic drops, generate AI drafts ranked by impact, publish to WordPress, and prove what worked with before-after ROI tracking. Free to start."
      />
      <meta property="og:type" content="website" />
      <meta property="og:url" content={canonicalUrl} />
      <meta property="og:image" content={`${appUrl}/og/og-welcome-v2.png`} />
      <meta property="og:image:alt" content={`${appName} — SEO ROI Platform for WordPress`} />
      <meta property="og:image:width" content="1200" />
      <meta property="og:image:height" content="630" />
      <meta name="twitter:card" content="summary_large_image" />
      <meta
        name="twitter:title"
        content={`${appName} — See which pages lost traffic. Fix them. Prove it worked.`}
      />
      <meta
        name="twitter:description"
        content="Diagnose GSC traffic drops, generate AI drafts ranked by impact, publish to WordPress, and prove what worked with before-after ROI tracking. Free to start."
      />
      <meta name="twitter:image" content={`${appUrl}/og/og-welcome-v2.png`} />
      <script type="application/ld+json">
        {JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'WebSite',
          '@id': `${appUrl}/#website`,
          name: appName,
          url: appUrl,
          description:
            'SEO ROI platform for WordPress that connects your real Google data to GPT-4o-mini content fixes and proves they worked',
        })}
      </script>
      {/* R3SEO-007: Organization is the single source of truth in app.blade.php
           (with @id, logo, sameAs). Do NOT re-emit it here — two Organization nodes
           with conflicting descriptions break Google's entity graph. */}
      <script type="application/ld+json">
        {JSON.stringify({
          '@context': 'https://schema.org',
          ...softwareApplicationBase({
            name: appName,
            url: appUrl,
            description:
              'SEO ROI platform for WordPress with Google Search Console integration, AI draft generation, and ROI tracking.',
            image: `${appUrl}/og/og-default-v2.png`,
            screenshot: `${appUrl}/og/og-default-v2.png`,
          }),
          description:
            'SEO ROI platform for WordPress with Google Search Console integration, AI draft generation, and ROI tracking.',
          // F5SEO-004: derive highPrice + offerCount from the actual tiers array so
          // the schema stays in sync with the pricing section without a separate prop.
          offers: {
            '@type': 'AggregateOffer',
            lowPrice: '0',
            highPrice: String(
              Math.max(
                0,
                ...pricingTiers.map((t) => parseFloat(t.price.replace(/[^0-9.]/g, '')) || 0),
              ),
            ),
            priceCurrency: 'USD',
            offerCount: String(pricingTiers.length),
            // TSEO-02: route through buildOffer so each child Offer carries
            // availability + priceValidUntil (required for price rich result eligibility).
            offers: pricingTiers.map((tier) =>
              buildOffer({
                name: tier.name,
                price: tier.price.replace('$', ''),
                priceCurrency: 'USD',
              }),
            ),
          },
          // R3SEO-011: only emit aggregateRating when >= AGGREGATE_RATING_MIN_COUNT
          // attributable testimonials exist (rating > 0 AND non-null source).
          // Self-serving snippets from a handful of seed testimonials attract
          // Google quality rater scrutiny; a minimum count + source attribution
          // signals genuine third-party provenance.
          ...(testimonials.length >= AGGREGATE_RATING_MIN_COUNT &&
          testimonials.every(
            (t) => typeof t.rating === 'number' && t.rating > 0 && t.source != null,
          )
            ? {
                aggregateRating: {
                  '@type': 'AggregateRating',
                  ratingValue: parseFloat(
                    (
                      testimonials.reduce((sum, t) => sum + (Number(t.rating) || 0), 0) /
                      testimonials.length
                    ).toFixed(1),
                  ),
                  reviewCount: testimonials.length,
                  bestRating: 5,
                  worstRating: 1,
                },
              }
            : {}),
        })}
      </script>
      <script type="application/ld+json">
        {JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'WebPage',
          '@id': `${appUrl}/#webpage`,
          url: appUrl,
          name: `${appName} — See which pages lost traffic. Fix them. Prove it worked.`,
          description:
            'SEO ROI platform for WordPress. Connect Google Search Console, diagnose traffic changes, generate AI content fixes, publish to WordPress, and track ROI on every change.',
          isPartOf: {
            '@type': 'WebSite',
            '@id': `${appUrl}/#website`,
            name: appName,
            url: appUrl,
          },
          about: {
            '@type': 'SoftwareApplication',
            name: appName,
          },
          speakable: {
            '@type': 'SpeakableSpecification',
            cssSelector: ['h1', 'h2', '[data-speakable]'],
          },
        })}
      </script>
      <script type="application/ld+json">
        {JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'BreadcrumbList',
          itemListElement: [{ '@type': 'ListItem', position: 1, name: 'Home', item: appUrl }],
        })}
      </script>
      <script type="application/ld+json">
        {JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'ItemList',
          name: `${appName} Key Features`,
          description: 'Core features of the RankWizAI SEO ROI platform for WordPress',
          itemListElement: features.map((feature, index) => ({
            '@type': 'ListItem',
            position: index + 1,
            name: feature.title,
            description: feature.description,
          })),
        })}
      </script>
    </Head>
  );
}
