import {
  AlertTriangle,
  BarChart2,
  CheckCircle2,
  ChevronDown,
  DollarSign,
  GitMerge,
  ShoppingCart,
  Sparkles,
  Target,
  TrendingUp,
  Wand2,
} from 'lucide-react';

import { useState } from 'react';

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

import { AnalysisMockup } from '@/Components/marketing/AnalysisMockup';
import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { Button } from '@/Components/ui/button';
import { Card, CardContent } from '@/Components/ui/card';
import { CTA_LABELS } from '@/config/cta-labels';
import { trackEvent } from '@/lib/analytics';
import {
  MARKETING_REGISTER_CLICK_FROM_USE_CASE_PAGE,
  USE_CASE_CTA_CLICKED,
  USE_CASE_TO_BLOG_CLICK,
} from '@/lib/event-catalog';
import { type PageProps } from '@/types';

interface EcommerceProps {
  can_login: boolean;
  can_register: boolean;
}

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

const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';

const painPoints = [
  {
    icon: TrendingUp,
    title: 'Product Pages Losing Rankings',
    description:
      'High-converting product and category pages slip out of the top 10 without warning. You see the revenue impact but cannot trace it back to the ranking cause.',
  },
  {
    icon: ShoppingCart,
    title: 'Thin Content on Category Pages',
    description:
      'Category pages with minimal copy underperform in search — but you have hundreds of them. Finding and prioritizing which ones to fix is a full-time job.',
  },
  {
    icon: BarChart2,
    title: 'Cannot Connect GSC Drops to Revenue',
    description:
      'Google Search Console shows traffic. Your analytics shows revenue. Connecting a GSC click decline to an actual sales impact requires manual work no one has time for.',
  },
];

const valueProps = [
  {
    icon: Target,
    title: 'Striking Distance Opportunities',
    description:
      'Automatically surface product and category queries ranking in positions 11-20 with high impression volume. These are your fastest-win ranking opportunities.',
  },
  {
    icon: ShoppingCart,
    title: 'Thin Content Detection',
    description:
      'Identify every page below your content depth threshold. Prioritized by traffic potential so your content team works on pages that actually move revenue.',
  },
  {
    icon: DollarSign,
    title: 'Closed-Loop ROI: GSC → Fix → Proof',
    description:
      'When you apply an optimization, RankWiz captures the GSC baseline. It then tracks clicks, impressions, CTR, and position changes at 7, 14, 30, and 90 days — closing the loop from traffic drop to measurable revenue recovery.',
  },
  {
    icon: GitMerge,
    title: 'Cannibalization Detection',
    description:
      "Automatically find product and category pages competing for the same queries. Consolidate or redirect competing pages before they erode each other's rankings — critical for large ecommerce catalogs.",
  },
  {
    icon: AlertTriangle,
    title: 'Traffic Anomaly Alerts for Seasonal Drops',
    description:
      'Get immediate alerts when any page drops 20% or more in traffic. Seasonal shifts and algorithm updates are caught automatically — so you respond before the revenue impact compounds.',
  },
  {
    icon: Wand2,
    title: 'AI Draft Generation for Product Pages',
    description:
      'Generate optimized rewrites for product and category pages in bulk. Bring your own OpenAI key to keep costs predictable, then publish directly to WooCommerce with one click.',
  },
  {
    icon: Sparkles,
    title: 'GEO: Visibility in AI Shopping Assistants',
    description:
      'As shoppers use ChatGPT, Perplexity, and Google AI Overviews to research purchases, RankWiz scores your product and category pages across 6 Generative Engine Optimization (GEO) pillars to maximize AI search visibility.',
  },
];

