import { Document, Page, View } from "@react-pdf/renderer";
import type { SeoSection } from "../types";
import { S } from "./styles";
// Existing structural components
import { Cover } from "./components/Cover";
import { PageHeader } from "./components/PageHeader";
import { PageFooter } from "./components/PageFooter";
import { ExecutiveSummary } from "./components/ExecutiveSummary";
import { ExecutiveBriefPdfSection } from "./components/ExecutiveBriefPdfSection";
import { Methodology } from "./components/Methodology";
import { ScoreSection } from "./components/ScoreSection";
import { AiSearchPerformanceLive, AiSearchPerformanceLocked } from "./components/AiSearchPerformance";
import { KeyFindings } from "./components/KeyFindings";
import { PriorityActions } from "./components/PriorityActions";
import { QuickWins } from "./components/QuickWins";
import { TechnicalHealth } from "./components/TechnicalHealth";
// New page-level sections (Block 12A FULL)
import { CompetitiveLandscapePage } from "./pages/CompetitiveLandscapePage";
import { AuthorityProfilePage } from "./pages/AuthorityProfilePage";
import { AiVisibilityPage } from "./pages/AiVisibilityPage";
import { OrganicSearchPerformancePage } from "./pages/OrganicSearchPerformancePage";
import { AiConversionAttributionPage } from "./pages/AiConversionAttributionPage";
import { ImplementationReferencePage } from "./pages/ImplementationReferencePage";
import { ScoreProjectionPage } from "./pages/ScoreProjectionPage";
import { LockedTeaserPage } from "./pages/LockedTeaserPage";
import { PagesAnalyzedPage } from "./pages/PagesAnalyzedPage";
import { SignalCenterPage } from "./pages/SignalCenterPage";
import { BilingualContentPage } from "./pages/BilingualContentPage";
import { CompetitorDeepDivePage } from "./pages/CompetitorDeepDivePage";
import { ThirdVsFirstPartyPage } from "./pages/ThirdVsFirstPartyPage";
import { SchemaOpportunityForecastPage } from "./pages/SchemaOpportunityForecastPage";
import { StrategicRoadmapPage } from "./pages/StrategicRoadmapPage";
import { IndustryBenchmarkPage } from "./pages/IndustryBenchmarkPage";
import { PageStrategicPassPage } from "./pages/PageStrategicPassPage";
import { AiEnginePersonalityPage } from "./pages/AiEnginePersonalityPage";
import { AiSourceAttributionComparisonPage } from "./pages/AiSourceAttributionComparisonPage";
import { BehavioralActionBridgePage } from "./pages/BehavioralActionBridgePage";
import { EeatAuditPage } from "./pages/EeatAuditPage";
import { AiSnippetEligibilityPage } from "./pages/AiSnippetEligibilityPage";
import { MultiTouchAiPathPage } from "./pages/MultiTouchAiPathPage";
import { RevenueAttributionPage } from "./pages/RevenueAttributionPage";
import { PredictiveConversionScoringPage } from "./pages/PredictiveConversionScoringPage";
import { ConversionHeatMapPage } from "./pages/ConversionHeatMapPage";
import { AiSearchVerificationPage } from "./pages/AiSearchVerificationPage";
import { LostOpportunityCalculatorPage } from "./pages/LostOpportunityCalculatorPage";
import { LiveVisualAnnotationsPage } from "./pages/LiveVisualAnnotationsPage";
import { CompetitorVisualComparisonPage } from "./pages/CompetitorVisualComparisonPage";
import { BrandAuthorityScorePage } from "./pages/BrandAuthorityScorePage";
import { SnippetCaptureStrategyPage } from "./pages/SnippetCaptureStrategyPage";
import { VoiceSearchEligibilityPage } from "./pages/VoiceSearchEligibilityPage";
import { MobileFirstAuditPage } from "./pages/MobileFirstAuditPage";
import { PageSpeedInsightsPage } from "./pages/PageSpeedInsightsPage";

