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: 14 },
  prose: { ...S.body, marginBottom: 10 },
  themesBlock: { marginTop: 16 },
  themesLabel: { ...S.label, marginBottom: 8 },
  themeRow: {
    marginBottom: 8,
    borderWidth: 0.75,
    borderColor: C.border,
    borderLeftWidth: 3,
    borderLeftColor: C.accent,
    borderRadius: 3,
    padding: 10,
    backgroundColor: C.surface,
  },
  themeTitle: { fontSize: 10, fontFamily: "Helvetica-Bold", color: C.ink, marginBottom: 2 },
  themeObs: { ...S.body, fontSize: 10, lineHeight: 1.55 },
});

function splitParagraphs(text: string): string[] {
  return text.split(/\n\n+/).map((p) => p.trim()).filter(Boolean);
}

interface Props {
  seo: SeoSection;
}

export function ExecutiveSummary({ seo }: Props) {
  const prose = seo.narrative ?? "";
  const paras = splitParagraphs(prose);

  return (
    <View>
      <Text style={s.heading}>Executive Summary</Text>
      {paras.map((p, i) => {
        if (i === 0) {
          // Bold the first sentence of the executive summary as the "hook"
          const firstDot = p.search(/[.!?]/);
          const hook = firstDot >= 0 ? p.slice(0, firstDot + 1) : p;
          const rest = firstDot >= 0 ? p.slice(firstDot + 1) : "";
          return (
            <Text key={i} style={s.prose}>
              <Text style={{ fontFamily: "Helvetica-Bold", color: "#111827" }}>{hook}</Text>
              {rest}
            </Text>
          );
        }
        return <Text key={i} style={s.prose}>{p}</Text>;
      })}
      {seo.summaryThemes && seo.summaryThemes.length > 0 && (
        <View style={s.themesBlock}>
          <Text style={s.themesLabel}>Cross-Cutting Themes</Text>
          {seo.summaryThemes.map((t, i) => (
            <View key={i} style={s.themeRow}>
              <View>
                <Text style={s.themeTitle}>{t.theme}</Text>
                <Text style={s.themeObs}>{t.observation}</Text>
              </View>
            </View>
          ))}
        </View>
      )}
    </View>
  );
}
