"use client";

import Link from "next/link";
import {
  Bot, CheckCircle2, ExternalLink, Search, FileText, Target, Lightbulb,
} from "lucide-react";

interface Monitoring {
  installedAt: string | null;
  lastEventAt: string | null;
  sessionsScanned: number;
  isActive: boolean;
}

interface PlatformEntry {
  name: string;
  domain: string;
  color: string;
  note?: string;
}

// Primary AI platforms — the ones most likely to drive traffic. Google
// AI Overview goes first because for most brands it's the largest AI
// traffic source, even though the referrer is indistinguishable from
// organic Google (we detect it via text-fragment highlighting).
const PLATFORMS: PlatformEntry[] = [
  { name: "Google AI Overview",  domain: "google.com (AI)",        color: "bg-blue-100 text-blue-700",     note: "Detected via text fragment analysis" },
  { name: "ChatGPT",             domain: "chatgpt.com",            color: "bg-emerald-100 text-emerald-700" },
  { name: "Perplexity",          domain: "perplexity.ai",          color: "bg-violet-100 text-violet-700" },
  { name: "Gemini",              domain: "gemini.google.com",      color: "bg-sky-100 text-sky-700" },
  { name: "Microsoft Copilot",   domain: "copilot.microsoft.com",  color: "bg-cyan-100 text-cyan-700" },
  { name: "Claude",              domain: "claude.ai",              color: "bg-orange-100 text-orange-700" },
  { name: "Meta AI",             domain: "meta.ai",                color: "bg-indigo-100 text-indigo-700" },
];

const NEXT_STEPS: Array<{ title: string; description: string; href: string; icon: typeof Bot }> = [
  {
    title: "Check your AI visibility",
    description: "See how AI platforms describe your business and which keywords they cite you for.",
    href: "/ai-visibility",
    icon: Search,
  },
  {
    title: "Create LLMO-optimized content",
    description: "Use the LLMO Content Brief to create FAQ-structured content that AI platforms prefer to cite.",
    href: "/llmo-content-brief",
    icon: FileText,
  },
  {
    title: "Research AI-citable keywords",
    description: "Find high-volume keywords where competitors are cited by AI but you're not.",
    href: "/keyword-research",
    icon: Target,
  },
];