const ecommerceFaqs = [
  {
    question: 'Does RankWiz work with WooCommerce?',
    answer:
      'Yes. RankWiz connects to any WordPress site via a lightweight plugin, including WooCommerce stores. It analyzes product pages, category pages, and blog content.',
  },
  {
    question: 'Can I track ROI on individual product page fixes?',
    answer:
      'Yes. When you apply a recommendation, RankWiz captures baseline GSC metrics. It then tracks clicks, impressions, CTR, and position changes at 7, 14, 30, and 90 days.',
  },
  {
    question: 'How does cannibalization detection work for product pages?',
    answer:
      'RankWiz analyzes your GSC query data to find product and category pages competing for the same search queries. It groups them into cannibalization cases with severity scores and suggests consolidation actions.',
  },
  {
    question: 'Can I manage multiple WooCommerce stores from one account?',
    answer:
      'Yes. Free plan covers 1 store. Pro plan supports up to 5 sites with 500 pages analyzed per run, ROI tracking, traffic anomaly alerts, and SERP content scoring. Team (Agency) plan includes unlimited sites, bulk AI draft generation, white-label reports, and team member seats — built for stores that need to scale across multiple properties.',
  },
];

function FaqItem({ 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>
  );
}

const Ecommerce: EcommerceComponent = ({ can_login, can_register }) => {
  const { app_url } = usePage<PageProps>().props;

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'WebPage',
    name: `${appName} for Ecommerce — Stop Losing Sales to SEO Gaps You Cannot See`,
    description:
      'RankWiz helps ecommerce stores recover lost rankings with striking distance keyword detection, thin content identification, and ROI tracking that connects SEO fixes to revenue impact.',
    url: `${app_url}/use-cases/ecommerce`,
  };

  const handleRegisterClick = () => {
    trackEvent(MARKETING_REGISTER_CLICK_FROM_USE_CASE_PAGE, { persona: 'ecommerce' });
  };

  return (
    <>
      <Head title={`${appName} for WooCommerce & Ecommerce — Stop Losing Sales to SEO Gaps`}>
        <meta
          name="description"
          content="RankWiz helps ecommerce stores recover lost rankings with striking distance keyword detection, thin content identification, and ROI tracking that connects SEO fixes to revenue impact."
        />
        <meta
          property="og:title"
          content={`${appName} for Ecommerce — Stop Losing Sales to SEO Gaps`}
        />
        <meta
          property="og:description"
          content="Recover lost rankings with striking distance keyword detection, thin content identification, and ROI tracking."
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/use-cases/ecommerce`} />
        <meta property="og:image" content={`${app_url}/og-image.png`} />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content={`${appName} for Ecommerce`} />
        <meta
          name="twitter:description"
          content="Stop losing sales to SEO gaps with AI-powered traffic analysis and content fixes."
        />
        <meta name="twitter:image" content={`${app_url}/og-image.png`} />
        <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" />
        <link rel="canonical" href={`${app_url}/use-cases/ecommerce`} />
        <script type="application/ld+json">{JSON.stringify(jsonLd)}</script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'BreadcrumbList',
            itemListElement: [
              { '@type': 'ListItem', position: 1, name: 'Home', item: `${app_url}/` },
              {
                '@type': 'ListItem',
                position: 2,
                name: 'Use Cases',
                item: `${app_url}/use-cases/ecommerce`,
              },
              {
                '@type': 'ListItem',
                position: 3,
                name: 'Ecommerce',
                item: `${app_url}/use-cases/ecommerce`,
              },
            ],
          })}
        </script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'FAQPage',
            mainEntity: ecommerceFaqs.map((faq) => ({
              '@type': 'Question',
              name: faq.question,
              acceptedAnswer: { '@type': 'Answer', text: faq.answer },
            })),
          })}
        </script>
      </Head>

      <div className="min-h-screen bg-background">
        <MarketingNav canLogin={can_login} canRegister={can_register} />

        <main id="main-content">
          {/* Hero Section */}
          <section className="px-4 py-20 text-center sm:px-6 lg:px-8">
            <div className="mx-auto max-w-4xl">
              <p className="mb-4 text-sm font-semibold uppercase tracking-widest text-primary">
                For WooCommerce &amp; Ecommerce Stores
              </p>
              <h1 className="mb-6 text-4xl font-extrabold tracking-tight text-foreground sm:text-5xl lg:text-6xl">
                Recover product page traffic before it costs you sales
              </h1>
              <p className="mx-auto mb-10 max-w-2xl text-xl text-muted-foreground">
                Connect your Google Search Console to your WooCommerce store. {appName} surfaces the
                ranking gaps costing you the most revenue, generates AI-powered fixes you can
                publish in one click, then tracks the traffic and revenue lift so you can prove
                every optimization paid off.
              </p>
              <div className="flex flex-col items-center justify-center gap-4 sm:flex-row">
                <Link href="/register" onClick={handleRegisterClick}>
                  <Button size="lg" className="px-8 text-base">
                    {CTA_LABELS.FREE_ENTRY}
                  </Button>
                </Link>
                <Link href="/pricing">
                  <Button size="lg" variant="outline" className="px-8 text-base">
                    {CTA_LABELS.USE_CASE_PRICING}
                  </Button>
                </Link>
              </div>
              <AnalysisMockup className="mx-auto mt-10 max-w-3xl" />
            </div>
          </section>

          {/* Platform Metrics Bar */}
          <section className="border-y bg-muted/30 px-4 py-6 sm:px-6 lg:px-8">
            <div className="mx-auto flex max-w-4xl flex-wrap items-center justify-center gap-8 text-center sm:gap-12">
              <div>
                <p className="text-2xl font-bold text-foreground">12+</p>
                <p className="text-xs text-muted-foreground">Recommendation types</p>
              </div>
              <div className="hidden h-8 w-px bg-border sm:block" aria-hidden="true" />
              <div>
                <p className="text-2xl font-bold text-foreground">2 min</p>
                <p className="text-xs text-muted-foreground">Setup time</p>
              </div>
              <div className="hidden h-8 w-px bg-border sm:block" aria-hidden="true" />
              <div>
                <p className="text-2xl font-bold text-foreground">$0</p>
                <p className="text-xs text-muted-foreground">Free forever plan</p>
              </div>
            </div>
          </section>

          {/* Pain Points Section */}
          <section className="bg-muted/40 px-4 py-20 sm:px-6 lg:px-8">
            <div className="mx-auto max-w-6xl">
              <h2 className="mb-4 text-center text-3xl font-bold text-foreground">
                The Ecommerce SEO Blind Spots
              </h2>
              <p className="mb-12 text-center text-lg text-muted-foreground">
                Most ecommerce stores are losing revenue to problems they cannot see yet.
              </p>
              <div className="grid gap-8 md:grid-cols-3">
                {painPoints.map((point) => (
                  <Card key={point.title} className="border-border bg-card">
                    <CardContent className="pt-6">
                      <point.icon className="mb-4 h-8 w-8 text-destructive" />
                      <h3 className="mb-2 text-lg font-semibold text-foreground">{point.title}</h3>
                      <p className="text-muted-foreground">{point.description}</p>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          </section>

          {/* Value Props Section */}
          <section className="px-4 py-20 sm:px-6 lg:px-8">
            <div className="mx-auto max-w-6xl">
              <h2 className="mb-4 text-center text-3xl font-bold text-foreground">
                From Traffic Drop to Published Fix
              </h2>
              <p className="mb-12 text-center text-lg text-muted-foreground">
                {appName} closes the loop: GSC data surfaces the problem, AI drafts the fix, one
                click publishes to WooCommerce, and built-in ROI tracking proves the revenue impact.
              </p>
              <div className="grid gap-8 sm:grid-cols-2 lg:grid-cols-3">
                {valueProps.map((prop) => (
                  <div key={prop.title} className="flex flex-col">
                    <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
                      <prop.icon className="h-6 w-6 text-primary" />
                    </div>
                    <h3 className="mb-2 text-lg font-semibold text-foreground">{prop.title}</h3>
                    <p className="text-muted-foreground">{prop.description}</p>
                  </div>
                ))}
              </div>
            </div>
          </section>

          {/* Related Resources */}
          <section className="px-4 py-20 sm:px-6 lg:px-8">
            <div className="mx-auto max-w-6xl">
              <h2 className="mb-4 text-center text-3xl font-bold text-foreground">
                Related Resources
              </h2>
              <p className="mb-8 text-center text-lg text-muted-foreground">
                Guides and insights for ecommerce SEO
              </p>
              <div className="grid gap-6 md:grid-cols-3">
                {[
                  {
                    title: 'Keyword Cannibalization: How to Find and Fix Competing Pages',
                    slug: 'keyword-cannibalization-find-fix-competing-pages',
                    excerpt:
                      'When multiple product pages target the same query, they compete with each other. Here is how to detect and resolve it.',
                  },
                  {
                    title: 'Thin Content Detection for Large Product Catalogs',
                    slug: 'thin-content-detection-product-catalogs',
                    excerpt:
                      'Identify and prioritize thin product and category pages that are hurting your search rankings.',
                  },
                  {
                    title: 'Traffic Anomaly Detection: Catching Revenue-Impacting Drops Early',
                    slug: 'traffic-anomaly-detection-catching-drops-early',
                    excerpt:
                      'Set up alerts for sudden traffic drops so you can respond before the revenue impact compounds.',
                  },
                ].map((post) => (
                  <Link
                    key={post.slug}
                    href={`/blog/${post.slug}`}
                    className="group rounded-xl border bg-card p-6 transition-shadow hover:shadow-lg"
                    onClick={() =>
                      trackEvent(USE_CASE_TO_BLOG_CLICK, {
                        use_case: 'ecommerce',
                        blog_slug: post.slug,
                      })
                    }
                  >
                    <h3 className="mb-2 text-lg font-semibold transition-colors group-hover:text-primary">
                      {post.title}
                    </h3>
                    <p className="text-sm text-muted-foreground">{post.excerpt}</p>
                  </Link>
                ))}
              </div>
            </div>
          </section>

          {/* FAQ Section */}
          <section className="px-4 py-20 sm:px-6 lg:px-8">
            <div className="mx-auto max-w-3xl">
              <h2 className="mb-8 text-center text-3xl font-bold text-foreground">
                Frequently Asked Questions
              </h2>
              <div className="space-y-3">
                {ecommerceFaqs.map((faq, index) => (
                  <FaqItem key={index} question={faq.question} answer={faq.answer} />
                ))}
              </div>
            </div>
          </section>

          {/* Bottom CTA */}
          <section className="bg-muted/40 px-4 py-20 sm:px-6 lg:px-8">
            <div className="mx-auto max-w-2xl text-center">
              <CheckCircle2 className="mx-auto mb-4 h-10 w-10 text-primary" />
              <h2 className="mb-4 text-3xl font-bold text-foreground">
                Find Your First Revenue-Recovering Fix Today
              </h2>
              <p className="mb-8 text-lg text-muted-foreground">
                Connect your store and run your first analysis free. No credit card required.{' '}
                <Link href="/pricing" className="text-primary underline underline-offset-4">
                  Compare plans
                </Link>{' '}
                to see what is included.
              </p>
              <Link
                href="/register"
                onClick={() => {
                  handleRegisterClick();
                  trackEvent(USE_CASE_CTA_CLICKED, { persona: 'ecommerce' });
                }}
              >
                <Button size="lg" className="px-10 text-base">
                  {CTA_LABELS.FREE_ENTRY}
                </Button>
              </Link>
            </div>
          </section>
        </main>

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

Ecommerce.disableGlobalUi = true;

export default Ecommerce;
