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: 4 },
  subheading: { fontSize: 12, color: C.muted, fontFamily: "Helvetica", marginBottom: 16 },
  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.4 },
  // Table
  tableLabel: { ...S.label, marginBottom: 7 },
  table: {
    borderWidth: 0.75,
    borderColor: C.border,
    borderRadius: 4,
    overflow: "hidden",
    marginBottom: 14,
  },
  headerRow: {
    flexDirection: "row",
    backgroundColor: C.surface,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderBottomWidth: 0.75,
    borderBottomColor: C.border,
  },
  row: {
    flexDirection: "row",
    paddingHorizontal: 12,
    paddingVertical: 9,
    borderBottomWidth: 0.5,
    borderBottomColor: "#f1f5f9",
    alignItems: "center",
  },
  rowAlt: { backgroundColor: "#fafafa" },
  colDomain: { flex: 2.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  colKeywords: { flex: 1.5, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8, textAlign: "center" },
  colLossQuery: { flex: 4, fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.muted, letterSpacing: 0.8 },
  domainText: { flex: 2.5, fontSize: 9.5, color: C.accent, fontFamily: "Helvetica-Bold" },
  keywordsText: { flex: 1.5, fontSize: 9.5, color: C.body, textAlign: "center" },
  lossQueryText: { flex: 4, fontSize: 8.5, color: C.muted, lineHeight: 1.4 },
  // Callout
  citationWarning: {
    borderWidth: 1,
    borderColor: C.red,
    borderRadius: 4,
    padding: 12,
    backgroundColor: "#fef2f2",
  },
  citationWarningText: { fontSize: 9.5, color: "#991b1b", lineHeight: 1.55 },
});

function fmtPct(n: number | undefined | null): string {
  if (n == null) return "—";
  return `${n.toFixed(0)}%`;
}

function subheader(seo: SeoSection): string {
  const sub = seo.industryFramework?.subVertical;
  const loc = seo.brandEcho?.locations?.[0];
  if (!sub && !loc) return "AI and organic search visibility in your competitive market";
  if (sub && loc) return `${sub} — ${loc}`;
  return sub ?? loc ?? "";
}

interface Props {
  seo: SeoSection;
}

export function CompetitiveLandscapePage({ seo }: Props) {
  const cl = seo.competitiveLandscape;
  if (!cl || cl.topCompetitors.length === 0) return null;

  const details = cl.topCompetitorDetails ?? [];
  const rows = cl.topCompetitors.slice(0, 5).map((domain) => {
    const d = details.find((x) => x.domain === domain);
    return { domain, sharedKeywords: d?.sharedKeywords, topBrandLossQuery: d?.topBrandLossQuery };
  });

  const showCitationWarning =
    cl.aiOverviewBrandCitationRate != null && cl.aiOverviewBrandCitationRate < 30;

  return (
    <View>
      <Text style={s.heading}>Competitive Landscape</Text>
      <Text style={s.subheading}>{subheader(seo)}</Text>

      {/* Stat strip */}
      <View style={s.statStrip}>
        {cl.serpShareOfVoice != null && (
          <View style={s.statBox}>
            <Text style={s.statLabel}>SERP Share of Voice</Text>
            <Text style={[s.statValue, {
              color: cl.serpShareOfVoice >= 20 ? C.green : cl.serpShareOfVoice >= 8 ? C.amber : C.red,
            }]}>
              {fmtPct(cl.serpShareOfVoice)}
            </Text>
            <Text style={s.statSub}>Visibility across tracked industry queries</Text>
          </View>
        )}
        <View style={s.statBox}>
          <Text style={s.statLabel}>AI Overview Coverage</Text>
          <Text style={s.statValue}>{fmtPct(cl.aiOverviewCoveragePercent)}</Text>
          <Text style={s.statSub}>AI Overview surfaced in tracked queries</Text>
        </View>
        <View style={s.statBox}>
          <Text style={s.statLabel}>Brand Citation Rate</Text>
          <Text style={[s.statValue, {
            color: cl.aiOverviewBrandCitationRate >= 30 ? C.green : cl.aiOverviewBrandCitationRate >= 10 ? C.amber : C.red,
          }]}>
            {fmtPct(cl.aiOverviewBrandCitationRate)}
          </Text>
          <Text style={s.statSub}>Brand cited when AI Overview is present</Text>
        </View>
      </View>

      {/* Top competitors table */}
      <Text style={s.tableLabel}>Top Competitors</Text>
      <View style={s.table}>
        <View style={s.headerRow}>
          <Text style={s.colDomain}>DOMAIN</Text>
          <Text style={s.colKeywords}>SHARED KW</Text>
          <Text style={s.colLossQuery}>TOP BRAND LOSS QUERY</Text>
        </View>
        {rows.map((r, i) => (
          <View key={i} style={[s.row, i % 2 === 1 ? s.rowAlt : {}, i === rows.length - 1 ? { borderBottomWidth: 0 } : {}]}>
            <Text style={s.domainText}>{r.domain}</Text>
            <Text style={s.keywordsText}>{r.sharedKeywords != null ? String(r.sharedKeywords) : "—"}</Text>
            <Text style={s.lossQueryText}>{r.topBrandLossQuery ?? "—"}</Text>
          </View>
        ))}
      </View>

      {/* Low citation rate warning */}
      {showCitationWarning && (
        <View style={s.citationWarning}>
          <Text style={s.citationWarningText}>
            {`Brand cited in AI Overview for only ${cl.aiOverviewBrandCitationRate.toFixed(0)}% of tracked queries. Schema and content gaps identified in Key Findings directly affect AI surface presence.`}
          </Text>
        </View>
      )}
    </View>
  );
}
