import { ArrowRight } from 'lucide-react';

import { useEffect, useState } from 'react';

import { Link } from '@inertiajs/react';

import { trackEvent } from '@/lib/analytics';
import {
  RETURNING_THRESHOLD,
  getBlogVisitCount,
  incrementBlogVisitCount,
} from '@/lib/blog-visit-counter';
import { BLOG_TO_PRODUCT_CTA_CLICK } from '@/lib/event-catalog';

interface BlogProductCtaProps {
  category: string | null;
  blogSlug: string;
  variant?: 'inline' | 'bottom';
}

const CATEGORY_FEATURE_MAP: Record<string, { anchor: string; copy: string; subtext: string }> = {
  'gsc-analytics': {
    anchor: 'diagnose',
    copy: 'See your GSC traffic drops in real time',
    subtext:
      'Connect Google Search Console and get a ranked list of pages losing clicks — in under 2 minutes.',
  },
  'content-optimization': {
    anchor: 'fix',
    copy: 'Generate AI content fixes from your GSC data',
    subtext:
      'RankWiz writes AI drafts for underperforming pages and publishes them to WordPress in one click.',
  },
  'keyword-strategy': {
    anchor: 'analyze',
    copy: 'Find your striking-distance keyword opportunities',
    subtext:
      'RankWiz surfaces queries ranking positions 11–20 with high impressions — your fastest path to page 1.',
  },
  'wordpress-seo': {
    anchor: 'fix',
    copy: 'Fix your WordPress SEO issues with real data',
    subtext: 'Connect your site and get AI-powered recommendations ranked by traffic impact.',
  },
  'seo-measurement': {
    anchor: 'prove',
    copy: 'Prove what your SEO work actually achieved',
    subtext:
      'RankWiz tracks clicks, CTR, and position changes at 7, 14, 30, and 90 days — for every optimization.',
  },
};

const DEFAULT_CTA = {
  anchor: 'diagnose',
  copy: 'See this in action with your real GSC data',
  subtext: 'Connect Google Search Console and get AI-powered recommendations in under 2 minutes.',
};

export function BlogProductCta({ category, blogSlug, variant = 'inline' }: BlogProductCtaProps) {
  const cta = (category && CATEGORY_FEATURE_MAP[category]) || DEFAULT_CTA;
  const featureUrl = `/features#${cta.anchor}`;

  // Start at 0 (SSR-safe); effect updates after hydration and on slug changes
  const [visitCount, setVisitCount] = useState(0);

  useEffect(() => {
    incrementBlogVisitCount(blogSlug);
    setVisitCount(getBlogVisitCount(blogSlug));
  }, [blogSlug]);

  const ctaLabel =
    visitCount >= RETURNING_THRESHOLD ? 'Start Pro Trial' : 'Try Free — No Credit Card';

  const handleClick = () => {
    trackEvent(BLOG_TO_PRODUCT_CTA_CLICK, {
      blog_slug: blogSlug,
      target_feature: cta.anchor,
      variant,
      visit_count: visitCount,
    });
  };

  if (variant === 'bottom') {
    return (
      <section className="mt-12 rounded-2xl bg-primary/5 border border-primary/20 p-8 text-center">
        <p className="mb-1 text-xs font-semibold uppercase tracking-widest text-primary">
          See this in action
        </p>
        <h3 className="mb-3 text-xl font-bold text-foreground">{cta.copy}</h3>
        <p className="mb-6 text-sm text-muted-foreground">{cta.subtext}</p>
        <div className="flex flex-wrap items-center justify-center gap-3">
          <Link
            href="/register"
            className="inline-flex items-center gap-2 rounded-md bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90 transition-colors"
            onClick={handleClick}
          >
            {ctaLabel}
            <ArrowRight className="h-4 w-4" aria-hidden="true" />
          </Link>
          <Link
            href={featureUrl}
            className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
            onClick={handleClick}
          >
            Learn about this feature →
          </Link>
        </div>
      </section>
    );
  }

  // inline variant
  return (
    <div className="not-prose my-8 rounded-xl border-l-4 border-primary bg-primary/5 px-6 py-5">
      <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-primary">
        See this in action
      </p>
      <p className="mb-3 text-sm font-semibold text-foreground">{cta.copy}</p>
      <p className="mb-4 text-sm text-muted-foreground">{cta.subtext}</p>
      <Link
        href="/register"
        className="inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-xs font-semibold text-primary-foreground hover:bg-primary/90 transition-colors"
        onClick={handleClick}
      >
        {ctaLabel}
        <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
      </Link>
    </div>
  );
}
