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 },
  statStrip: { flexDirection: "row", gap: 10, marginBottom: 18 },
  statBox: {
    flex: 1,
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 12,
    backgroundColor: C.surface,
  },
  statLabel: { ...S.label, marginBottom: 5 },
  statValue: { fontSize: 26, fontFamily: "Helvetica-Bold", color: C.ink, lineHeight: 1 },
  statSub: { fontSize: 8, color: C.muted, marginTop: 4, lineHeight: 1.35 },
  tableLabel: { ...S.label, marginBottom: 7 },
  table: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
    marginBottom: 12,
  },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  row: {
    flexDirection: "row",
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  rowAlt: { backgroundColor: "#fafafa" },
  colQuery: { flex: 3.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colAio: { flex: 1, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "center" },
  colMentioned: { flex: 1.2, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "center" },
  colCompetitors: { flex: 3, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  queryText: { flex: 3.5, fontSize: 9, color: C.body, lineHeight: 1.35 },
  aioYes: { flex: 1, fontSize: 9, color: C.green, fontFamily: "Helvetica-Bold", textAlign: "center" },
  aioNo: { flex: 1, fontSize: 9, color: C.caption, textAlign: "center" },
  mentionedYes: { flex: 1.2, fontSize: 9, color: C.green, fontFamily: "Helvetica-Bold", textAlign: "center" },
  mentionedNo: { flex: 1.2, fontSize: 9, color: C.red, textAlign: "center" },
  mentionedNa: { flex: 1.2, fontSize: 9, color: C.caption, textAlign: "center" },
  competitorsText: { flex: 3, fontSize: 8.5, color: C.muted, lineHeight: 1.35 },
  footnote: { ...S.caption, marginTop: 10, lineHeight: 1.5 },
  // Fallback box for 3rd-party with no public data
  noDataBox: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    padding: 14,
    backgroundColor: C.surface,
  },
  noDataText: { fontSize: 10, color: C.muted, lineHeight: 1.6 },
});

function citabilityScore(pav: SeoSection["publicAiVisibility"]): number | null {
  if (!pav) return null;
  if (pav.overallCitabilityScore != null) return pav.overallCitabilityScore;
  // Derive: 50% from coverage rate, 50% from citation rate (when present)
  const coverage = pav.queriesWithAiOverview / Math.max(pav.totalQueriesChecked, 1);
  const brandRate = pav.aiOverviewDetails.length > 0
    ? pav.aiOverviewDetails.filter((d) => d.brandMentioned).length / pav.aiOverviewDetails.length
    : 0;
  return Math.round((coverage * 0.5 + brandRate * 0.5) * 100);
}

interface Props {
  seo: SeoSection;
  isFirstParty: boolean;
}

export function AiVisibilityPage({ seo, isFirstParty }: Props) {
  const pav = seo.publicAiVisibility;

  if (!pav && !isFirstParty) {
    // 3rd-party with no public AI data: fallback box
    return (
      <View>
        <Text style={s.heading}>AI Visibility</Text>
        <Text style={s.subtext}>AI surface presence and brand citation across tracked industry queries.</Text>
        <View style={s.noDataBox}>
          <Text style={s.noDataText}>
            Public AI Overview analysis was not available for this audit. AI Visibility data requires verified
            industry query coverage. See the {'"'}What First-Party Data Would Reveal{'"'} section for context on what first-party
            AI referral telemetry adds.
          </Text>
        </View>
      </View>
    );
  }

  if (!pav) return null; // 1st-party with no publicAiVisibility — augment block simply absent

  const citability = citabilityScore(pav);
  const coverageRate = pav.totalQueriesChecked > 0
    ? Math.round((pav.queriesWithAiOverview / pav.totalQueriesChecked) * 100)
    : 0;
  const citationRate = pav.aiOverviewDetails.length > 0
    ? Math.round((pav.aiOverviewDetails.filter((d) => d.brandMentioned).length / pav.aiOverviewDetails.length) * 100)
    : 0;

  const title = isFirstParty ? "AI Surface Presence" : "AI Visibility";

  return (
    <View>
      <Text style={s.heading}>{title}</Text>
      <Text style={s.subtext}>
        {isFirstParty
          ? "Public AI Overview observability — brand presence in AI-generated search results for industry queries."
          : "AI surface presence and brand citation across tracked industry queries."}
      </Text>

      {/* Stat strip */}
      <View style={s.statStrip}>
        <View style={s.statBox}>
          <Text style={s.statLabel}>AI Overview Coverage</Text>
          <Text style={s.statValue}>{coverageRate}%</Text>
          <Text style={s.statSub}>{pav.queriesWithAiOverview} of {pav.totalQueriesChecked} queries surfaced AI Overviews</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statLabel}>Brand Citation Rate</Text>
          <Text style={[s.statValue, { color: citationRate >= 30 ? C.green : citationRate >= 10 ? C.amber : C.red }]}>
            {citationRate}%
          </Text>
          <Text style={s.statSub}>of AI Overviews cited this brand</Text>
        </View>
        {citability != null && (
          <View style={s.statBox}>
            <Text style={s.statLabel}>Citability Score</Text>
            <Text style={[s.statValue, { color: citability >= 60 ? C.green : citability >= 30 ? C.amber : C.red }]}>
              {citability}
            </Text>
            <Text style={s.statSub}>composite AI surface score (0–100)</Text>
          </View>
        )}
      </View>

      {/* Per-query table */}
      {pav.aiOverviewDetails.length > 0 && (
        <View>
          <Text style={s.tableLabel}>Per-Query AI Overview Breakdown</Text>
          <View style={s.table}>
            <View style={s.headerRow}>
              <Text style={s.colQuery}>QUERY</Text>
              <Text style={s.colAio}>AI OVW</Text>
              <Text style={s.colMentioned}>BRAND CITED</Text>
              <Text style={s.colCompetitors}>COMPETITORS MENTIONED</Text>
            </View>
            {pav.aiOverviewDetails.slice(0, 15).map((d, i) => {
              const competitors = d.competitors ?? [];
              const compLabel = competitors.length === 0
                ? "—"
                : competitors.length <= 3
                ? competitors.join(", ")
                : `${competitors.slice(0, 3).join(", ")} and ${competitors.length - 3} more`;

              const hasAio = d.snippet != null || d.brandMentioned;

              return (
                <View
                  key={i}
                  style={[s.row, i % 2 === 1 ? s.rowAlt : {}, i === Math.min(pav.aiOverviewDetails.length, 15) - 1 ? { borderBottomWidth: 0 } : {}]}
                >
                  <Text style={s.queryText}>{d.query}</Text>
                  <Text style={hasAio ? s.aioYes : s.aioNo}>{hasAio ? "✓" : "✗"}</Text>
                  <Text style={hasAio ? (d.brandMentioned ? s.mentionedYes : s.mentionedNo) : s.mentionedNa}>
                    {hasAio ? (d.brandMentioned ? "✓" : "✗") : "—"}
                  </Text>
                  <Text style={s.competitorsText}>{compLabel}</Text>
                </View>
              );
            })}
          </View>
        </View>
      )}

      {!isFirstParty && (
        <Text style={s.footnote}>
          AI surface presence reflects publicly observable signals. First-party AI referral telemetry is not available for this audit.
        </Text>
      )}
    </View>
  );
}
