import {
  AlertTriangle,
  ArrowRight,
  BarChart2,
  CheckCircle2,
  ChevronDown,
  Globe,
  Mail,
  Search,
  Shield,
  Sparkles,
  TrendingUp,
  Zap,
} from 'lucide-react';

import { type FormEvent, 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 { type PageProps } from '@/types';

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

const faqs: { question: string; answer: string }[] = [
  {
    question: 'What does the free SEO audit include?',
    answer:
      'RankWiz connects to your Google Search Console account and analyzes your actual traffic data — page-level clicks, impressions, CTR, and position trends. You get a full breakdown of your biggest traffic losers, content gaps, thin pages, and meta tag issues. Unlike generic crawl-based audits, everything is powered by real GSC data.',
  },
  {
    question: 'Do I need a WordPress site?',
    answer:
      'The SEO analysis works for any site connected to Google Search Console. The WordPress integration is optional and unlocks extra features like one-click AI draft publishing. You can start the audit and connect WordPress later if you want to use the publishing features.',
  },
  {
    question: 'Is the free tier actually free? No credit card?',
    answer:
      'Yes — no credit card required to sign up or run an audit. The free plan includes one site and one analysis run per month. The free plan includes 5 AI drafts per month — no API key required. Power users can add their own OpenAI key for unlimited drafts at cost.',
  },
  {
    question: 'How long does the audit take?',
    answer:
      "Most audits complete in under two minutes. RankWiz pulls up to 90 days of GSC data, runs it through our analysis engine, and surfaces prioritized recommendations — all before you've finished your coffee.",
  },
  {
    question: 'What kind of recommendations will I get?',
    answer:
      'Recommendations are grouped by action type: content rewrites for pages losing traffic, meta tag optimization for low-CTR pages, thin content expansion, internal linking opportunities, and freshness refreshes for decaying content. Each recommendation includes impact score and the GSC data behind it.',
  },
  {
    question: 'Is my data secure?',
    answer:
      'RankWiz uses read-only OAuth access to Google Search Console — we can never modify your GSC data. Your OpenAI API key (if you add one) is encrypted at rest using AES-256. We do not sell or share your data with third parties.',
  },
];

const steps = [
  {
    icon: Globe,
    title: 'Connect Google Search Console',
    description:
      'OAuth sign-in — read-only access. Takes 30 seconds. We pull up to 90 days of your traffic data.',
  },
  {
    icon: Search,
    title: 'Run your first analysis',
    description:
      'RankWiz analyzes your Google Search Console data across before/after traffic windows, filters for statistically significant changes, and ranks opportunities by impact.',
  },
  {
    icon: BarChart2,
    title: 'Get prioritized recommendations',
    description:
      'See exactly which pages are losing traffic and why — with concrete actions ranked by potential impact score.',
  },
  {
    icon: Sparkles,
    title: 'Generate AI Drafts (optional)',
    description:
      'AI drafts are included — generate content rewrite drafts immediately. Add your own OpenAI key for unlimited drafts. Publish directly to WordPress with one click.',
  },
];

const benefits = [
  { icon: TrendingUp, text: 'Find your biggest traffic opportunities in minutes' },
  { icon: AlertTriangle, text: 'Spot pages losing traffic before they crater' },
  { icon: CheckCircle2, text: 'Prioritized action list — no guesswork' },
  { icon: Shield, text: 'Real GSC data, not generic crawl estimates' },
  { icon: Zap, text: 'AI drafts included — no API key needed' },
  { icon: BarChart2, text: 'Track ROI after you apply recommendations' },
];

function FaqItem({ question, answer }: { question: string; answer: string }) {
  const [open, setOpen] = useState(false);
  const panelId = `faq-${question.slice(0, 20).replace(/\s/g, '-')}`;

  return (
    <div className="border-border border-b last:border-0">
      <button
        aria-controls={panelId}
        aria-expanded={open === true}
        className="flex w-full items-center justify-between gap-4 py-5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm"
        onClick={() => setOpen(!open)}
        type="button"
      >
        <span className="text-foreground font-medium">{question}</span>
        <ChevronDown
          aria-hidden="true"
          className={`text-muted-foreground h-5 w-5 shrink-0 transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
        />
      </button>
      {open && (
        <div
          className="animate-in fade-in-0 text-muted-foreground pb-5 text-sm leading-relaxed"
          id={panelId}
        >
          {answer}
        </div>
      )}
    </div>
  );
}

export default function FreeAudit({ can_login, can_register }: FreeAuditProps) {
  const { app_url } = usePage<PageProps>().props;

  // CRO-005: Inline intent-capture form — lower friction than linking straight to /register
  const [leadEmail, setLeadEmail] = useState('');
  const [leadWebsite, setLeadWebsite] = useState('');

  const handleStartAudit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!leadEmail) return;

    // Store intent for cross-page persistence (e.g. if user navigates away and returns)
    if (typeof window !== 'undefined') {
      localStorage.setItem('rankwiz_lead_email', leadEmail);
      if (leadWebsite) localStorage.setItem('rankwiz_lead_website', leadWebsite);
    }

    // Redirect to register with email pre-filled
    const params = new URLSearchParams({ email: leadEmail });
    if (leadWebsite) params.set('website', leadWebsite);
    window.location.href = `${route('register')}?${params.toString()}`;
  };
  const faqSchema = {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: faqs.map((faq) => ({
      '@type': 'Question',
      name: faq.question,
      acceptedAnswer: {
        '@type': 'Answer',
        text: faq.answer,
      },
    })),
  };

  return (
    <>
      <Head>
        <title>Free WordPress SEO Audit — RankWiz</title>
        <link rel="canonical" href={`${app_url}/free-audit`} />
        <meta
          content="Get a free SEO health check for your WordPress site. Connect Google Search Console and find your biggest traffic opportunities in minutes. No credit card required."
          name="description"
        />
        <meta
          content="free WordPress SEO audit, free SEO health check, WordPress traffic analysis, Google Search Console audit, SEO diagnostic tool"
          name="keywords"
        />
        <meta content="Free WordPress SEO Audit — RankWiz" property="og:title" />
        <meta
          content="Find your biggest traffic opportunities in minutes. Connect Google Search Console and get prioritized SEO recommendations — free, no credit card required."
          property="og:description"
        />
        <meta content="website" property="og:type" />
        <meta content={`${app_url}/free-audit`} property="og:url" />
        <meta content={`${app_url}/og-image.png`} property="og:image" />
        <meta content="1200" property="og:image:width" />
        <meta content="630" property="og:image:height" />
        <meta content="Free WordPress SEO Audit — RankWiz" property="og:image:alt" />
        <meta content="summary_large_image" name="twitter:card" />
        <meta content="@rankwiz_ai" name="twitter:site" />
        <meta content="Free WordPress SEO Audit — RankWiz" name="twitter:title" />
        <meta
          content="Find your biggest traffic opportunities in minutes. Connect Google Search Console and get prioritized SEO recommendations — free, no credit card required."
          name="twitter:description"
        />
        <meta content={`${app_url}/og-image.png`} name="twitter:image" />
        <script type="application/ld+json">{JSON.stringify(faqSchema)}</script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'Service',
            name: 'Free SEO Audit — RankWiz AI',
            description:
              'Free Google Search Console analysis to identify your top traffic opportunities and keyword gaps.',
            provider: {
              '@type': 'Organization',
              name: 'RankWiz AI',
              url: app_url,
            },
            serviceType: 'SEO Analysis',
            areaServed: 'Worldwide',
            offers: { '@type': 'Offer', price: '0', priceCurrency: 'USD' },
          })}
        </script>
      </Head>

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

        <main>
          {/* Hero */}
          <section className="px-4 py-20 text-center sm:px-6 sm:py-28">
            <div className="mx-auto max-w-3xl">
              <div className="bg-primary/10 text-primary mb-6 inline-flex items-center gap-2 rounded-full px-4 py-1.5 text-sm font-medium">
                <Zap className="h-4 w-4" />
                Free — No credit card required
              </div>

              <h1 className="text-foreground mb-6 text-4xl font-bold tracking-tight sm:text-5xl lg:text-6xl">
                Get a Free SEO Health Check
                <br />
                <span className="text-primary">for Your WordPress Site</span>
              </h1>

              <p className="text-muted-foreground mx-auto mb-10 max-w-2xl text-lg sm:text-xl">
                Connect Google Search Console and find out exactly which pages are losing traffic,
                why, and what to do about it — in under two minutes.
              </p>

              {can_register ? (
                /* CRO-005: Two-field intent form — captures email+site before registration */
                <form
                  onSubmit={handleStartAudit}
                  className="mx-auto w-full max-w-md text-left"
                  aria-label="Start your free SEO audit"
                >
                  <div className="flex flex-col gap-3">
                    <div className="relative">
                      <Mail className="text-muted-foreground absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
                      <input
                        type="email"
                        required
                        placeholder="you@example.com"
                        value={leadEmail}
                        onChange={(e) => setLeadEmail(e.target.value)}
                        className="border-border bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary w-full rounded-xl border py-3 pl-10 pr-4 text-sm shadow-sm focus:outline-none focus:ring-2"
                        aria-label="Your email address"
                        autoComplete="email"
                      />
                    </div>
                    <div className="relative">
                      <Globe className="text-muted-foreground absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
                      <input
                        type="url"
                        placeholder="https://yoursite.com (optional)"
                        value={leadWebsite}
                        onChange={(e) => setLeadWebsite(e.target.value)}
                        className="border-border bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary w-full rounded-xl border py-3 pl-10 pr-4 text-sm shadow-sm focus:outline-none focus:ring-2"
                        aria-label="Your website URL"
                        autoComplete="url"
                      />
                    </div>
                    <button
                      type="submit"
                      className="bg-primary text-primary-foreground hover:bg-primary/90 inline-flex w-full items-center justify-center gap-2 rounded-xl px-8 py-4 text-base font-semibold shadow-lg transition-all hover:shadow-xl"
                    >
                      Start Free Analysis
                      <ArrowRight className="h-5 w-5" />
                    </button>
                  </div>
                  <p className="text-muted-foreground mt-3 text-center text-xs">
                    Free forever · No credit card · 2 minutes to first insight
                  </p>
                </form>
              ) : (
                <div className="flex flex-col items-center justify-center gap-4 sm:flex-row">
                  <Link
                    className="bg-primary text-primary-foreground hover:bg-primary/90 inline-flex items-center gap-2 rounded-xl px-8 py-4 text-base font-semibold shadow-lg transition-all hover:shadow-xl"
                    href={route('login')}
                  >
                    Start Free Analysis
                    <ArrowRight className="h-5 w-5" />
                  </Link>
                  <Link
                    className="text-muted-foreground hover:text-foreground inline-flex items-center gap-2 text-sm transition-colors"
                    href={route('features')}
                  >
                    See all features <ArrowRight className="h-4 w-4" />
                  </Link>
                </div>
              )}

              <AnalysisMockup className="mx-auto mt-10 max-w-3xl" />
            </div>
          </section>

          {/* Benefits */}
          <section className="bg-muted/30 px-4 py-16 sm:px-6">
            <div className="mx-auto max-w-5xl">
              <h2 className="text-foreground mb-10 text-center text-2xl font-bold sm:text-3xl">
                What you&apos;ll discover in your free audit
              </h2>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {benefits.map(({ icon: Icon, text }) => (
                  <div
                    className="bg-card border-border flex items-start gap-3 rounded-xl border p-5"
                    key={text}
                  >
                    <div className="bg-primary/10 mt-0.5 shrink-0 rounded-lg p-2">
                      <Icon className="text-primary h-5 w-5" />
                    </div>
                    <p className="text-foreground text-sm font-medium">{text}</p>
                  </div>
                ))}
              </div>
            </div>
          </section>

          {/* How it works */}
          <section className="px-4 py-16 sm:px-6">
            <div className="mx-auto max-w-4xl">
              <h2 className="text-foreground mb-4 text-center text-2xl font-bold sm:text-3xl">
                How the free audit works
              </h2>
              <p className="text-muted-foreground mb-12 text-center">
                Four steps from sign-up to actionable recommendations.
              </p>

              <div className="grid gap-6 sm:grid-cols-2">
                {steps.map(({ icon: Icon, title, description }, i) => (
                  <div className="bg-card border-border relative rounded-xl border p-6" key={title}>
                    <div className="bg-primary/10 mb-4 inline-flex rounded-lg p-2.5">
                      <Icon className="text-primary h-6 w-6" />
                    </div>
                    <div className="bg-primary text-primary-foreground absolute right-4 top-4 flex h-7 w-7 items-center justify-center rounded-full text-xs font-bold">
                      {i + 1}
                    </div>
                    <h3 className="text-foreground mb-2 font-semibold">{title}</h3>
                    <p className="text-muted-foreground text-sm leading-relaxed">{description}</p>
                  </div>
                ))}
              </div>
            </div>
          </section>

          {/* Social proof / trust bar */}
          <section className="bg-muted/30 px-4 py-12 sm:px-6">
            <div className="mx-auto max-w-3xl text-center">
              <p className="text-muted-foreground mb-6 text-sm font-medium uppercase tracking-widest">
                Built for WordPress site owners who rely on organic traffic
              </p>
              <div className="flex flex-wrap justify-center gap-6 text-sm">
                {[
                  'No agency required',
                  'No keyword tools subscription',
                  'Powered by your own GSC data',
                  'AI drafts included on every plan',
                ].map((item) => (
                  <span
                    className="text-foreground flex items-center gap-1.5 font-medium"
                    key={item}
                  >
                    <CheckCircle2 className="text-primary h-4 w-4" />
                    {item}
                  </span>
                ))}
              </div>
            </div>
          </section>

          {/* FAQ */}
          <section className="px-4 py-16 sm:px-6">
            <div className="mx-auto max-w-2xl">
              <h2 className="text-foreground mb-10 text-center text-2xl font-bold sm:text-3xl">
                Frequently asked questions
              </h2>
              <div className="bg-card border-border rounded-xl border px-6">
                {faqs.map((faq) => (
                  <FaqItem answer={faq.answer} key={faq.question} question={faq.question} />
                ))}
              </div>
            </div>
          </section>

          {/* Final CTA */}
          <section className="px-4 py-20 sm:px-6">
            <div className="bg-primary mx-auto max-w-2xl rounded-2xl px-8 py-14 text-center shadow-xl">
              <h2 className="text-primary-foreground mb-4 text-2xl font-bold sm:text-3xl">
                Ready to find your traffic leaks?
              </h2>
              <p className="text-primary-foreground/80 mb-8 text-base">
                Your first audit is free. No credit card. No obligation.
              </p>
              {can_register ? (
                <button
                  type="button"
                  onClick={() => {
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                    // Give the scroll a moment then focus the email field
                    setTimeout(() => {
                      const emailInput =
                        document.querySelector<HTMLInputElement>('input[type="email"]');
                      emailInput?.focus();
                    }, 400);
                  }}
                  className="bg-background text-foreground hover:bg-background/90 inline-flex items-center gap-2 rounded-xl px-8 py-4 font-semibold shadow-md transition-all hover:shadow-lg"
                >
                  Start Free Analysis
                  <ArrowRight className="h-5 w-5" />
                </button>
              ) : (
                <Link
                  className="bg-background text-foreground hover:bg-background/90 inline-flex items-center gap-2 rounded-xl px-8 py-4 font-semibold shadow-md transition-all hover:shadow-lg"
                  href={route('login')}
                >
                  Start Free Analysis
                  <ArrowRight className="h-5 w-5" />
                </Link>
              )}
            </div>
          </section>
        </main>

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