export interface AuditPdfProps {
  brandName: string;
  website: string;
  auditDate: string;
  auditId: string;
  isFirstParty: boolean;
  seo: SeoSection;
  rawData?: {
    pagesScanned?: number;
    summary?: {
      hasSitemap?: boolean;
      hasRobotsTxt?: boolean;
      mobileFriendly?: boolean | null;
      totalPages?: number;
    };
    technicalMetrics?: {
      brokenLinksTotal?: number;
      schemaPercent?: number;
      nonIndexablePages?: number;
      redirectChainsCount?: number;
      missingTitles?: number;
      missingDescriptions?: number;
      missingH1?: number;
    };
    webVitalsSummary?: Array<{
      url: string;
      samples: number;
      lcp75?: number;
      cls75?: number;
      inp75?: number;
      ttfb75?: number;
    }>;
    // Pages for the Pages Analyzed appendix
    pages?: Array<{
      url: string;
      wordCount?: number;
      h1?: string;
      metaDescription?: string;
      schemaTypes?: string[];
      isIndexable?: boolean;
    }>;
    totalPagesDiscovered?: number;
  } | null;
}

export function AuditPdf({
  brandName, website, auditDate, isFirstParty, seo, rawData,
}: AuditPdfProps) {
  const displayName = seo.displayName || brandName;
  const hasCompetitive = !!(seo.competitiveLandscape?.topCompetitors?.length);
  const hasCompetitorDeepDive = !!(seo.competitorAnalysis);
  const hasSchemaForecast = !!(seo.schemaOpportunityForecast);
  const hasStrategicRoadmap = !!(seo.strategicRoadmap?.phases?.length);
  const hasPageStrategicPass = !!(seo.pageStrategicPass?.pages?.length);
  const hasIndustryBenchmark = !!(seo.industryBenchmarkComparison);
  const hasAuthority = !!(seo.backlinkProfile && (seo.backlinkProfile.referringDomains || seo.backlinkProfile.totalBacklinks));
  const hasOrganic = isFirstParty && !!seo.organicSearchSummary;
  const hasAiConversion = isFirstParty && !!seo.aiConversionAttribution;
  // ImplementationReferencePage renders null internally if no data (with console.warn).
  // Gate removed — render unconditionally and let the component decide.
  const hasLockedTeaser = !isFirstParty && !!seo.lockedFirstPartyTeaser;
  const hasAiAttribComparison = isFirstParty && !!(seo.aiSourceAttributionComparison?.hasFirstPartyData);
  const hasBehavioralBridge = isFirstParty && !!(seo.behavioralActionBridge);
  const hasMultiTouchPath = isFirstParty && !!(seo.multiTouchAiPath);
  const hasRevenueAttribution = isFirstParty && !!(seo.revenueAttribution?.hasRevenueTracking);
  const hasPredictiveScoring = isFirstParty && !!(seo.predictiveConversionScoring);
  const hasConversionHeatMap = isFirstParty && !!(seo.conversionHeatMap);
  const hasAiSearchVerification = !!(seo.aiSearchVerification);
  const hasLostOpportunity = !!(seo.lostOpportunityCalculation?.hasCalculation);
  const hasLiveVisualAnnotations = !!(seo.liveVisualAnnotations?.hasAnnotations);
  const hasCompetitorVisualComparison = !!(seo.competitorVisualComparison?.hasComparison);
  const hasBrandAuthorityScore = !!(seo.brandAuthorityScore?.hasScore);
  const hasSnippetCaptureStrategy = !!(seo.snippetCaptureStrategy?.hasStrategy && (seo.snippetCaptureStrategy?.totalReformulationsGenerated ?? 0) > 0);
  const hasVoiceSearch = !!(seo.voiceSearchEligibility?.hasData);
  const hasMobileFirstAudit = !!(seo.mobileFirstAudit?.hasAudit);
  const hasPageSpeedInsights = !!(seo.pageSpeedInsights?.hasInsights);
  const opportunityContext = seo.lostOpportunityCalculation?.confidence !== "low" && seo.lostOpportunityCalculation
    ? { totalMonthlyUsd: seo.lostOpportunityCalculation.aggregateOpportunity.totalMonthlyOpportunityUsd, confidence: seo.lostOpportunityCalculation.confidence }
    : null;
  const rawPages = rawData?.pages;
  const totalPagesCrawled = rawData?.totalPagesDiscovered;
  const pagesScanned = rawData?.pagesScanned;

  return (
    <Document
      title={`meSEO Audit — ${brandName}`}
      author="meSEO"
      subject="AI Search Visibility Audit"
      creator="meSEO Audit Engine"
    >
      {/* ── Cover page ── */}
      <Cover
        brandName={displayName}
        website={website}
        auditDate={auditDate}
        score={seo.healthScore}
        isFirstParty={isFirstParty}
        siteTagDaysActive={seo.siteTagContext?.daysActive}
        aiTrend={seo.aiSearchPerformance?.trendVsTrailing90d}
      />

      {/* ── Content pages ── */}
      <Page size="LETTER" style={S.contentPage}>
        <PageHeader sectionName="AI Search Visibility Report" brandName={displayName} />
        <PageFooter isFirstParty={isFirstParty} />

        {/* 1. Executive Brief (expanded) or fallback to legacy Executive Summary */}
        {seo.executiveBrief
          ? <ExecutiveBriefPdfSection brief={seo.executiveBrief} isFirstParty={isFirstParty} opportunityContext={opportunityContext} />
          : <ExecutiveSummary seo={seo} />
        }

        {/* 2. Industry Framework + Audit Methodology */}
        {(seo.methodology || seo.industryFramework) && (
          <View break>
            <Methodology seo={seo} />
          </View>
        )}

        {/* 3. SEO Health Score (5 dimensions) */}
        <View break>
          <ScoreSection seo={seo} />
        </View>

        {/* ── 1ST-PARTY SECTION ORDER ── */}
        {isFirstParty && (
          <>
            {/* 4. AI Search Performance (live first-party referral data) */}
            <View break>
              {seo.aiSearchPerformance
                ? <AiSearchPerformanceLive data={seo.aiSearchPerformance} siteTagContext={seo.siteTagContext} />
                : <AiSearchPerformanceLocked />
              }
            </View>

            {/* 4b. AI Surface Presence (public observability — augments above) */}
            {seo.publicAiVisibility && (
              <View break>
                <AiVisibilityPage seo={seo} isFirstParty={true} />
              </View>
            )}

            {/* 4c. AI Snippet Eligibility (conditional — both audit types) */}
            {seo.aiSnippetEligibility && (
              <View break>
                <AiSnippetEligibilityPage aiSnippetEligibility={seo.aiSnippetEligibility} />
              </View>
            )}

            {/* 4c-2. Snippet Capture Strategy (conditional — both audit types; not in Executive Brief) */}
            {hasSnippetCaptureStrategy && (
              <View break>
                <SnippetCaptureStrategyPage snippetCaptureStrategy={seo.snippetCaptureStrategy!} />
              </View>
            )}

            {/* 4c-3. Voice Search Eligibility (conditional — both audit types) */}
            {hasVoiceSearch && (
              <View break>
                <VoiceSearchEligibilityPage voiceSearchEligibility={seo.voiceSearchEligibility!} />
              </View>
            )}

            {/* 4d. AI Engine Profiles (always present) */}
            {seo.aiEnginePersonalityAnalysis && (
              <View break>
                <AiEnginePersonalityPage aiEnginePersonalityAnalysis={seo.aiEnginePersonalityAnalysis} />
              </View>
            )}

            {/* 5. AI Conversion Attribution */}
            {hasAiConversion && (
              <View break>
                <AiConversionAttributionPage seo={seo} />
              </View>
            )}

            {/* 6. Signal Center (behavioral telemetry — 1st-party only) */}
            {seo.signalCenter && (
              <View break>
                <SignalCenterPage seo={seo} />
              </View>
            )}

            {/* 6b. Public vs First-Party Attribution Comparison (conditional — 1st-party only) */}
            {hasAiAttribComparison && (
              <View break>
                <AiSourceAttributionComparisonPage aiSourceAttributionComparison={seo.aiSourceAttributionComparison!} />
              </View>
            )}

            {/* 6c. Multi-Touch AI Path Analysis (conditional — 1st-party only) */}
            {hasMultiTouchPath && (
              <View break>
                <MultiTouchAiPathPage multiTouchAiPath={seo.multiTouchAiPath!} />
              </View>
            )}

            {/* 6d. Revenue Attribution (conditional — 1st-party only) */}
            {hasRevenueAttribution && (
              <View break>
                <RevenueAttributionPage revenueAttribution={seo.revenueAttribution!} />
              </View>
            )}

            {/* 6e. Predictive Conversion Scoring (conditional — 1st-party only, not in Executive Brief) */}
            {hasPredictiveScoring && (
              <View break>
                <PredictiveConversionScoringPage predictiveConversionScoring={seo.predictiveConversionScoring!} />
              </View>
            )}

            {/* 6f. Conversion Heat Map (conditional — 1st-party only, not in Executive Brief) */}
            {hasConversionHeatMap && (
              <View break>
                <ConversionHeatMapPage conversionHeatMap={seo.conversionHeatMap!} />
              </View>
            )}

            {/* 6g. Live Visual Annotations (conditional — both audit types, not in Executive Brief) */}
            {hasLiveVisualAnnotations && (
              <View break>
                <LiveVisualAnnotationsPage liveVisualAnnotations={seo.liveVisualAnnotations!} />
              </View>
            )}

            {/* 6h. AI Search Verification (conditional — both audit types, not in Executive Brief) */}
            {hasAiSearchVerification && (
              <View break>
                <AiSearchVerificationPage aiSearchVerification={seo.aiSearchVerification!} />
              </View>
            )}

            {/* 6i. Competitor Visual Comparison (conditional — both audit types, not in Executive Brief) */}
            {hasCompetitorVisualComparison && (
              <View break>
                <CompetitorVisualComparisonPage competitorVisualComparison={seo.competitorVisualComparison!} />
              </View>
            )}

            {/* 7. Multi-Language Presence (conditional — bilingual brands only) */}
            {seo.bilingualAudit && (
              <View break>
                <BilingualContentPage bilingualAudit={seo.bilingualAudit} />
              </View>
            )}

            {/* 7b. Competitor Deep Dive (conditional) */}
            {hasCompetitorDeepDive && (
              <View break>
                <CompetitorDeepDivePage competitorAnalysis={seo.competitorAnalysis!} />
              </View>
            )}

            {/* 8. Organic Search Performance (conditional on GSC) */}
            {hasOrganic && (
              <View break>
                <OrganicSearchPerformancePage seo={seo} />
              </View>
            )}

            {/* 8. Competitive Landscape */}
            {hasCompetitive && (
              <View break>
                <CompetitiveLandscapePage seo={seo} />
              </View>
            )}

            {/* 9. Authority Profile */}
            {hasAuthority && (
              <View break>
                <AuthorityProfilePage seo={seo} />
              </View>
            )}

            {/* 9b. E-E-A-T Audit (always present) */}
            {seo.eeatAudit && (
              <View break>
                <EeatAuditPage eeatAudit={seo.eeatAudit} />
              </View>
            )}

            {/* 9b-2. Brand Authority Score (conditional — both audit types; not in Executive Brief) */}
            {hasBrandAuthorityScore && (
              <View break>
                <BrandAuthorityScorePage brandAuthorityScore={seo.brandAuthorityScore!} />
              </View>
            )}

            {/* 9b-3. Mobile-First Audit (conditional — both audit types; not in Executive Brief) */}
            {hasMobileFirstAudit && (
              <View break>
                <MobileFirstAuditPage mobileFirstAudit={seo.mobileFirstAudit!} />
              </View>
            )}

            {/* 9b-4. Page Speed Insights (conditional — both audit types; not in Executive Brief) */}
            {hasPageSpeedInsights && (
              <View break>
                <PageSpeedInsightsPage pageSpeedInsights={seo.pageSpeedInsights!} />
              </View>
            )}

            {/* 9c. Industry Benchmark (conditional) */}
            {hasIndustryBenchmark && (
              <View break>
                <IndustryBenchmarkPage benchmarkComparison={seo.industryBenchmarkComparison!} />
              </View>
            )}

            {/* 10. Pages Deeply Reviewed — appendix before analysis sections */}
            <View break>
              <PagesAnalyzedPage
                seo={seo}
                isFirstParty={true}
                rawPages={rawPages}
                totalPagesCrawled={totalPagesCrawled}
                pagesScanned={pagesScanned}
              />
            </View>

            {/* 11. Key Findings */}
            <View break>
              <KeyFindings seo={seo} />
            </View>

            {/* 12. Priority Actions */}
            <View break>
              <PriorityActions seo={seo} />
            </View>

            {/* 12b. Behavioral Action Bridge (conditional — 1st-party only) */}
            {hasBehavioralBridge && (
              <View break>
                <BehavioralActionBridgePage behavioralActionBridge={seo.behavioralActionBridge!} />
              </View>
            )}

            {/* 13. Quick Wins */}
            <View break>
              <QuickWins seo={seo} />
            </View>

            {/* 13b. Lost Opportunity Calculator (conditional — both audit types) */}
            {hasLostOpportunity && (
              <View break>
                <LostOpportunityCalculatorPage lostOpportunityCalculation={seo.lostOpportunityCalculation!} />
              </View>
            )}

            {/* 14. Implementation Reference (paste-ready code per priority action, both audit types) */}
            <View break>
              <ImplementationReferencePage seo={seo} />
            </View>

            {/* 15. Score Projection */}
            <View break>
              <ScoreProjectionPage seo={seo} auditType="1st" />
            </View>

            {/* 16. Technical Health Diagnostics */}
            <View break>
              <TechnicalHealth rawData={rawData} />
            </View>

            {/* 17. Page-by-Page Review (conditional) */}
            {hasPageStrategicPass && (
              <View break>
                <PageStrategicPassPage pageStrategicPass={seo.pageStrategicPass!} />
              </View>
            )}

            {/* 18. Schema Opportunity Forecast (conditional) */}
            {hasSchemaForecast && (
              <View break>
                <SchemaOpportunityForecastPage schemaForecast={seo.schemaOpportunityForecast!} />
              </View>
            )}

            {/* 19. Strategic Roadmap (conditional) */}
            {hasStrategicRoadmap && (
              <View break>
                <StrategicRoadmapPage strategicRoadmap={seo.strategicRoadmap!} />
              </View>
            )}
          </>
        )}

        {/* ── 3RD-PARTY SECTION ORDER ── */}
        {!isFirstParty && (
          <>
            {/* 4. AI Visibility (public observability only — replaces AI Search Performance) */}
            <View break>
              <AiVisibilityPage seo={seo} isFirstParty={false} />
            </View>

            {/* 4b. AI Snippet Eligibility (conditional — both audit types) */}
            {seo.aiSnippetEligibility && (
              <View break>
                <AiSnippetEligibilityPage aiSnippetEligibility={seo.aiSnippetEligibility} />
              </View>
            )}

            {/* 4b-2. Snippet Capture Strategy (conditional — both audit types; not in Executive Brief) */}
            {hasSnippetCaptureStrategy && (
              <View break>
                <SnippetCaptureStrategyPage snippetCaptureStrategy={seo.snippetCaptureStrategy!} />
              </View>
            )}

            {/* 4b-3. Voice Search Eligibility (conditional — both audit types) */}
            {hasVoiceSearch && (
              <View break>
                <VoiceSearchEligibilityPage voiceSearchEligibility={seo.voiceSearchEligibility!} />
              </View>
            )}

            {/* 4c. AI Engine Profiles (always present) */}
            {seo.aiEnginePersonalityAnalysis && (
              <View break>
                <AiEnginePersonalityPage aiEnginePersonalityAnalysis={seo.aiEnginePersonalityAnalysis} />
              </View>
            )}

            {/* 5. Competitive Landscape */}
            {hasCompetitive && (
              <View break>
                <CompetitiveLandscapePage seo={seo} />
              </View>
            )}

            {/* 6. Authority Profile */}
            {hasAuthority && (
              <View break>
                <AuthorityProfilePage seo={seo} />
              </View>
            )}

            {/* 6a. E-E-A-T Audit (always present) */}
            {seo.eeatAudit && (
              <View break>
                <EeatAuditPage eeatAudit={seo.eeatAudit} />
              </View>
            )}

            {/* 6a-2. Brand Authority Score (conditional — both audit types; not in Executive Brief) */}
            {hasBrandAuthorityScore && (
              <View break>
                <BrandAuthorityScorePage brandAuthorityScore={seo.brandAuthorityScore!} />
              </View>
            )}

            {/* 6a-3. Mobile-First Audit (conditional — both audit types; not in Executive Brief) */}
            {hasMobileFirstAudit && (
              <View break>
                <MobileFirstAuditPage mobileFirstAudit={seo.mobileFirstAudit!} />
              </View>
            )}

            {/* 6a-4. Page Speed Insights (conditional — both audit types; not in Executive Brief) */}
            {hasPageSpeedInsights && (
              <View break>
                <PageSpeedInsightsPage pageSpeedInsights={seo.pageSpeedInsights!} />
              </View>
            )}

            {/* 6b. Industry Benchmark (conditional) */}
            {hasIndustryBenchmark && (
              <View break>
                <IndustryBenchmarkPage benchmarkComparison={seo.industryBenchmarkComparison!} />
              </View>
            )}

            {/* 6c. Live Visual Annotations (conditional — both audit types) */}
            {hasLiveVisualAnnotations && (
              <View break>
                <LiveVisualAnnotationsPage liveVisualAnnotations={seo.liveVisualAnnotations!} />
              </View>
            )}

            {/* 6d. AI Search Verification (conditional — both audit types) */}
            {hasAiSearchVerification && (
              <View break>
                <AiSearchVerificationPage aiSearchVerification={seo.aiSearchVerification!} />
              </View>
            )}

            {/* 6e. Competitor Visual Comparison (conditional — both audit types) */}
            {hasCompetitorVisualComparison && (
              <View break>
                <CompetitorVisualComparisonPage competitorVisualComparison={seo.competitorVisualComparison!} />
              </View>
            )}

            {/* 6f. Competitor Deep Dive (conditional) */}
            {hasCompetitorDeepDive && (
              <View break>
                <CompetitorDeepDivePage competitorAnalysis={seo.competitorAnalysis!} />
              </View>
            )}

            {/* 7. Multi-Language Presence (conditional — bilingual brands only) */}
            {seo.bilingualAudit && (
              <View break>
                <BilingualContentPage bilingualAudit={seo.bilingualAudit} />
              </View>
            )}

            {/* 8. Pages Deeply Reviewed — appendix before analysis sections */}
            <View break>
              <PagesAnalyzedPage
                seo={seo}
                isFirstParty={false}
                rawPages={rawPages}
                totalPagesCrawled={totalPagesCrawled}
                pagesScanned={pagesScanned}
              />
            </View>

            {/* 8. Key Findings */}
            <View break>
              <KeyFindings seo={seo} />
            </View>

            {/* 9. Priority Actions */}
            <View break>
              <PriorityActions seo={seo} />
            </View>

            {/* 10. Quick Wins */}
            <View break>
              <QuickWins seo={seo} />
            </View>

            {/* 10b. Lost Opportunity Calculator (conditional — both audit types) */}
            {hasLostOpportunity && (
              <View break>
                <LostOpportunityCalculatorPage lostOpportunityCalculation={seo.lostOpportunityCalculation!} />
              </View>
            )}

            {/* 11. Implementation Reference (paste-ready code per priority action, both audit types) */}
            <View break>
              <ImplementationReferencePage seo={seo} />
            </View>

            {/* 12. 3rd vs 1st Party Comparison (3rd-party only) */}
            <View break>
              <ThirdVsFirstPartyPage />
            </View>

            {/* 13. Score Projection */}
            <View break>
              <ScoreProjectionPage seo={seo} auditType="3rd" />
            </View>

            {/* 14. Technical Health Diagnostics */}
            <View break>
              <TechnicalHealth rawData={rawData} />
            </View>

            {/* 15. Page-by-Page Review (conditional) */}
            {hasPageStrategicPass && (
              <View break>
                <PageStrategicPassPage pageStrategicPass={seo.pageStrategicPass!} />
              </View>
            )}

            {/* 16. Schema Opportunity Forecast (conditional) */}
            {hasSchemaForecast && (
              <View break>
                <SchemaOpportunityForecastPage schemaForecast={seo.schemaOpportunityForecast!} />
              </View>
            )}

            {/* 17. Strategic Roadmap (conditional) */}
            {hasStrategicRoadmap && (
              <View break>
                <StrategicRoadmapPage strategicRoadmap={seo.strategicRoadmap!} />
              </View>
            )}

            {/* 17. Locked Teaser — sits near end after reader has consumed full analysis */}
            {hasLockedTeaser && (
              <View break>
                <LockedTeaserPage seo={seo} isFirstParty={false} />
              </View>
            )}
          </>
        )}
      </Page>
    </Document>
  );
}
