import {
  BarChart2,
  CheckCircle2,
  ChevronDown,
  DollarSign,
  Globe,
  Target,
  Users,
  Zap,
} from 'lucide-react';

import { useState } from 'react';

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

import { HeroDashboardMockup } from '@/Components/marketing/HeroDashboardMockup';
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 AgenciesProps {
  can_login: boolean;
  can_register: boolean;
}

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

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

const painPoints = [
  {
    icon: BarChart2,
    title: 'Manual Reporting Eats Your Margins',
    description:
      'You spend hours every month pulling data from GSC, building spreadsheets, and writing slide decks. That time could go toward strategy — or winning new clients.',
  },
  {
    icon: DollarSign,
    title: 'Cannot Show ROI to Clients',
    description:
      'Clients want to see the impact of every optimization. Without ROI tracking tied to real traffic changes, renewals become conversations you dread.',
  },
  {
    icon: Globe,
    title: 'Juggling Multiple WordPress Sites',
    description:
      'Each client has their own WordPress install, their own GSC account, and their own content quirks. Managing it all without a unified view is chaos.',
  },
];

const valueProps = [
  {
    icon: Target,
    title: 'White-Label Reports in One Click',
    description:
      'Generate branded PDF reports from your agency domain. Clients see your logo — not another tool. Shareable links with optional password protection.',
  },
  {
    icon: Users,
    title: 'Team Seats with Role-Based Access',
    description:
      'Invite team members with editor or viewer roles per site. Clients can log in to view their own data without touching other accounts.',
  },
  {
    icon: Zap,
    title: 'Multi-Site GSC Integration',
    description:
      'Connect all client sites to their Google Search Console accounts in minutes. One dashboard shows traffic winners, losers, and opportunities across every site you manage.',
  },
  {
    icon: BarChart2,
    title: 'Bulk AI Drafts and Batch Publishing',
    description:
      'Generate dozens of AI Drafts across all client sites in one batch job. Review, approve, and bulk-publish to WordPress — so your team ships more fixes per hour without adding headcount.',
  },
];

