import { ArrowRight } from 'lucide-react';

import { Head, Link, usePage } from '@inertiajs/react';

import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { trackEvent } from '@/lib/analytics';
import { CASE_STUDY_CTA_CLICKED } from '@/lib/event-catalog';
import { type PageProps } from '@/types';

interface CaseStudyMetric {
  label: string;
  value: string;
}

interface CaseStudy {
  id?: number;
  company_type: string;
  result: string;
  challenge: string;
  approach: string;
  outcome: string;
  timeline?: string;
  key_metrics?: CaseStudyMetric[];
  tools_used?: string[];
}

interface CaseStudiesProps {
  can_login: boolean;
  can_register: boolean;
  case_studies: CaseStudy[];
}

const PLACEHOLDER_CASE_STUDIES: CaseStudy[] = [
  {
    company_type: 'B2B SaaS Blog',
    result: '+47% organic traffic in 90 days',
    challenge:
      'Traffic had stagnated despite a consistent publishing cadence. The team had no clear signal on which pages were underperforming or why.',
    approach:
      'Connected Google Search Console and ran a RankWiz analysis comparing the last 90 days vs the prior period. The tool flagged 12 pages with high impressions but poor CTR — all ranking in positions 11–20.',
    outcome:
      '9 of those 12 pages moved to page 1 within 90 days after applying AI-drafted meta tag and content section rewrites. Organic traffic increased 47% quarter-over-quarter.',
    timeline: '90 days',
    key_metrics: [
      { label: 'Traffic increase', value: '+47%' },
      { label: 'Pages to page 1', value: '9 of 12' },
      { label: 'Time to results', value: '90 days' },
    ],
    tools_used: ['Traffic Analysis', 'AI Content Drafts', 'ROI Tracking'],
  },
  {
    company_type: 'WordPress E-commerce Store',
    result: 'Recovered –63% traffic loss in 6 weeks',
    challenge:
      'A Google algorithm update caused a sudden drop in organic traffic to category pages. The store had no way to identify which pages were hit or what changed.',
    approach:
      'RankWiz anomaly detection flagged the drop within 48 hours. Traffic Alert notifications identified 8 category pages with ≥20% week-over-week declines. Freshness analysis showed most of those pages had not been updated in over a year.',
    outcome:
      'After refreshing content on the flagged pages using AI-drafted updates, traffic recovered to pre-update levels within 6 weeks. The store now runs weekly anomaly scans automatically.',
    timeline: '6 weeks',
    key_metrics: [
      { label: 'Traffic recovered', value: '100%' },
      { label: 'Pages fixed', value: '8' },
      { label: 'Detection time', value: '48 hrs' },
    ],
    tools_used: ['Anomaly Detection', 'Freshness Analysis', 'AI Content Drafts'],
  },
  {
    company_type: 'SEO Agency (10 Client Sites)',
    result: '3× faster monthly reporting',
    challenge:
      'Preparing monthly SEO reports for 10 client sites took 3 days each month. Manually exporting GSC data, comparing periods, and writing summaries left little time for strategy.',
    approach:
      'Connected all 10 sites to RankWiz. Automated analysis runs generate winners/losers summaries, recommendation queues, and ROI snapshots for each client on a set schedule.',
    outcome:
      'Reporting time dropped from 3 days to under 1 day. Clients now receive data-backed reports with before/after performance metrics for every recommendation applied.',
    timeline: 'Ongoing',
    key_metrics: [
      { label: 'Reporting time', value: '–3× faster' },
      { label: 'Sites managed', value: '10' },
      { label: 'Manual hours saved', value: '~16/mo' },
    ],
    tools_used: ['Multi-site Dashboard', 'Analysis Runs', 'ROI Tracking'],
  },
];

type CaseStudiesComponent = ((props: CaseStudiesProps) => JSX.Element) & {
  disableGlobalUi?: boolean;
};

