'use client';

import type { ReportSynthesis } from '../types';
import type { ReportLocale } from '../i18n/useReportLocale';
import { useReportLocale } from '../i18n/useReportLocale';
import ReportPage from '../components/ReportPage';
import SectionHeader from '../components/SectionHeader';
import { getScoreColor } from '../styles/report-theme';
import { translateLevel, translateTimeline } from '../i18n/contentTranslations';

const PILLAR_KEYS = ['rating_quality', 'sentiment_depth', 'volume', 'momentum', 'intensity'] as const;
const PILLAR_MAX: Record<string, number> = {
  rating_quality: 30, sentiment_depth: 25, volume: 15, momentum: 15, intensity: 15,
};

interface ExecutiveSummaryProps {
  report: ReportSynthesis;
  locale?: ReportLocale;
  pageNumber?: number;
  totalPages?: number;
}

export default function ExecutiveSummary({ report, locale = 'en', pageNumber = 2, totalPages = 9 }: ExecutiveSummaryProps) {
  const { t } = useReportLocale(locale);
  const scoreColor = getScoreColor(report.reputation_score);
  const topActions = report.actions.slice(0, 3);
  const breakdown = report.score_breakdown;

  return (
    <ReportPage pageNumber={pageNumber} totalPages={totalPages} background="white">
      <SectionHeader number={1} title={t('executive_summary')} subtitle={t('executive_summary_lead')} />

      {/* Verdict */}
      {report.verdict && (
        <div className="insight-callout">
          <p className="body-lg text-primary" style={{ fontWeight: 500 }}>{report.verdict}</p>
        </div>
      )}

      {/* Score Breakdown */}
      <div style={{ margin: '20px 0' }}>
        <h3 className="caption" style={{ marginBottom: 14 }}>{t('score_breakdown')}</h3>
        <div className="score-bar-group">
          {PILLAR_KEYS.map((key) => {
            const value = breakdown[key] ?? 0;
            const max = PILLAR_MAX[key] || 25;
            const pct = (value / max) * 100;
            return (
              <div key={key} className="score-bar-row">
                <span className="score-bar-label">{t(`pillar_${key}`)}</span>
                <div className="score-bar-track">
                  <div className="score-bar-fill" style={{ width: `${Math.min(pct, 100)}%`, backgroundColor: scoreColor }} />
                </div>
                <span className="score-bar-value" style={{ color: scoreColor }}>{value.toFixed(1)}<span className="text-tertiary" style={{ fontSize: 11 }}>/{max}</span></span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Key Findings */}
      {report.key_findings.length > 0 && (
        <div style={{ margin: '20px 0' }}>
          <h3 className="caption" style={{ marginBottom: 12 }}>{t('key_findings')}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {report.key_findings.map((finding, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                <div className="section-number" style={{ width: 28, height: 28, fontSize: 13, flexShrink: 0 }}>{i + 1}</div>
                <p className="body-md text-primary">{finding}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Revenue Impact */}
      {report.revenue_impact && (
        <div className="alert-block">
          <div className="alert-label">{t('revenue_impact')}</div>
          <p className="body-md text-primary">{report.revenue_impact}</p>
        </div>
      )}

      {/* Reputational Cost Summary */}
      {report.critical_issues.some(ci => ci.score_cost != null && ci.score_cost > 0) && (() => {
        const costIssues = report.critical_issues
          .filter(ci => ci.score_cost != null && ci.score_cost > 0)
          .sort((a, b) => (b.score_cost ?? 0) - (a.score_cost ?? 0))
          .slice(0, 3);
        const totalCost = costIssues.reduce((s, ci) => s + (ci.score_cost ?? 0), 0);
        return (
          <div style={{ marginTop: 16, padding: '12px 16px', background: '#FEF2F2', borderRadius: 8, borderLeft: '3px solid #DC2626' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <span className="heading-md" style={{ color: '#B91C1C', fontSize: 13 }}>{t('score_cost')}</span>
              <span style={{ color: '#B91C1C', fontWeight: 700, fontSize: 18 }}>−{totalCost.toFixed(1)} pts</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {costIssues.map((ci, i) => (
                <div key={i} className="body-sm" style={{ color: '#7F1D1D' }}>
                  <strong>−{ci.score_cost?.toFixed(1)}</strong> {ci.title}
                </div>
              ))}
            </div>
          </div>
        );
      })()}

      {/* Top Actions Preview */}
      {topActions.length > 0 && (
        <div style={{ marginTop: 16 }}>
          <h3 className="caption" style={{ marginBottom: 12 }}>{t('top_priority_actions')}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {topActions.map((action, i) => (
              <div key={i} className="framework-item" style={{ padding: 14 }}>
                <div className="framework-number" style={{ width: 28, height: 28, fontSize: 13 }}>{i + 1}</div>
                <div className="framework-body">
                  <div className="heading-md" style={{ fontSize: 14 }}>{action.action}</div>
                  <div className="body-sm" style={{ marginTop: 4 }}>
                    {action.owner} &middot; {translateTimeline(action.timeline, locale)} &middot; <strong>{translateLevel(action.impact, locale)} {t('impact')}</strong>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </ReportPage>
  );
}
