'use client';

import './styles/report-brand.css';
import { useState, useRef, useEffect } from 'react';
import type { ReportSynthesis } from './types';
import type { ReportLocale } from './i18n/useReportLocale';
import { countPages, countTrendsCharts, countTrendsPages } from './utils/paginate';
import CoverPage from './sections/CoverPage';
import TableOfContents from './sections/TableOfContents';
import HowToRead from './sections/HowToRead';
import ExecutiveSummary from './sections/ExecutiveSummary';
import RatingDashboard from './sections/RatingDashboard';
import ThemeAnalysis from './sections/ThemeAnalysis';
import DomainPerformance from './sections/DomainPerformance';
import TrendsTimeline from './sections/TrendsTimeline';
import CriticalIssues from './sections/CriticalIssues';
import StrengthsToProtect from './sections/StrengthsToProtect';
import StaffLeaderboard from './sections/StaffLeaderboard';
import ActionPlan from './sections/ActionPlan';
import TrackingFramework from './sections/TrackingFramework';
import EndPage from './sections/EndPage';
import ReviewEvidence from './sections/ReviewEvidence';
import { useReportLocale } from './i18n/useReportLocale';

interface ReputationBlueprintProps {
  report: ReportSynthesis;
}

export default function ReputationBlueprint({ report }: ReputationBlueprintProps) {
  const reportLang: ReportLocale = report.language === 'es' ? 'es' : 'en';
  const [locale, setLocale] = useState<ReportLocale>(reportLang);
  const reportRef = useRef<HTMLDivElement>(null);
  const [reportReady, setReportReady] = useState(false);
  useEffect(() => {
    const timer = setTimeout(() => setReportReady(true), 1500);
    return () => clearTimeout(timer);
  }, []);

  const hasStaff = Array.isArray(report.staff_leaderboard)
    ? report.staff_leaderboard.length > 0
    : !!(report.staff_leaderboard && (
        (report.staff_leaderboard as any).individuals?.length > 0 ||
        (report.staff_leaderboard as any).groups?.length > 0
      ));
  const hasReviewEvidence = !!report.review_evidence?.length;
  const hasConclusion = !!report.conclusion;
  const hasTrends = countTrendsCharts(report) > 0;
  const trendsPages = countTrendsPages(report);
  const reviewEvidenceFiltered = (report.review_evidence || []).filter(r => r.full_text?.length > 0);

  // Dynamic page counting per section
  const issuePages = countPages(report.critical_issues.length, 2, 3) || 1;
  const strengthPages = countPages(report.strengths.length, 2, 3) || 1;
  const actionPages = countPages(report.actions.length, 3, 4) || 1;
  const staffCount = hasStaff
    ? (Array.isArray(report.staff_leaderboard)
        ? report.staff_leaderboard.length
        : ((report.staff_leaderboard as any)?.individuals?.length || 0) + ((report.staff_leaderboard as any)?.groups?.length || 0))
    : 0;
  const staffPages = hasStaff ? (countPages(staffCount, 6, 12) || 1) : 0;
  const trackingPages = report.kpis.length > 0 ? 1 : 0;
  const reviewEvidencePages = hasReviewEvidence ? (countPages(reviewEvidenceFiltered.length, 3, 4) || 1) : 0;

  const { t } = useReportLocale(locale);

  // Running page offsets
  // Order: Cover → ToC → HowToRead → Exec → Rating → Theme → Domain → Trends → Issues → Strengths → Staff → Action → Tracking → EndPage → Appendix
  let page = 1;
  const coverStart = page; page += 1;
  const tocStart = page; page += 1;
  const howToReadStart = page; page += 1;
  const execStart = page; page += 1;
  const ratingStart = page; page += 1;
  const themeStart = page; page += 1;
  const domainStart = page; page += 1;
  const trendsStart = page; page += trendsPages;
  const issueStart = page; page += issuePages;
  const strengthStart = page; page += strengthPages;
  const staffStart = page; page += staffPages;
  const actionStart = page; page += actionPages;
  const trackingStart = page; page += trackingPages;
  const endPageStart = page; page += (hasConclusion ? 1 : 0);
  const reviewEvidenceStart = page; page += reviewEvidencePages;

  const TOTAL_PAGES = page - 1;

  // Dynamic section numbers (numbered sections start at Exec Summary = 1)
  let nextSection = 5;
  const trendsSectionNum = nextSection; if (hasTrends) nextSection++;
  const issueSectionNum = nextSection; nextSection++;
  const strengthSectionNum = nextSection; nextSection++;
  const staffSectionNum = nextSection; if (hasStaff) nextSection++;
  const actionSectionNum = nextSection; nextSection++;
  const trackingSectionNum = nextSection; if (report.kpis.length > 0) nextSection++;
  const endPageSectionNum = nextSection; if (hasConclusion) nextSection++;
  // ReviewEvidence uses "A" (appendix label, not a number)

  // Build ToC entries with anchor IDs for smooth-scroll navigation
  const tocEntries: { number: string | number; title: string; page: number; anchorId: string; description?: string }[] = [
    { number: 1, title: t('executive_summary'), page: execStart, anchorId: 'section-exec', description: t('toc_desc_executive_summary') },
    { number: 2, title: t('rating_dashboard'), page: ratingStart, anchorId: 'section-rating', description: t('toc_desc_rating_dashboard') },
    { number: 3, title: t('theme_analysis'), page: themeStart, anchorId: 'section-themes', description: t('toc_desc_theme_analysis') },
    { number: 4, title: t('domain_performance'), page: domainStart, anchorId: 'section-domains', description: t('toc_desc_domain_performance') },
    ...(hasTrends ? [{ number: trendsSectionNum, title: t('trends_timeline'), page: trendsStart, anchorId: 'section-trends', description: t('toc_desc_trends_timeline') }] : []),
    { number: issueSectionNum, title: t('critical_issues'), page: issueStart, anchorId: 'section-issues', description: t('toc_desc_critical_issues') },
    { number: strengthSectionNum, title: t('protect_strengths'), page: strengthStart, anchorId: 'section-strengths', description: t('toc_desc_strengths') },
  ];
  if (hasStaff) tocEntries.push({ number: staffSectionNum, title: t('staff_leaderboard'), page: staffStart, anchorId: 'section-staff', description: t('toc_desc_staff_leaderboard') });
  tocEntries.push({ number: actionSectionNum, title: t('action_plan'), page: actionStart, anchorId: 'section-actions', description: t('toc_desc_action_plan') });
  if (report.kpis.length > 0) tocEntries.push({ number: trackingSectionNum, title: t('tracking_framework'), page: trackingStart, anchorId: 'section-tracking', description: t('toc_desc_tracking_framework') });
  if (hasReviewEvidence) tocEntries.push({ number: 'A', title: t('appendix_review_evidence'), page: reviewEvidenceStart, anchorId: 'section-evidence', description: t('toc_desc_review_evidence') });

  return (
    <div data-report-ready={reportReady ? "true" : undefined} style={{ minHeight: '100vh', background: '#E2E8F0' }}>
      {/* Top Bar */}
      <div className="report-toolbar" style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: 'white', borderBottom: '1px solid var(--border-light)',
        padding: '12px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'
      }}>
        <div>
          <h1 style={{ fontSize: 16, fontWeight: 600, color: 'var(--text-primary)' }}>{report.business_name}</h1>
          <p style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
            Reputation Blueprint &middot; {report.report_date}
          </p>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {/* Language Selector */}
          <div style={{ display: 'flex', borderRadius: 8, overflow: 'hidden', border: '1px solid var(--border-light)' }}>
            <button
              onClick={() => setLocale('en')}
              style={{
                padding: '6px 14px', fontSize: 13, fontWeight: 500, border: 'none', cursor: 'pointer',
                background: locale === 'en' ? 'var(--ui-primary)' : 'white',
                color: locale === 'en' ? 'white' : 'var(--text-secondary)',
              }}
            >
              EN
            </button>
            <button
              onClick={() => setLocale('es')}
              style={{
                padding: '6px 14px', fontSize: 13, fontWeight: 500, border: 'none', cursor: 'pointer',
                borderLeft: '1px solid var(--border-light)',
                background: locale === 'es' ? 'var(--ui-primary)' : 'white',
                color: locale === 'es' ? 'white' : 'var(--text-secondary)',
              }}
            >
              ES
            </button>
          </div>
        </div>
      </div>

      {/* Report Content */}
      <div ref={reportRef} style={{ maxWidth: 1024, margin: '24px auto', paddingBottom: 48 }}>
        <CoverPage report={report} locale={locale} pageNumber={coverStart} totalPages={TOTAL_PAGES} />
        <TableOfContents entries={tocEntries} locale={locale} pageNumber={tocStart} totalPages={TOTAL_PAGES} />
        <HowToRead locale={locale} pageNumber={howToReadStart} totalPages={TOTAL_PAGES} />
        <div id="section-exec"><ExecutiveSummary report={report} locale={locale} pageNumber={execStart} totalPages={TOTAL_PAGES} /></div>
        <div id="section-rating"><RatingDashboard report={report} locale={locale} pageNumber={ratingStart} totalPages={TOTAL_PAGES} /></div>
        <div id="section-themes"><ThemeAnalysis report={report} locale={locale} pageNumber={themeStart} totalPages={TOTAL_PAGES} /></div>
        <div id="section-domains"><DomainPerformance report={report} locale={locale} pageNumber={domainStart} totalPages={TOTAL_PAGES} /></div>
        {hasTrends && <div id="section-trends"><TrendsTimeline report={report} locale={locale} startPage={trendsStart} totalPages={TOTAL_PAGES} sectionNumber={trendsSectionNum} /></div>}
        <div id="section-issues"><CriticalIssues report={report} locale={locale} startPage={issueStart} totalPages={TOTAL_PAGES} sectionNumber={issueSectionNum} /></div>
        <div id="section-strengths"><StrengthsToProtect report={report} locale={locale} startPage={strengthStart} totalPages={TOTAL_PAGES} sectionNumber={strengthSectionNum} /></div>
        {hasStaff && <div id="section-staff"><StaffLeaderboard report={report} locale={locale} startPage={staffStart} totalPages={TOTAL_PAGES} sectionNumber={staffSectionNum} /></div>}
        <div id="section-actions"><ActionPlan report={report} locale={locale} startPage={actionStart} totalPages={TOTAL_PAGES} sectionNumber={actionSectionNum} /></div>
        <div id="section-tracking"><TrackingFramework report={report} locale={locale} pageNumber={trackingStart} totalPages={TOTAL_PAGES} sectionNumber={trackingSectionNum} /></div>
        {hasConclusion && <EndPage report={report} locale={locale} pageNumber={endPageStart} totalPages={TOTAL_PAGES} />}
        {hasReviewEvidence && <div id="section-evidence"><ReviewEvidence report={report} locale={locale} startPage={reviewEvidenceStart} totalPages={TOTAL_PAGES} sectionNumber={'A'} /></div>}
      </div>
    </div>
  );
}
