import {
  ArrowRight,
  BarChart2,
  CheckCircle2,
  ChevronDown,
  DollarSign,
  Globe,
  Lock,
  Shield,
  Sparkles,
  TrendingUp,
  Zap,
} from 'lucide-react';

import { useState } from 'react';

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

import { ComparisonTable } from '@/Components/marketing/ComparisonTable';
import { ComplementWorkflowDiagram } from '@/Components/marketing/ComplementWorkflowDiagram';
import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { BYOK_COST_RANGE } from '@/config/plan-limits';
import { competitors, formatLastVerified } from '@/data/competitors';
import { trackEvent } from '@/lib/analytics';
import { COMPARISON_CTA_CLICKED } from '@/lib/event-catalog';
import { softwareApplicationBase } from '@/lib/schema';
import { type PageProps } from '@/types';

interface ComparisonProps {
  canLogin: boolean;
  canRegister: boolean;
  competitor: string;
  pro_price?: number;
}

function safeJsonLd(data: unknown): string {
  return JSON.stringify(data)
    .replace(/&/g, '\u0026')
    .replace(/</g, '\u003c')
    .replace(/>/g, '\u003e')
    .replace(/\//g, '\u002f');
}

function buildSavingsExamples(proPrice: number) {
  return [
    {
      icon: DollarSign,
      title: 'Pay Only for What You Use',
      description: `With RankWiz's BYOK model, you pay OpenAI directly — typically ${BYOK_COST_RANGE}. No per-word markup, no tiered pricing based on usage.`,
    },
    {
      icon: Lock,
      title: 'Full Cost Control',
      description:
        'Set spending limits in your OpenAI account. You have complete visibility into AI usage and costs. No surprise bills.',
    },
    {
      icon: Shield,
      title: 'Transparent Pricing',
      description: `RankWiz subscription starts at free, Pro at $${proPrice}/mo. AI costs are separate and under your control. No hidden fees.`,
    },
  ];
}

function SwitchingFaqItem({ question, answer }: { question: string; answer: string }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="rounded-lg border bg-card">
      <button
        type="button"
        className="flex w-full items-center justify-between rounded-lg p-4 text-left hover:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
        onClick={() => setOpen(!open)}
        aria-expanded={open}
      >
        <span className="pr-4 font-semibold">{question}</span>
        <ChevronDown
          className={`h-4 w-4 shrink-0 transition-transform ${open ? 'rotate-180' : ''}`}
          aria-hidden="true"
        />
      </button>
      {open && (
        <div className="border-t px-4 pb-4 pt-3 text-sm text-muted-foreground">{answer}</div>
      )}
    </div>
  );
}

type ComparisonComponent = ((props: ComparisonProps) => JSX.Element | null) & {
  disableGlobalUi?: boolean;
};

