import {
  AlertCircle,
  CheckCircle2,
  ChevronDown,
  Clock,
  FileText,
  Sparkles,
  TrendingUp,
  Zap,
} 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 BloggersProps {
  can_login: boolean;
  can_register: boolean;
}

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

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

const painPoints = [
  {
    icon: AlertCircle,
    title: 'Do Not Know Which Posts Are Losing Traffic',
    description:
      'You publish consistently but rankings slip without warning. Figuring out which posts are bleeding traffic means hours in Google Search Console spreadsheets.',
  },
  {
    icon: Clock,
    title: 'GSC Data Is Overwhelming',
    description:
      'Google Search Console shows you everything — but makes it nearly impossible to prioritize. Hundreds of queries, dozens of pages, no clear "fix this first."',
  },
  {
    icon: FileText,
    title: 'No Time for Technical SEO',
    description:
      'You are a writer, not an SEO specialist. You need clear, actionable fixes you can implement without a developer or an agency retainer.',
  },
];

const valueProps = [
  {
    icon: TrendingUp,
    title: 'Traffic Winners and Losers in One View',
    description:
      'Connect your GSC account and get a ranked list of posts gaining or losing clicks — sorted by impact. Know exactly where to focus this week.',
  },
  {
    icon: Zap,
    title: 'AI-Generated Rewrites in Minutes',
    description:
      'For every underperforming post, RankWiz generates a full rewrite draft powered by AI — included on every plan. E-E-A-T (Experience, Expertise, Authoritativeness, Trustworthiness) signals, keyword coverage, and freshness — all baked in.',
  },
  {
    icon: CheckCircle2,
    title: 'Publish Directly to WordPress',
    description:
      'No copy-pasting. Approve a draft and it lands in your WordPress editor, ready to review. One click from insight to published update.',
  },
  {
    icon: Sparkles,
    title: 'GEO: Stay Visible in AI Search',
    description:
      'As readers shift to ChatGPT, Perplexity, and Google AI Overviews, RankWiz scores your content across 6 Generative Engine Optimization (GEO) pillars — so your posts stay discoverable as search evolves beyond the traditional blue links.',
  },
];