function formatInstallDate(iso: string | null): string {
  if (!iso) return "just now";
  const date = new Date(iso);
  const days = Math.floor((Date.now() - date.getTime()) / 86_400_000);
  if (days === 0) return "today";
  if (days === 1) return "yesterday";
  if (days < 30) return `${days} days ago`;
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

export function AiAttributionEmptyState({ monitoring }: { monitoring: Monitoring | null }) {
  const installedLabel = formatInstallDate(monitoring?.installedAt ?? null);
  const sessionsScanned = monitoring?.sessionsScanned ?? 0;

  return (
    <div className="space-y-6">
      {/* Hero — system is active */}
      <div className="bg-gradient-to-br from-violet-50 to-blue-50 border border-violet-200 rounded-xl p-8">
        <div className="flex items-start gap-4">
          <div className="relative shrink-0">
            <Bot className="w-10 h-10 text-violet-600" />
            <span className="absolute -top-0.5 -right-0.5 w-3 h-3 rounded-full bg-emerald-400 border-2 border-white animate-pulse" />
          </div>
          <div className="flex-1">
            <h2 className="text-lg font-bold text-slate-900 mb-1">AI Attribution is Active &amp; Monitoring</h2>
            <p className="text-sm text-slate-600">
              The Site Tag is watching for visitors from AI platforms. Every session is scanned for
              AI referrers — when one arrives, it will appear here within seconds.
            </p>
          </div>
        </div>

        {/* Status bar */}
        <div className="mt-5 grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
          <div className="bg-white/80 rounded-lg px-3 py-2.5 flex items-center gap-2">
            <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
            <div>
              <p className="font-semibold text-slate-700">Monitoring active</p>
              <p className="text-[10px] text-slate-500">Since {installedLabel}</p>
            </div>
          </div>
          <div className="bg-white/80 rounded-lg px-3 py-2.5">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Sessions scanned</p>
            <p className="text-lg font-bold tabular-nums text-slate-800">{(sessionsScanned ?? 0).toLocaleString()}</p>
          </div>
          <div className="bg-white/80 rounded-lg px-3 py-2.5">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">AI referrals detected</p>
            <p className="text-lg font-bold tabular-nums text-slate-800">0 <span className="text-[10px] font-medium text-slate-400">so far</span></p>
          </div>
        </div>
      </div>

      {/* Monitored platforms */}
      <div className="bg-white rounded-xl border border-slate-200 p-5">
        <h3 className="text-sm font-bold text-slate-800 mb-1">What&apos;s being monitored</h3>
        <p className="text-xs text-slate-500 mb-4">
          The Site Tag detects traffic from these AI platforms via referrer URL, text fragment analysis,
          and behavioral fingerprinting.
        </p>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
          {PLATFORMS.map((p) => (
            <div
              key={p.domain}
              className="flex items-start gap-2 px-3 py-2.5 rounded-lg border border-slate-100 hover:border-slate-200 transition-colors"
            >
              <span className={`w-7 h-7 rounded-md flex items-center justify-center text-xs font-bold shrink-0 ${p.color}`}>
                {p.name.charAt(0)}
              </span>
              <div className="min-w-0 flex-1">
                <p className="text-xs font-semibold text-slate-700 truncate">{p.name}</p>
                <p className="text-[10px] font-mono text-slate-400 truncate">{p.domain}</p>
                {p.note && <p className="text-[10px] text-blue-600 mt-0.5 italic">{p.note}</p>}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Test it */}
      <div className="bg-amber-50 border border-amber-200 rounded-xl p-4 flex items-start gap-3">
        <Lightbulb className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
        <div className="flex-1">
          <p className="text-xs font-bold text-amber-900 mb-0.5">Test the detection yourself</p>
          <p className="text-xs text-amber-800 leading-relaxed">
            Search for your brand on <span className="font-semibold">Google</span> — if an AI Overview
            appears and cites your page, click through. The text-highlighted link should appear here
            within minutes. Or search on{" "}
            <a href="https://perplexity.ai" target="_blank" rel="noreferrer" className="underline font-semibold">
              Perplexity.ai
            </a>{" "}
            and click the result. Either will appear here within minutes as a confirmed AI referral.
          </p>
        </div>
      </div>

      {/* How to get AI traffic */}
      <div className="bg-white rounded-xl border border-slate-200 p-5">
        <h3 className="text-sm font-bold text-slate-800 mb-1">How to get AI traffic</h3>
        <p className="text-xs text-slate-500 mb-4">
          AI platforms cite content that&apos;s well-structured, comprehensive, and authoritative. Use these
          meSEO features to optimize your content for AI citation.
        </p>
        <div className="space-y-2">
          {NEXT_STEPS.map((step) => {
            const Icon = step.icon;
            return (
              <Link
                key={step.href}
                href={step.href}
                className="flex items-start gap-3 px-4 py-3 rounded-lg border border-slate-100 hover:border-brand-200 hover:bg-brand-50/30 transition-colors group"
              >
                <span className="w-8 h-8 rounded-lg bg-brand-50 flex items-center justify-center text-brand-600 shrink-0 group-hover:bg-brand-100 transition-colors">
                  <Icon className="w-4 h-4" />
                </span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-slate-800 flex items-center gap-1">
                    {step.title}
                    <ExternalLink className="w-3 h-3 text-slate-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                  </p>
                  <p className="text-xs text-slate-500 mt-0.5 leading-relaxed">{step.description}</p>
                </div>
              </Link>
            );
          })}
        </div>
      </div>
    </div>
  );
}
