import { View, Text, StyleSheet, Svg, Polyline, Path } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { AiSearchPerformance, SiteTagContext } from "../../types";

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 6 },
  subtext: { ...S.small, marginBottom: 16 },
  // Hero row
  heroRow: { flexDirection: "row", gap: 16, marginBottom: 20 },
  heroCard: {
    flex: 1,
    backgroundColor: "#1e1b4b",
    borderRadius: 6,
    padding: 18,
  },
  heroLabel: { fontSize: 8, fontFamily: "Helvetica-Bold", color: "#a5b4fc", letterSpacing: 1.2, textTransform: "uppercase", marginBottom: 8 },
  heroNum: { fontSize: 48, fontFamily: "Helvetica-Bold", color: C.white, lineHeight: 1 },
  trendText: { fontSize: 9, color: "#a5b4fc", marginTop: 6 },
  siteTagNote: { fontSize: 8, color: "rgba(165,180,252,0.6)", marginTop: 8 },
  // Engines card
  enginesCard: {
    flex: 1,
    backgroundColor: "#1e1b4b",
    borderRadius: 6,
    padding: 18,
  },
  engLabel: { ...S.label, color: "#a5b4fc", marginBottom: 10 },
  engineRow: { flexDirection: "row", alignItems: "center", marginBottom: 6 },
  engineName: { fontSize: 9, color: "#c7d2fe", width: 72, flexShrink: 0 },
  barBg: { flex: 1, backgroundColor: "rgba(255,255,255,0.1)", borderRadius: 2, height: 4, position: "relative" },
  barFill: { height: 4, borderRadius: 2, backgroundColor: "#818cf8", position: "absolute", top: 0, left: 0 },
  engineCount: { fontSize: 9, color: "#c7d2fe", width: 32, textAlign: "right", marginLeft: 6 },
  // Pages table
  pagesSection: { marginTop: 4 },
  tableHeader: { flexDirection: "row", paddingBottom: 5, borderBottomWidth: 0.75, borderBottomColor: C.border, marginBottom: 4 },
  tableRow: { flexDirection: "row", paddingVertical: 4, borderBottomWidth: 0.5, borderBottomColor: "#f1f5f9" },
  colUrl: { flex: 3, fontSize: 9, color: C.body },
  colNum: { width: 55, fontSize: 9, color: C.body, textAlign: "right" },
  colHead: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, textAlign: "right" },
  colHeadUrl: { flex: 3, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted },
  // Locked variant
  lockedCard: {
    backgroundColor: C.surface,
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 6,
    padding: 24,
    alignItems: "center",
  },
  lockIcon: { fontSize: 28, marginBottom: 10, color: C.muted },
  lockTitle: { fontSize: 13, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 6, textAlign: "center" },
  lockBody: { fontSize: 10, color: C.muted, textAlign: "center", lineHeight: 1.6, marginBottom: 14 },
  ctaBox: {
    backgroundColor: C.accentLight,
    borderWidth: 0.75,
    borderColor: C.accent,
    borderRadius: 4,
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  ctaText: { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.accentDark, textAlign: "center" },
  // Sparkline
  sparkContainer: { marginTop: 10, marginBottom: 4 },
  sparkLabel: { fontSize: 7.5, color: "#a5b4fc", marginBottom: 4, letterSpacing: 0.5 },
});

function urlPath(url: string): string {
  try {
    const u = new URL(url);
    const p = u.pathname.replace(/\/$/, "") || "/";
    return p.length > 42 ? p.slice(0, 40) + "…" : p;
  } catch {
    return url.length > 42 ? url.slice(0, 40) + "…" : url;
  }
}

function engineLabel(raw: string): string {
  const map: Record<string, string> = {
    chatgpt: "ChatGPT", openai: "ChatGPT", perplexity: "Perplexity",
    claude: "Claude", anthropic: "Claude", gemini: "Gemini", bard: "Gemini",
    google_ai_overview: "Google AI", google_ai: "Google AI", copilot: "Copilot",
    bing: "Copilot", grok: "Grok", unknown: "Other",
  };
  return map[raw.toLowerCase()] ?? raw;
}