const Comparison: ComparisonComponent = ({ canLogin, canRegister, competitor, pro_price }) => {
  const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';
  const { app_url } = usePage<PageProps>().props;
  const config = competitors[competitor];
  const savingsExamples = buildSavingsExamples(pro_price ?? 49);

  if (!config) {
    return null;
  }

  return (
    <>
      <Head title={`${appName} vs ${config.name}`}>
        <link rel="canonical" href={`${app_url}/vs/${competitor}`} />
        <meta name="description" content={config.metaDescription} />
        <meta property="og:title" content={`${appName} vs ${config.name} — Feature Comparison`} />
        <meta property="og:description" content={config.metaDescription} />
        <meta property="og:type" content="website" />
        <meta property="og:image" content={`/og-${config.ogImageSlug}.svg`} />
        <meta
          property="og:image:alt"
          content={`${appName} vs ${config.name} — SEO Tool Comparison`}
        />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:site" content="@rankwiz_ai" />
        <meta name="twitter:title" content={`${appName} vs ${config.name}`} />
        <meta name="twitter:description" content={config.metaDescription} />
        <meta name="twitter:image" content={`/og-${config.ogImageSlug}.svg`} />
        <meta name="twitter:image:width" content="1200" />
        <meta name="twitter:image:height" content="630" />
        <meta property="og:image:width" content="1200" />
        <meta property="og:image:height" content="630" />
        <script type="application/ld+json">
          {safeJsonLd({
            '@context': 'https://schema.org',
            '@type': 'WebPage',
            name: `${appName} vs ${config.name} — Feature Comparison`,
            description: config.description,
            url: `${app_url}/vs/${competitor}`,
            about: [
              { '@type': 'SoftwareApplication', name: appName },
              { '@type': 'SoftwareApplication', name: config.name },
            ],
          })}
        </script>
        <script type="application/ld+json">
          {safeJsonLd({
            '@context': 'https://schema.org',
            ...softwareApplicationBase(appName),
            offers: {
              '@type': 'Offer',
              price: '0',
              priceCurrency: 'USD',
            },
          })}
        </script>
        <script type="application/ld+json">
          {safeJsonLd({
            '@context': 'https://schema.org',
            '@type': 'BreadcrumbList',
            itemListElement: [
              {
                '@type': 'ListItem',
                position: 1,
                name: 'Home',
                item: `${app_url}/`,
              },
              {
                '@type': 'ListItem',
                position: 2,
                name: 'Compare',
                item: `${app_url}/compare`,
              },
              {
                '@type': 'ListItem',
                position: 3,
                name: `${appName} vs ${config.name}`,
                item: `${app_url}/vs/${competitor}`,
              },
            ],
          })}
        </script>
        <script type="application/ld+json">
          {safeJsonLd({
            '@context': 'https://schema.org',
            '@type': 'ItemList',
            name: `${appName} vs ${config.name} — Feature Comparison Table`,
            description: `Detailed feature comparison between ${appName} and ${config.name}`,
            numberOfItems: config.features.length,
            itemListElement: config.features.map((f, i) => ({
              '@type': 'ListItem',
              position: i + 1,
              name: f.feature,
              description: `${appName}: ${f.rankwiz === true ? 'Yes' : f.rankwiz === false ? 'No' : f.rankwiz} | ${config.name}: ${f.competitor === true ? 'Yes' : f.competitor === false ? 'No' : f.competitor}`,
            })),
          })}
        </script>
      </Head>

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

        <main id="main-content">
          {/* Breadcrumb */}
          <nav aria-label="Breadcrumb" className="container pt-6">
            <ol className="flex items-center gap-2 text-sm text-muted-foreground">
              <li>
                <Link href={route('welcome')} className="transition-colors hover:text-foreground">
                  Home
                </Link>
              </li>
              <li aria-hidden="true" className="select-none">
                ›
              </li>
              <li>
                <Link href={route('compare')} className="transition-colors hover:text-foreground">
                  Compare
                </Link>
              </li>
              <li aria-hidden="true" className="select-none">
                ›
              </li>
              <li className="font-medium text-foreground" aria-current="page">
                vs {config.name}
              </li>
            </ol>
          </nav>

          {/* Hero Section */}
          <section className="container py-16 text-center">
            <div className="mx-auto max-w-3xl space-y-6">
              <div className="animate-fade-in-up inline-flex items-center gap-2 rounded-full border bg-muted px-4 py-1.5 text-sm text-muted-foreground">
                <TrendingUp className="h-4 w-4" aria-hidden="true" />
                Feature Comparison
              </div>
              <h1 className="animate-fade-in-up animate-delay-100 text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl">
                {appName} vs {config.name}
                <br />
                <span className="text-primary">{config.tagline}</span>
              </h1>
              <p className="animate-fade-in-up animate-delay-200 text-lg text-muted-foreground md:text-xl">
                {config.description}
              </p>
              <p className="text-sm text-muted-foreground mt-2">
                Feature data last verified {formatLastVerified(config.lastVerified)}
              </p>
            </div>
          </section>

          {/* BYOK Savings Section — only for AI content tool competitors */}
          {config.showByokSection !== false && (
            <section className="container py-16">
              <div className="mx-auto max-w-5xl">
                <div className="mb-8 text-center">
                  <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/5 px-3 py-1 text-sm font-medium text-primary">
                    No AI markup
                  </div>
                  <h2 className="mb-4 text-3xl font-bold tracking-tight">
                    AI Drafts Included — Add Your Own Key for Unlimited
                  </h2>
                  <p className="text-lg text-muted-foreground">
                    Every plan includes bundled AI drafts. Need more? Add your own OpenAI key for
                    unlimited drafts at {BYOK_COST_RANGE} — no markup, full spending control.
                  </p>
                </div>
                <div className="grid gap-6 md:grid-cols-3">
                  {savingsExamples.map((example, index) => (
                    <Card key={index} className="transition-shadow hover:shadow-lg">
                      <CardHeader>
                        <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                          <example.icon className="h-6 w-6 text-primary" aria-hidden="true" />
                        </div>
                        <CardTitle className="text-xl">{example.title}</CardTitle>
                      </CardHeader>
                      <CardContent>
                        <p className="text-base leading-relaxed text-muted-foreground">
                          {example.description}
                        </p>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </div>
            </section>
          )}

          {/* Better Together — for on-page plugin competitors (Yoast, Rank Math) */}
          {config.alternativeSection === 'complement' && (
            <section className="container py-16">
              <div className="mx-auto max-w-5xl">
                <div className="mb-8 text-center">
                  <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/5 px-3 py-1 text-sm font-medium text-primary">
                    Better Together
                  </div>
                  <h2 className="mb-4 text-3xl font-bold tracking-tight">
                    {config.name} Handles On-Page. {appName} Handles Everything Else.
                  </h2>
                  <p className="text-lg text-muted-foreground">
                    Keep {config.name} for meta tags and schema. Add {appName} for the analytics, AI
                    content, and ROI tracking that {config.name} doesn&apos;t do.
                  </p>
                </div>
                {config.partnerInfo && (
                  <ComplementWorkflowDiagram
                    competitorName={config.name}
                    appName={appName}
                    workflowNote={config.partnerInfo.workflowNote}
                  />
                )}
                <div className="grid gap-6 md:grid-cols-3">
                  <Card className="transition-shadow hover:shadow-lg">
                    <CardHeader>
                      <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                        <BarChart2 className="h-6 w-6 text-primary" aria-hidden="true" />
                      </div>
                      <CardTitle className="text-xl">GSC Traffic Analysis</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-base leading-relaxed text-muted-foreground">
                        {config.name} shows basic GSC metrics. {appName} runs before/after traffic
                        analysis, detects anomalies, and surfaces striking-distance keywords you
                        should target next.
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="transition-shadow hover:shadow-lg">
                    <CardHeader>
                      <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                        <Sparkles className="h-6 w-6 text-primary" aria-hidden="true" />
                      </div>
                      <CardTitle className="text-xl">AI Content Drafts</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-base leading-relaxed text-muted-foreground">
                        Generate full content rewrites, meta descriptions, and title tags based on
                        your actual GSC data. Included on every plan — or bring your own OpenAI key
                        for unlimited drafts.
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="transition-shadow hover:shadow-lg">
                    <CardHeader>
                      <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                        <TrendingUp className="h-6 w-6 text-primary" aria-hidden="true" />
                      </div>
                      <CardTitle className="text-xl">ROI Tracking</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-base leading-relaxed text-muted-foreground">
                        Know which SEO changes actually moved the needle. {appName} tracks
                        before/after metrics on every recommendation you apply — at 7, 14, 30, and
                        90 days.
                      </p>
                    </CardContent>
                  </Card>
                </div>
              </div>
            </section>
          )}

          {/* WordPress-First Advantage — for SEO suite competitors (Ahrefs, Semrush, etc.) */}
          {config.alternativeSection === 'wordpress-first' && (
            <section className="container py-16">
              <div className="mx-auto max-w-5xl">
                <div className="mb-8 text-center">
                  <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/5 px-3 py-1 text-sm font-medium text-primary">
                    WordPress-First
                  </div>
                  <h2 className="mb-4 text-3xl font-bold tracking-tight">
                    Built for WordPress. Not Bolted On.
                  </h2>
                  <p className="text-lg text-muted-foreground">
                    {config.name} is a general-purpose SEO suite. {appName} is purpose-built for
                    WordPress sites — from GSC analysis to one-click publishing.
                  </p>
                </div>
                <div className="grid gap-6 md:grid-cols-3">
                  <Card className="transition-shadow hover:shadow-lg">
                    <CardHeader>
                      <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                        <Globe className="h-6 w-6 text-primary" aria-hidden="true" />
                      </div>
                      <CardTitle className="text-xl">Direct WP Publishing</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-base leading-relaxed text-muted-foreground">
                        Publish AI-generated content directly to your WordPress site with one click.
                        No copy-pasting, no manual transfers. Bulk publish up to 50 drafts in
                        parallel.
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="transition-shadow hover:shadow-lg">
                    <CardHeader>
                      <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                        <DollarSign className="h-6 w-6 text-primary" aria-hidden="true" />
                      </div>
                      <CardTitle className="text-xl">BYOK Cost Savings</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-base leading-relaxed text-muted-foreground">
                        AI drafts are included on every plan. Need more? Add your own OpenAI key for
                        unlimited drafts at {BYOK_COST_RANGE} — no markup, full spending control.
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="transition-shadow hover:shadow-lg">
                    <CardHeader>
                      <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                        <BarChart2 className="h-6 w-6 text-primary" aria-hidden="true" />
                      </div>
                      <CardTitle className="text-xl">GSC-Native Analysis</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-base leading-relaxed text-muted-foreground">
                        Built on real Google Search Console data — not third-party estimates.
                        Before/after traffic analysis, anomaly detection, and keyword opportunities
                        from your actual search performance.
                      </p>
                    </CardContent>
                  </Card>
                </div>
              </div>
            </section>
          )}

          {/* Comparison Table */}
          <section className="container py-16">
            <div className="mx-auto max-w-5xl">
              <div className="mb-8 text-center">
                <h2 className="mb-4 text-3xl font-bold tracking-tight">Feature Comparison</h2>
                <p className="text-lg text-muted-foreground">
                  See how {appName} stacks up against {config.name}
                </p>
              </div>
              <Card>
                <CardContent className="p-0">
                  <ComparisonTable features={config.features} competitorName={config.name} />
                </CardContent>
              </Card>
              {config.features.some(
                (f) => f.rankwiz === false && typeof f.competitor !== 'string',
              ) && (
                <div className="mt-6 rounded-lg border border-dashed bg-muted/30 p-6 text-sm text-muted-foreground">
                  <p>
                    <strong className="text-foreground">A note on scope:</strong> RankWiz is
                    purpose-built for <em>content performance</em> &mdash; the intersection of
                    Google Search Console data, WordPress content, and AI-driven fixes. Features
                    like backlink analysis and site auditing: RankWiz is laser-focused on WordPress
                    traffic ROI. If you manage external link-building as a core KPI, you may want to
                    keep your {config.name} subscription alongside RankWiz. They complement each
                    other well.
                  </p>
                </div>
              )}
            </div>
          </section>

          {/* Additional Benefits */}
          <section className="container py-16">
            <div className="mx-auto max-w-5xl">
              <Card className="border-primary/20 bg-linear-to-r from-primary/5 via-primary/3 to-background">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2 text-2xl">
                    <Zap className="h-6 w-6 text-primary" aria-hidden="true" />
                    Why Choose RankWiz?
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <ul className="space-y-3 text-base text-muted-foreground">
                    <li className="flex items-start gap-2">
                      <ArrowRight
                        className="mt-0.5 h-5 w-5 shrink-0 text-primary"
                        aria-hidden="true"
                      />
                      <span>
                        <strong className="text-foreground">WordPress-First:</strong> Stop
                        copy-pasting content between tools. Approve an AI draft and it publishes
                        directly to your WordPress site — no manual transfers, no formatting
                        cleanup.
                      </span>
                    </li>
                    <li className="flex items-start gap-2">
                      <ArrowRight
                        className="mt-0.5 h-5 w-5 shrink-0 text-primary"
                        aria-hidden="true"
                      />
                      <span>
                        <strong className="text-foreground">Real Data:</strong> Stop guessing which
                        pages to fix. Your Google Search Console data surfaces exact pages losing
                        clicks, striking-distance keywords, and anomalies — so you work on what will
                        actually move your rankings.
                      </span>
                    </li>
                    <li className="flex items-start gap-2">
                      <ArrowRight
                        className="mt-0.5 h-5 w-5 shrink-0 text-primary"
                        aria-hidden="true"
                      />
                      <span>
                        <strong className="text-foreground">Transparent Costs:</strong> Stop paying
                        per-word markups on AI content. Bring your own OpenAI key and generate
                        unlimited drafts at {BYOK_COST_RANGE} — with full visibility into every
                        dollar spent.
                      </span>
                    </li>
                    <li className="flex items-start gap-2">
                      <ArrowRight
                        className="mt-0.5 h-5 w-5 shrink-0 text-primary"
                        aria-hidden="true"
                      />
                      <span>
                        <strong className="text-foreground">ROI Tracking:</strong> Stop wondering if
                        your SEO work is paying off. Every applied recommendation is tracked at 7,
                        14, 30, and 90 days — so you can see the traffic lift each change delivered.
                      </span>
                    </li>
                  </ul>
                </CardContent>
              </Card>
            </div>
          </section>

          {/* Compare with Other Tools */}
          <section className="container py-16">
            <div className="mx-auto max-w-5xl">
              <div className="mb-8 text-center">
                <h2 className="mb-4 text-2xl font-bold tracking-tight">
                  Compare RankWiz with Other Tools
                </h2>
                <p className="text-muted-foreground">
                  See how {appName} compares to other popular SEO tools
                </p>
              </div>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {Object.entries(competitors)
                  .filter(([slug]) => slug !== competitor)
                  .map(([slug, comp]) => (
                    <Card key={slug} className="transition-shadow hover:shadow-lg">
                      <CardContent className="p-6">
                        <Link
                          href={route('comparison', { competitor: slug })}
                          className="group block"
                        >
                          <h3 className="mb-1 text-lg font-semibold group-hover:text-primary">
                            {appName} vs {comp.name}
                          </h3>
                          <p className="text-sm text-muted-foreground">{comp.tagline}</p>
                        </Link>
                      </CardContent>
                    </Card>
                  ))}
              </div>
            </div>
          </section>

          {/* Switching is Easy */}
          {config.switchingFaq && config.switchingFaq.length > 0 && (
            <section className="container py-16">
              <div className="mx-auto max-w-5xl">
                <div className="mb-8 text-center">
                  <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/5 px-3 py-1 text-sm font-medium text-primary">
                    <CheckCircle2 className="h-4 w-4" aria-hidden="true" />
                    Easy Switch
                  </div>
                  <h2 className="mb-4 text-3xl font-bold tracking-tight">
                    Switching from {config.name} Is Easy
                  </h2>
                  <p className="text-lg text-muted-foreground">
                    No data migration. No lock-in. Run both tools side-by-side if you want.
                  </p>
                </div>
                <div className="grid gap-6 md:grid-cols-3">
                  <Card className="text-center">
                    <CardContent className="pt-6">
                      <p className="mb-2 text-3xl font-bold text-primary">&lt; 5 min</p>
                      <p className="text-sm text-muted-foreground">
                        Setup time — OAuth + WordPress plugin
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="text-center">
                    <CardContent className="pt-6">
                      <p className="mb-2 text-3xl font-bold text-primary">0 exports</p>
                      <p className="text-sm text-muted-foreground">
                        No data migration needed — GSC is the source
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="text-center">
                    <CardContent className="pt-6">
                      <p className="mb-2 text-3xl font-bold text-primary">Side-by-side</p>
                      <p className="text-sm text-muted-foreground">
                        Run both tools in parallel — no conflicts
                      </p>
                    </CardContent>
                  </Card>
                </div>
                <div className="mt-8 space-y-3">
                  {config.switchingFaq.map((faq, i) => (
                    <SwitchingFaqItem key={i} question={faq.question} answer={faq.answer} />
                  ))}
                </div>
              </div>
            </section>
          )}

          {/* CTA Section */}
          <section className="container py-24">
            <div className="rounded-2xl bg-linear-to-r from-primary/10 via-primary/5 to-background p-12 text-center">
              <h2 className="mb-4 text-3xl font-bold tracking-tight">Ready to Try {appName}?</h2>
              <p className="mb-8 text-lg text-muted-foreground">
                Start analyzing your WordPress site's traffic for free. No credit card required.
              </p>
              <div className="flex flex-wrap items-center justify-center gap-4">
                {canRegister && (
                  <Button size="lg" asChild>
                    <Link
                      href={route('register')}
                      onClick={() => trackEvent(COMPARISON_CTA_CLICKED, { competitor })}
                    >
                      Start Free Analysis
                      <ArrowRight className="ml-2 h-4 w-4" aria-hidden="true" />
                    </Link>
                  </Button>
                )}
                <Button size="lg" variant="outline" asChild>
                  <Link href={route('features')}>View All Features</Link>
                </Button>
              </div>
            </div>
          </section>
        </main>

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

Comparison.disableGlobalUi = true;

export default Comparison;