const bloggerFaqs = [
  {
    question: 'Do I need technical SEO knowledge to use RankWiz?',
    answer:
      'No. RankWiz translates GSC data into plain-language recommendations. You get a prioritized list of what to fix, why, and an AI-generated draft to help you do it.',
  },
  {
    question: 'How does the free plan work for bloggers?',
    answer:
      'The free plan includes 1 site, all 12 recommendation types, and bundled AI drafts. No credit card required. You can run analyses and generate content fixes immediately.',
  },
  {
    question: 'Can RankWiz help with content that has never ranked?',
    answer:
      'Yes. Content gap detection and topic clustering identify topics your competitors cover that you do not. Content briefs help you plan new posts targeting those gaps.',
  },
];

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 Bloggers: BloggersComponent = ({ can_login, can_register }) => {
  const { app_url } = usePage<PageProps>().props;

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'WebPage',
    name: `${appName} for Bloggers — Turn Declining Blog Traffic Into Your Next Growth Spike`,
    description:
      'RankWiz helps bloggers identify which posts are losing traffic, understand why, and generate AI Drafts that can be published directly to WordPress — no technical SEO required.',
    url: `${app_url}/use-cases/bloggers`,
  };

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

  return (
    <>
      <Head title={`${appName} for Bloggers — Turn Declining Traffic Into Growth`}>
        <meta
          name="description"
          content="RankWiz helps bloggers identify which posts are losing traffic, understand why, and generate AI Drafts that publish directly to WordPress — no technical SEO required."
        />
        <meta
          property="og:title"
          content={`${appName} for Bloggers — Turn Declining Traffic Into Growth`}
        />
        <meta
          property="og:description"
          content="Identify which posts are losing traffic, understand why, and generate AI Drafts that publish directly to WordPress."
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/use-cases/bloggers`} />
        <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 Bloggers`} />
        <meta
          name="twitter:description"
          content="Turn declining blog traffic into growth with AI-powered 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" />
        <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/bloggers`,
              },
              {
                '@type': 'ListItem',
                position: 3,
                name: 'Bloggers',
                item: `${app_url}/use-cases/bloggers`,
              },
            ],
          })}
        </script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'FAQPage',
            mainEntity: bloggerFaqs.map((faq) => ({
              '@type': 'Question',
              name: faq.question,
              acceptedAnswer: { '@type': 'Answer', text: faq.answer },
            })),
          })}
        </script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'HowTo',
            name: `How to Fix Declining Blog Traffic with ${appName}`,
            description:
              'Use RankWiz to identify which blog posts are losing traffic, understand why, and publish AI-generated fixes directly to WordPress.',
            step: [
              {
                '@type': 'HowToStep',
                position: 1,
                name: 'Connect your WordPress blog',
                text: 'Install the RankWiz plugin on your WordPress site and complete the one-time setup in under 2 minutes.',
              },
              {
                '@type': 'HowToStep',
                position: 2,
                name: 'Link Google Search Console',
                text: 'Authorize RankWiz to access your GSC data. Daily sync starts automatically so your traffic data is always current.',
              },
              {
                '@type': 'HowToStep',
                position: 3,
                name: 'Run a traffic analysis',
                text: 'Trigger an analysis to get a prioritized list of posts that are gaining or losing traffic, sorted by impact.',
              },
              {
                '@type': 'HowToStep',
                position: 4,
                name: 'Generate an AI rewrite draft',
                text: 'Select an underperforming post and generate an AI draft that improves keyword coverage, E-E-A-T signals, and content freshness.',
              },
              {
                '@type': 'HowToStep',
                position: 5,
                name: 'Publish the fix to WordPress',
                text: 'Approve the draft and publish it directly to your WordPress editor with one click — no copy-pasting required.',
              },
            ],
          })}
        </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 Bloggers
              </p>
              <h1 className="mb-6 text-4xl font-extrabold tracking-tight text-foreground sm:text-5xl lg:text-6xl">
                Find which posts are losing traffic and fix them with AI
              </h1>
              <p className="mx-auto mb-10 max-w-2xl text-xl text-muted-foreground">
                Stop guessing which posts need attention. {appName} connects your Google Search
                Console to your WordPress blog and shows you exactly where traffic is slipping —
                then writes the fix.
              </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">
                Sound Familiar?
              </h2>
              <p className="mb-12 text-center text-lg text-muted-foreground">
                Every blogger hits these walls. {appName} was built to break through them.
              </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">
                Everything You Need to Stop the Decline
              </h2>
              <p className="mb-12 text-center text-lg text-muted-foreground">
                From diagnosis to published update — in the same tool.
              </p>
              <div className="grid gap-8 md: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 bloggers
              </p>
              <div className="grid gap-6 md:grid-cols-3">
                {[
                  {
                    title: 'Content Freshness: Why Updating Old Posts Beats Writing New Ones',
                    slug: 'content-freshness-updating-old-posts',
                    excerpt:
                      'Discover why refreshing existing content often delivers faster traffic gains than publishing new articles.',
                  },
                  {
                    title: 'Striking Distance Keywords: Your Fastest Path to Page 1',
                    slug: 'striking-distance-keywords-fastest-path-page-one',
                    excerpt:
                      'Find queries ranking positions 11-20 and learn exactly how to push them onto page one.',
                  },
                  {
                    title: 'How to Use Google Search Console for Blog Traffic Analysis',
                    slug: 'gsc-data-analysis-complete-guide',
                    excerpt:
                      'A practical guide to finding traffic trends and content opportunities in your GSC data.',
                  },
                ].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: 'bloggers',
                        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">
                {bloggerFaqs.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">
              <TrendingUp className="mx-auto mb-4 h-10 w-10 text-primary" />
              <h2 className="mb-4 text-3xl font-bold text-foreground">
                Your Next Traffic Win Is Already in Your GSC Data
              </h2>
              <p className="mb-8 text-lg text-muted-foreground">
                {appName} finds it for you. Free to start — no credit card, no setup fee.{' '}
                <Link href="/pricing" className="text-primary underline underline-offset-4">
                  View all plans
                </Link>
                .
              </p>
              <Link
                href="/register"
                onClick={() => {
                  handleRegisterClick();
                  trackEvent(USE_CASE_CTA_CLICKED, { persona: 'bloggers' });
                }}
              >
                <Button size="lg" className="px-10 text-base">
                  {CTA_LABELS.FREE_ENTRY}
                </Button>
              </Link>
            </div>
          </section>
        </main>

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

Bloggers.disableGlobalUi = true;

export default Bloggers;
