import { View, Text, StyleSheet } from "@react-pdf/renderer";
import { C, S } from "../styles";
import type { SeoSection } from "../../types";

const s = StyleSheet.create({
  heading: { ...S.h2, marginBottom: 6 },
  subtext: { ...S.small, marginBottom: 18 },
  // Hero stat
  heroBox: {
    backgroundColor: C.accentLight,
    borderWidth: 1,
    borderColor: "#c7d2fe",
    borderRadius: 6,
    padding: 18,
    marginBottom: 18,
    alignItems: "center",
  },
  heroHeadline: { fontSize: 22, fontFamily: "Helvetica-Bold", color: C.accentDark, textAlign: "center", lineHeight: 1.2 },
  heroSub: { fontSize: 10, color: C.accent, marginTop: 6, textAlign: "center", lineHeight: 1.5 },
  // Two-column layout
  columns: { flexDirection: "row", gap: 12, marginBottom: 14 },
  col: { flex: 1 },
  tableLabel: { ...S.label, marginBottom: 7 },
  table: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
  },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 10,
    paddingVertical: 7,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  // Engine table
  engineRow: {
    flexDirection: "row",
    paddingHorizontal: 10,
    paddingVertical: 7,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  engineRowActive: { borderLeftWidth: 3, borderLeftColor: C.green, paddingLeft: 7 },
  colEngine: { flex: 2.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colSessions: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  colConv: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  colRate: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  engineText: { flex: 2.5, fontSize: 9, color: C.body },
  sessionsText: { flex: 1.2, fontSize: 9, color: C.body, textAlign: "right" },
  convText: { flex: 1.2, fontSize: 9, color: C.green, fontFamily: "Helvetica-Bold", textAlign: "right" },
  rateText: { flex: 1.2, fontSize: 9, color: C.body, textAlign: "right" },
  // Landing pages table
  colUrl: { flex: 4, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colVisits: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  colConvNum: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "right" },
  pageRow: {
    flexDirection: "row",
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  urlText: { flex: 4, fontSize: 8.5, color: C.accent, lineHeight: 1.3 },
  visitsNum: { flex: 1.2, fontSize: 9, color: C.body, textAlign: "right" },
  convNum: { flex: 1.2, fontSize: 9, color: C.green, fontFamily: "Helvetica-Bold", textAlign: "right" },
  // Gap callout
  gapBox: {
    borderWidth: 1,
    borderColor: C.amber,
    borderRadius: 4,
    padding: 14,
    backgroundColor: C.amberLight,
  },
  gapHeader: { fontSize: 11, fontFamily: "Helvetica-Bold", color: "#92400e", marginBottom: 5 },
  gapBody: { fontSize: 9, color: "#92400e", lineHeight: 1.55, marginBottom: 8 },
  gapUrl: { fontSize: 8.5, fontFamily: "Courier", color: "#92400e", lineHeight: 1.6 },
  gapMore: { fontSize: 8, color: C.amber, marginTop: 4 },
});

function fmtNum(n: number): string {
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return String(n);
}

interface Props {
  seo: SeoSection;
}

export function AiConversionAttributionPage({ seo }: Props) {
  const ac = seo.aiConversionAttribution;
  if (!ac) return null;

  const engines = [...ac.topConvertingEngines].sort((a, b) => b.count - a.count);
  const pages = [...ac.topConvertingPages].sort((a, b) => b.conversions - a.conversions || b.aiVisits - a.aiVisits);
  const gapPages = ac.conversionGap?.infrastructureGapPages ?? [];

  return (
    <View>
      <Text style={s.heading}>AI Conversion Attribution</Text>
      <Text style={s.subtext}>AI-referred sessions and their conversion outcomes over the trailing 30-day window.</Text>

      {/* Hero stat */}
      <View style={s.heroBox}>
        <Text style={s.heroHeadline}>
          {`${ac.totalAiConversions30d} conversion${ac.totalAiConversions30d !== 1 ? "s" : ""} at ${ac.aiConversionRate.toFixed(1)}% rate`}
        </Text>
        <Text style={s.heroSub}>
          {`From ${fmtNum(ac.totalAiReferrals30d)} AI-referred sessions across ${engines.length} engine${engines.length !== 1 ? "s" : ""}`}
        </Text>
      </View>

      {/* Two columns */}
      <View style={s.columns}>
        {/* Engine breakdown */}
        {engines.length > 0 && (
          <View style={s.col}>
            <Text style={s.tableLabel}>By AI Engine</Text>
            <View style={s.table}>
              <View style={s.headerRow}>
                <Text style={s.colEngine}>ENGINE</Text>
                <Text style={s.colSessions}>SESSIONS</Text>
                <Text style={s.colConv}>CONV.</Text>
                <Text style={s.colRate}>CVR</Text>
              </View>
              {engines.slice(0, 8).map((e, i) => {
                const cvr = e.conversionRate ?? (e.count > 0 ? 0 : null);
                const hasConv = (e.conversionRate ?? 0) > 0;
                return (
                  <View
                    key={i}
                    style={[s.engineRow, hasConv ? s.engineRowActive : {}, i === Math.min(engines.length, 8) - 1 ? { borderBottomWidth: 0 } : {}]}
                  >
                    <Text style={s.engineText}>{e.engine}</Text>
                    <Text style={s.sessionsText}>{fmtNum(e.count)}</Text>
                    <Text style={s.convText}>—</Text>
                    <Text style={s.rateText}>{cvr != null ? `${cvr.toFixed(1)}%` : "—"}</Text>
                  </View>
                );
              })}
            </View>
          </View>
        )}

        {/* Top converting pages */}
        {pages.length > 0 && (
          <View style={[s.col, { flex: 1.4 }]}>
            <Text style={s.tableLabel}>Top Converting AI Landing Pages</Text>
            <View style={s.table}>
              <View style={s.headerRow}>
                <Text style={s.colUrl}>URL</Text>
                <Text style={s.colVisits}>AI VISITS</Text>
                <Text style={s.colConvNum}>CONV.</Text>
              </View>
              {pages.slice(0, 10).map((p, i) => (
                <View
                  key={i}
                  style={[s.pageRow, i === Math.min(pages.length, 10) - 1 ? { borderBottomWidth: 0 } : {}]}
                >
                  <Text style={s.urlText}>{p.url}</Text>
                  <Text style={s.visitsNum}>{fmtNum(p.aiVisits)}</Text>
                  <Text style={s.convNum}>{p.conversions}</Text>
                </View>
              ))}
            </View>
          </View>
        )}
      </View>

      {/* Conversion infrastructure gap */}
      {gapPages.length > 0 && (
        <View style={s.gapBox}>
          <Text style={s.gapHeader}>Pages Receiving AI Traffic Without Conversion Pathway</Text>
          <Text style={s.gapBody}>
            These pages received AI-referred sessions but lack appointment CTAs, location-specific scheduling links, or other conversion pathways visible in the crawled content.
          </Text>
          {gapPages.slice(0, 8).map((url, i) => (
            <Text key={i} style={s.gapUrl}>{url}</Text>
          ))}
          {gapPages.length > 8 && (
            <Text style={s.gapMore}>…and {gapPages.length - 8} more pages</Text>
          )}
        </View>
      )}
    </View>
  );
}
