/**
 * Tử Vi Số · PDF report generator
 *
 * Renders a Premium-only PDF với 6 luận-giải sections + chart summary.
 * Built with @react-pdf/renderer — runs in Node, no headless browser.
 *
 * Vietnamese diacritics: registers Be Vietnam Pro TTF from public/fonts.
 * Font registration is module-scope so it only happens once per Node
 * process (the renderer caches it internally too).
 */
import { Document, Page, Text, View, StyleSheet, Font } from "@react-pdf/renderer";
import path from "node:path";
import type { Chart } from "@/lib/tuvi/engine";
import type { Horoscope } from "@/lib/tuvi/horoscope";
import type { SectionKey } from "@/lib/ai/section-prompts";

// Resolve font paths relative to the project root so this works in both
// dev (cwd=project root) and prod (Next standalone output, which copies
// public/ alongside the server bundle).
const FONT_DIR = path.join(process.cwd(), "public", "fonts", "be-vietnam-pro");

let fontsRegistered = false;
function ensureFonts() {
  if (fontsRegistered) return;
  Font.register({
    family: "Be Vietnam Pro",
    fonts: [
      { src: path.join(FONT_DIR, "Regular.ttf") },
      { src: path.join(FONT_DIR, "Bold.ttf"), fontWeight: 700 },
    ],
  });
  // Disable Latin word-wrap heuristics that mishandle some Vietnamese
  // syllable boundaries (turns "không thể" into "không-thể" splits).
  Font.registerHyphenationCallback((word) => [word]);
  fontsRegistered = true;
}

const styles = StyleSheet.create({
  page: {
    fontFamily: "Be Vietnam Pro",
    fontSize: 10,
    paddingTop: 36,
    paddingBottom: 36,
    paddingHorizontal: 40,
    color: "#1a1a1a",
    lineHeight: 1.5,
  },
  header: {
    borderBottomWidth: 1.5,
    borderBottomColor: "#b58a3a",
    paddingBottom: 12,
    marginBottom: 18,
  },
  title: { fontSize: 22, fontWeight: 700, color: "#7a4f0e" },
  subtitle: { fontSize: 10, color: "#666", marginTop: 4 },
  sectionTitle: {
    fontSize: 14,
    fontWeight: 700,
    color: "#7a4f0e",
    marginTop: 14,
    marginBottom: 6,
    borderBottomWidth: 0.5,
    borderBottomColor: "#d8a85a",
    paddingBottom: 3,
  },
  metaTable: { marginTop: 4, marginBottom: 8 },
  metaRow: { flexDirection: "row", marginBottom: 2 },
  metaLabel: { width: 130, color: "#666", fontSize: 9 },
  metaValue: { flex: 1, fontSize: 9, fontWeight: 700 },
  body: { fontSize: 10, lineHeight: 1.6, marginBottom: 6, textAlign: "justify" },
  footer: {
    position: "absolute",
    bottom: 16,
    left: 40,
    right: 40,
    fontSize: 8,
    color: "#888",
    textAlign: "center",
    borderTopWidth: 0.5,
    borderTopColor: "#ccc",
    paddingTop: 6,
  },
  watermark: {
    position: "absolute",
    top: "45%",
    left: 0,
    right: 0,
    textAlign: "center",
    fontSize: 70,
    color: "#f0e2c2",
    opacity: 0.25,
    fontWeight: 700,
    letterSpacing: 6,
  },
});

export type SectionContent = {
  key: SectionKey;
  title: string;
  body: string;
};

export type ReportProps = {
  chart: Chart;
  horoscope?: Horoscope | null;
  sections: SectionContent[];
  /** When false, draw a "TUVISO" watermark (FREE preview tier). */
  noWatermark: boolean;
  /** ISO timestamp shown in the footer. */
  generatedAt: string;
};

/**
 * Top-level report. Each section is its own block but laid out so
 * @react-pdf/renderer auto-paginates when content overflows. The footer
 * is fixed via `<Text fixed />` so it shows on every page.
 */
export function ReportDocument(props: ReportProps) {
  ensureFonts();
  const { chart, horoscope, sections, noWatermark, generatedAt } = props;

  return (
    <Document
      title={`Luận giải ${chart.fullName || "lá số"} — Tử Vi Số`}
      author="Tử Vi Số"
      creator="Tử Vi Số"
      producer="Tử Vi Số"
    >
      <Page size="A4" style={styles.page}>
        {!noWatermark ? <Text style={styles.watermark}>TUVISO</Text> : null}

        <View style={styles.header}>
          <Text style={styles.title}>Luận giải lá số tử vi</Text>
          <Text style={styles.subtitle}>
            {chart.fullName || "(Khách)"} · {chart.gender} · {chart.solarDate}
          </Text>
        </View>

        {/* Chart meta */}
        <View style={styles.metaTable}>
          <MetaRow label="Họ tên" value={chart.fullName || "(không cung cấp)"} />
          <MetaRow label="Giới tính" value={chart.gender} />
          <MetaRow label="Sinh dương lịch" value={chart.solarDate} />
          <MetaRow label="Sinh âm lịch" value={chart.lunarDate} />
          <MetaRow label="Tứ trụ" value={chart.chineseDate} />
          <MetaRow label="Cục mệnh" value={chart.fiveElements} />
          <MetaRow label="Mệnh chủ · Thân chủ" value={`${chart.soulStar} · ${chart.bodyStar}`} />
          <MetaRow label="Con giáp" value={chart.zodiac} />
          {horoscope ? (
            <MetaRow
              label="Vận trình"
              value={`Tuổi ${horoscope.age} · Đại vận ${horoscope.decadal.heavenlyStem} ${horoscope.decadal.earthlyBranch} · Lưu niên ${horoscope.yearly.heavenlyStem} ${horoscope.yearly.earthlyBranch}`}
            />
          ) : null}
        </View>

        {/* Sections */}
        {sections.map((s) => (
          <View key={s.key} wrap={false}>
            <Text style={styles.sectionTitle}>{s.title}</Text>
            <Text style={styles.body}>{s.body || "(Chưa đọc mục này)"}</Text>
          </View>
        ))}

        <Text
          style={styles.footer}
          fixed
          render={({ pageNumber, totalPages }) =>
            `Tử Vi Số · tuvi.pain.io.vn · Tạo ngày ${formatDate(generatedAt)} · Trang ${pageNumber}/${totalPages}`
          }
        />
      </Page>
    </Document>
  );
}

function MetaRow({ label, value }: { label: string; value: string }) {
  return (
    <View style={styles.metaRow}>
      <Text style={styles.metaLabel}>{label}</Text>
      <Text style={styles.metaValue}>{value}</Text>
    </View>
  );
}

function formatDate(iso: string): string {
  try {
    return new Date(iso).toLocaleString("vi-VN", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}