const CaseStudiesIndex: CaseStudiesComponent = ({ can_login, can_register, case_studies }) => {
  const { app_url } = usePage<PageProps>().props;
  const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';

  const hasRealStudies = case_studies.length > 0;
  const displayStudies = hasRealStudies ? case_studies : PLACEHOLDER_CASE_STUDIES;

  return (
    <>
      <Head title="Case Studies">
        <link rel="canonical" href={`${app_url}/case-studies`} />
        <meta
          name="description"
          content={`See how ${appName} helps WordPress teams recover lost traffic, fix content gaps, and prove SEO ROI with real Google Search Console data.`}
        />
        <meta property="og:title" content={`Case Studies — ${appName}`} />
        <meta
          property="og:description"
          content={`Results from teams using ${appName} to fix SEO issues and prove ROI.`}
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/case-studies`} />
        <meta property="og:image" content={`${app_url}/og-image.png`} />
        <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:site" content="@rankwiz_ai" />
        <meta name="twitter:title" content={`Case Studies — ${appName}`} />
        <meta
          name="twitter:description"
          content={`Results from teams using ${appName} to fix SEO issues and prove ROI.`}
        />
        <meta name="twitter:image" content={`${app_url}/og-image.png`} />
      </Head>

      {hasRealStudies && (
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'ItemList',
            name: `${appName} Customer Case Studies`,
            url: `${app_url}/case-studies`,
            itemListElement: case_studies.map((study, index) => ({
              '@type': 'ListItem',
              position: index + 1,
              item: {
                '@type': 'Article',
                headline: `${study.company_type} — ${study.result}`,
                description: study.challenge,
                articleBody: `${study.approach} ${study.outcome}`,
                publisher: {
                  '@type': 'Organization',
                  name: appName,
                  url: app_url,
                },
                ...(study.timeline && { datePublished: study.timeline }),
              },
            })),
          })}
        </script>
      )}

      <div className="min-h-screen bg-gradient-to-b from-background to-muted/30">
        <MarketingNav canLogin={can_login} canRegister={can_register} />

        <main id="main-content">
          {/* Hero */}
          <section className="container py-16 text-center">
            <h1 className="text-4xl font-bold tracking-tight md:text-5xl">
              See {appName} in Action
            </h1>
            <p className="mx-auto mt-4 max-w-2xl text-lg text-muted-foreground">
              {hasRealStudies ? (
                <>
                  Real results from teams that connected their Google Search Console data and let{' '}
                  {appName} find exactly what to fix.
                </>
              ) : (
                <>
                  Illustrative examples of results you could achieve — not verified customer
                  results. Connect your Google Search Console data and let {appName} find exactly
                  what to fix.
                </>
              )}
            </p>
          </section>

          {/* Case Studies Grid */}
          <section className="container max-w-5xl py-8">
            <div className="grid gap-8">
              {displayStudies.map((study, index) => (
                <article
                  key={study.id ?? `${study.company_type}-${index}`}
                  className="rounded-xl border bg-card p-8"
                  aria-label={`Case study: ${study.company_type}`}
                >
                  <div className="mb-4 flex items-start justify-between gap-4">
                    <span className="text-sm font-medium text-muted-foreground">
                      {study.company_type}
                    </span>
                    <span className="inline-flex shrink-0 items-center rounded-full bg-primary/10 px-3 py-1 text-sm font-semibold text-primary">
                      {study.result}
                    </span>
                  </div>

                  {study.key_metrics && study.key_metrics.length > 0 && (
                    <div className="mb-4 flex flex-wrap gap-3">
                      {study.key_metrics.map((metric) => (
                        <div
                          key={metric.label}
                          className="rounded-lg bg-muted/60 px-3 py-2 text-center"
                        >
                          <p className="text-lg font-bold text-foreground">{metric.value}</p>
                          <p className="text-xs text-muted-foreground">{metric.label}</p>
                        </div>
                      ))}
                    </div>
                  )}

                  {study.tools_used && study.tools_used.length > 0 && (
                    <div className="mb-4 flex flex-wrap gap-2">
                      {study.tools_used.map((tool) => (
                        <span
                          key={tool}
                          className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium text-muted-foreground"
                        >
                          {tool}
                        </span>
                      ))}
                    </div>
                  )}

                  <div className="space-y-4 text-sm text-muted-foreground">
                    <div>
                      <p className="mb-1 font-semibold text-foreground">The Challenge</p>
                      <p>{study.challenge}</p>
                    </div>
                    <div>
                      <p className="mb-1 font-semibold text-foreground">The Approach</p>
                      <p>{study.approach}</p>
                    </div>
                    <div>
                      <p className="mb-1 font-semibold text-foreground">The Outcome</p>
                      <p>{study.outcome}</p>
                    </div>
                  </div>
                </article>
              ))}
            </div>
            <p className="mt-6 text-center text-sm text-muted-foreground">
              Individual results may vary based on site size, content quality, and implementation.
            </p>
          </section>

          {/* CTA */}
          <section className="container max-w-2xl py-16 text-center">
            <h2 className="text-3xl font-bold tracking-tight">Ready to see results like these?</h2>
            <p className="mt-3 text-lg text-muted-foreground">
              Connect your Google Search Console and get your first analysis in minutes.
            </p>
            <div className="mt-8 flex flex-wrap items-center justify-center gap-4">
              <Link
                href={route('register')}
                className="inline-flex items-center justify-center rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground transition-colors duration-150 hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                onClick={() =>
                  trackEvent(CASE_STUDY_CTA_CLICKED, { has_real_data: hasRealStudies })
                }
              >
                Start Free Analysis
                <ArrowRight className="ml-2 h-4 w-4" aria-hidden="true" />
              </Link>
              <Link
                href={route('pricing')}
                className="inline-flex items-center justify-center rounded-lg border px-6 py-3 text-sm font-medium transition-colors duration-150 hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              >
                View Pricing
              </Link>
            </div>
          </section>
        </main>

        <MarketingFooter />
      </div>
    </>
  );
};

CaseStudiesIndex.disableGlobalUi = true;

export default CaseStudiesIndex;