const agencyFaqs = [
  {
    question: 'Can I white-label reports for my clients?',
    answer:
      'Yes. Team plan includes white-label branding with your agency logo, colors, and custom domain. Clients see your brand, not RankWiz.',
  },
  {
    question: 'How many client sites can I manage?',
    answer:
      'Free plan covers 1 site. Pro supports up to 5 sites. Team plan includes unlimited sites with team member seats.',
  },
  {
    question: 'Do my clients need their own RankWiz account?',
    answer:
      'No. You can invite clients as viewers on specific sites with role-based access. They see their data without accessing other client accounts.',
  },
];

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

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'WebPage',
    name: `${appName} for SEO Agencies — Scale Client SEO Without Adding Headcount`,
    description:
      'RankWiz helps SEO agencies scale client deliverables with white-label reports, multi-site management, and AI Drafts connected directly to Google Search Console.',
    url: `${app_url}/use-cases/agencies`,
  };

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

  return (
    <>
      <Head title={`${appName} for SEO Agencies — Scale Client SEO Without Adding Headcount`}>
        <link rel="canonical" href={`${app_url}/use-cases/agencies`} />
        <meta
          name="description"
          content="RankWiz helps SEO agencies scale client deliverables with white-label reports, multi-site management, and AI Drafts connected directly to Google Search Console."
        />
        <meta property="og:title" content={`${appName} for SEO Agencies — Scale Client SEO`} />
        <meta
          property="og:description"
          content="Scale client SEO with white-label reports, multi-site management, and AI content rewrites."
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/use-cases/agencies`} />
        <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 SEO Agencies`} />
        <meta
          name="twitter:description"
          content="Scale client SEO with white-label reports, multi-site management, and AI content rewrites."
        />
        <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/agencies`,
              },
              {
                '@type': 'ListItem',
                position: 3,
                name: 'Agencies',
                item: `${app_url}/use-cases/agencies`,
              },
            ],
          })}
        </script>
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'FAQPage',
            mainEntity: agencyFaqs.map((faq) => ({
              '@type': 'Question',
              name: faq.question,
              acceptedAnswer: { '@type': 'Answer', text: faq.answer },
            })),
          })}
        </script>
        {/* HowTo structured data — intentionally retained for Google HowTo rich results eligibility */}
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'HowTo',
            name: `How to Scale Client SEO with ${appName}`,
            description:
              'Set up RankWiz for your agency to manage multiple client WordPress sites, generate white-label reports, and publish AI content fixes at scale.',
            step: [
              {
                '@type': 'HowToStep',
                position: 1,
                name: 'Connect a client WordPress site',
                text: "Install the RankWiz WordPress plugin on your client's site and complete the HMAC handshake to establish a secure connection.",
              },
              {
                '@type': 'HowToStep',
                position: 2,
                name: 'Link Google Search Console',
                text: "Authorize RankWiz to read the client's GSC data. RankWiz syncs daily traffic metrics automatically.",
              },
              {
                '@type': 'HowToStep',
                position: 3,
                name: 'Run a site analysis',
                text: "Trigger a traffic analysis to surface winners, losers, and keyword opportunities across the client's content.",
              },
              {
                '@type': 'HowToStep',
                position: 4,
                name: 'Generate AI content drafts in bulk',
                text: 'Use batch AI generation to create rewrite drafts for multiple underperforming pages in a single job.',
              },
              {
                '@type': 'HowToStep',
                position: 5,
                name: 'Publish and generate a white-label report',
                text: 'Bulk-publish approved drafts directly to WordPress and export a branded PDF report from your agency domain.',
              },
            ],
          })}
        </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 SEO Agencies
              </p>
              <h1 className="mb-6 text-4xl font-extrabold tracking-tight text-foreground sm:text-5xl lg:text-6xl">
                Client SEO reporting that proves ROI
              </h1>
              <p className="mx-auto mb-10 max-w-2xl text-xl text-muted-foreground">
                Connect every client&apos;s Google Search Console to WordPress. Diagnose traffic
                drops, generate AI Drafts, and publish — all from one agency dashboard.
              </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>
              <HeroDashboardMockup className="mx-auto mt-10 max-w-3xl" />
            </div>
          </section>

          {/* Agency Outcomes 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-5xl flex-wrap items-center justify-center gap-8 text-center sm:gap-12">
              <div>
                <p className="text-2xl font-bold text-foreground">8+ hours</p>
                <p className="text-xs text-muted-foreground">Saved per client/month on reporting</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">Under 5 min</p>
                <p className="text-xs text-muted-foreground">To connect a new client site</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">Before/after</p>
                <p className="text-xs text-muted-foreground">Traffic ROI for every change</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">White-label</p>
                <p className="text-xs text-muted-foreground">Your brand on every report</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 Problems Every Agency Knows
              </h2>
              <p className="mb-12 text-center text-lg text-muted-foreground">
                RankWiz was built to eliminate the busywork that kills agency margins.
              </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">
                Built for How Agencies Actually Work
              </h2>
              <p className="mb-12 text-center text-lg text-muted-foreground">
                From GSC connection to published content — without leaving {appName}.
              </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 SEO agencies
              </p>
              <div className="grid gap-6 md:grid-cols-3">
                {[
                  {
                    title: 'How to Track SEO ROI for Client Reporting',
                    slug: 'how-to-track-seo-roi-for-client-reporting',
                    excerpt:
                      'Build data-driven client reports that prove SEO ROI with before/after traffic metrics.',
                  },
                  {
                    title: 'GSC Data Analysis: A Complete Guide',
                    slug: 'gsc-data-analysis-complete-guide',
                    excerpt:
                      'Learn how to extract actionable insights from Google Search Console data.',
                  },
                  {
                    title: 'Scaling Content Operations with AI Drafts',
                    slug: 'scaling-content-operations-ai-drafts',
                    excerpt:
                      'How AI-generated content drafts help agencies ship more recommendations per hour.',
                  },
                ].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: 'agencies',
                        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">
                {agencyFaqs.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">
                Start Scaling Your Agency Today
              </h2>
              <p className="mb-8 text-lg text-muted-foreground">
                No credit card required. Connect your first client site in under 5 minutes.{' '}
                <Link href="/pricing" className="text-primary underline underline-offset-4">
                  Compare plans
                </Link>{' '}
                to find the right fit.
              </p>
              <Link
                href="/register"
                onClick={() => {
                  handleRegisterClick();
                  trackEvent(USE_CASE_CTA_CLICKED, { persona: 'agencies' });
                }}
              >
                <Button size="lg" className="px-10 text-base">
                  {CTA_LABELS.FREE_ENTRY}
                </Button>
              </Link>
            </div>
          </section>
        </main>

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

Agencies.disableGlobalUi = true;

export default Agencies;