function Sparkline({ data }: { data: Array<{ date: string; count: number }> }) {
  if (data.length < 2) return null;
  const W = 504; const H = 40; const PAD = 2;
  const maxCount = Math.max(...data.map((d) => d.count), 1);
  const segW = (W - PAD * 2) / (data.length - 1);

  const pts = data.map((d, i) => ({
    x: PAD + i * segW,
    y: H - PAD - (d.count / maxCount) * (H - PAD * 2),
  }));

  const polyPoints = pts.map((p) => `${p.x},${p.y}`).join(" ");
  const fillPath = [
    `M ${pts[0].x} ${H}`,
    ...pts.map((p) => `L ${p.x} ${p.y}`),
    `L ${pts[pts.length - 1].x} ${H}`,
    "Z",
  ].join(" ");

  return (
    <View style={s.sparkContainer}>
      <Text style={s.sparkLabel}>30-DAY REFERRAL TREND</Text>
      <Svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}>
        <Path d={fillPath} fill="rgba(129,140,248,0.2)" />
        <Polyline points={polyPoints} stroke="#818cf8" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      </Svg>
    </View>
  );
}

interface LiveProps {
  data: AiSearchPerformance;
  siteTagContext?: SiteTagContext;
}

export function AiSearchPerformanceLive({ data, siteTagContext }: LiveProps) {
  const totalEngineCount = data.topEngines.reduce((s, e) => s + e.count, 0);
  const trend = data.trendVsTrailing90d;
  const trendStr =
    trend != null
      ? `${trend >= 0 ? "+" : ""}${trend.toFixed(1)}% vs prior 60 days`
      : "Trend data unavailable";

  return (
    <View>
      <Text style={s.heading}>AI Search Performance</Text>
      <Text style={s.subtext}>
        AI referral attribution from your meSEO Site Tag over the trailing 30 days.
      </Text>

      <View style={s.heroRow}>
        {/* Hero stat */}
        <View style={s.heroCard}>
          <Text style={s.heroLabel}>AI Referrals · Last 30 Days</Text>
          <Text style={s.heroNum}>{data.totalReferrals30d.toLocaleString()}</Text>
          <Text style={s.trendText}>{trendStr}</Text>
          {data.referralsByDay && <Sparkline data={data.referralsByDay} />}
          {siteTagContext?.daysActive != null && (
            <Text style={s.siteTagNote}>Based on {siteTagContext.daysActive} days of Site Tag data</Text>
          )}
        </View>

        {/* Engine breakdown */}
        <View style={s.enginesCard}>
          <Text style={s.engLabel}>By Engine · Last 30 Days</Text>
          {data.topEngines.slice(0, 5).map((e) => {
            const pct = totalEngineCount > 0 ? (e.count / totalEngineCount) * 100 : 0;
            return (
              <View key={e.engine} style={s.engineRow}>
                <Text style={s.engineName}>{engineLabel(e.engine)}</Text>
                <View style={s.barBg}>
                  <View style={[s.barFill, { width: `${pct.toFixed(1)}%` }]} />
                </View>
                <Text style={s.engineCount}>{e.count}</Text>
              </View>
            );
          })}
        </View>
      </View>

      {data.topAttributedPages.length > 0 && (
        <View style={s.pagesSection}>
          <Text style={S.label}>Top Landing Pages · 30 Days</Text>
          <View style={s.tableHeader}>
            <Text style={s.colHeadUrl}>Page</Text>
            <Text style={s.colHead}>AI Visits</Text>
            <Text style={s.colHead}>Conversions</Text>
          </View>
          {data.topAttributedPages.slice(0, 6).map((p) => (
            <View key={p.url} style={s.tableRow}>
              <Text style={s.colUrl}>{urlPath(p.url)}</Text>
              <Text style={s.colNum}>{p.aiVisits.toLocaleString()}</Text>
              <Text style={s.colNum}>{p.conversions > 0 ? p.conversions : "—"}</Text>
            </View>
          ))}
        </View>
      )}
    </View>
  );
}

export function AiSearchPerformanceLocked() {
  return (
    <View>
      <Text style={s.heading}>AI Search Performance</Text>
      <Text style={s.subtext}>Real-time AI referral attribution — requires meSEO Site Tag.</Text>
      <View style={s.lockedCard}>
        <Text style={s.lockIcon}>🔒</Text>
        <Text style={s.lockTitle}>Unlock Your AI Search Data</Text>
        <Text style={s.lockBody}>
          Install the meSEO Site Tag to see exactly which AI engines are sending traffic to your site,
          which pages they land on, and how many convert. This section will populate with live data
          within 24 hours of installation.
        </Text>
        <View style={s.ctaBox}>
          <Text style={s.ctaText}>Book a demo → meseoapp.com/book-demo</Text>
        </View>
      </View>
    </View>
  );
}
