import { useState, useEffect } from 'react';
import { createEmptyReport, type Jurisdiction } from './OilSpillReportTemplate';
import {
  consumeReportGenCategory,
  consumeHnsReportPayload,
  type HnsReportPayload,
  consumeOilReportPayload,
  type OilReportPayload,
} from '@common/hooks/useSubMenu';
import { useAuthStore } from '@common/store/authStore';
import { useWeatherSnapshotStore } from '@common/store/weatherSnapshotStore';
import OilSpreadMapPanel from './OilSpreadMapPanel';
import { saveReport } from '../services/reportsApi';
import { CATEGORIES, type ReportCategory, type ReportSection } from './reportTypes';
import { exportAsPDF } from './reportUtils';

interface ReportGeneratorProps {
  onSave: () => void;
}

function ReportGenerator({ onSave }: ReportGeneratorProps) {
  const user = useAuthStore((s) => s.user);
  const [activeCat, setActiveCat] = useState<ReportCategory>(() => {
    const hint = consumeReportGenCategory();
    return hint === 0 || hint === 1 || hint === 2 ? hint : 0;
  });
  const [selectedTemplate, setSelectedTemplate] = useState(0);
  const [sectionsMap, setSectionsMap] = useState<Record<number, ReportSection[]>>(() => ({
    0: CATEGORIES[0].sections.map((s) => ({ ...s })),
    1: CATEGORIES[1].sections.map((s) => ({ ...s })),
    2: CATEGORIES[2].sections.map((s) => ({ ...s })),
  }));

  // HNS 실 데이터 (없으면 sampleHnsData fallback)
  const [hnsPayload, setHnsPayload] = useState<HnsReportPayload | null>(null);
  // OIL 실 데이터 (없으면 sampleOilData fallback)
  const [oilPayload, setOilPayload] = useState<OilReportPayload | null>(null);
  // 기상 스냅샷 (관측소명, 수집시각)
  const weatherSnapshot = useWeatherSnapshotStore((s) => s.snapshot);
  // 확산예측 지도 캡처 이미지 (3h/6h)
  const [capturedStep3, setCapturedStep3] = useState<string | null>(null);
  const [capturedStep6, setCapturedStep6] = useState<string | null>(null);

  // 외부에서 카테고리 힌트가 변경되면 반영
  useEffect(() => {
    const hint = consumeReportGenCategory();
    if (hint === 0 || hint === 1 || hint === 2) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setActiveCat(hint);
      setSelectedTemplate(0);
    }
    // HNS 데이터 소비
    const payload = consumeHnsReportPayload();
    if (payload) setHnsPayload(payload);
    // OIL 예측 데이터 소비
    const oilData = consumeOilReportPayload();
    if (oilData) setOilPayload(oilData);
  }, []);

  const cat = CATEGORIES[activeCat];
  const sections = sectionsMap[activeCat];
  const activeSections = sections.filter((s) => s.checked);

  const toggleSection = (id: string) => {
    setSectionsMap((prev) => ({
      ...prev,
      [activeCat]: prev[activeCat].map((s) => (s.id === id ? { ...s, checked: !s.checked } : s)),
    }));
  };

  const handleSave = async () => {
    const report = createEmptyReport((user?.org?.abbr || '') as Jurisdiction);
    report.reportType =
      activeCat === 0 ? '유출유 보고' : activeCat === 1 ? '종합보고서' : '초기보고서';
    report.analysisCategory =
      activeCat === 0 ? '유출유 확산예측' : activeCat === 1 ? 'HNS 대기확산' : '긴급구난';
    report.title = cat.reportName;
    report.status = '완료';
    report.author = '시스템 자동생성';
    if (activeCat === 0) {
      if (oilPayload) {
        // 사고 기본정보
        report.incident.name = oilPayload.incident.name;
        report.incident.occurTime = oilPayload.incident.occurTime;
        report.incident.location = oilPayload.incident.location;
        report.incident.lat = String(oilPayload.incident.lat ?? '');
        report.incident.lon = String(oilPayload.incident.lon ?? '');
        report.incident.shipName = oilPayload.incident.shipName;
        report.incident.pollutant = oilPayload.pollution.oilType;
        report.incident.spillAmount = oilPayload.pollution.spillAmount;
        // 해안부착 시간·오염길이 (oil-coastal)
        report.incident.agent = [
          oilPayload.coastal?.firstTime ? `해안도달: ${oilPayload.coastal.firstTime}` : '',
          oilPayload.pollution.coastLength ? `오염해안: ${oilPayload.pollution.coastLength}km` : '',
        ]
          .filter(Boolean)
          .join(', ');

        // 조석·기상정보 (oil-tide)
        if (oilPayload.weather) {
          report.weather = [
            {
              time: '',
              sunrise: '',
              sunset: '',
              windDir: oilPayload.weather.windDir,
              windSpeed: oilPayload.weather.windSpeed,
              currentDir: oilPayload.weather.currentDir ?? '',
              currentSpeed: oilPayload.weather.currentSpeed ?? '',
              waveHeight: oilPayload.weather.waveHeight,
            },
          ];
        }

        // 오염종합상황 + 해안부착 현황 (oil-pollution, oil-coastal)
        report.result = {
          spillTotal: oilPayload.pollution.spillAmount,
          weatheredTotal: oilPayload.pollution.weathered,
          recoveredTotal: '',
          seaRemainTotal: oilPayload.pollution.seaRemain,
          coastAttachTotal: oilPayload.pollution.coastAttach,
        };

        // 스텝별 오염종합 상황 (3h/6h) → report.spread
        if (oilPayload.spreadSteps) {
          report.spread = oilPayload.spreadSteps;
        }

        // acdntSn 전달 (민감자원 지도 로드용)
        if (oilPayload.acdntSn) {
          (report as typeof report & { acdntSn?: number }).acdntSn = oilPayload.acdntSn;
        }
      } else {
        report.incident.pollutant = '';
        report.incident.spillAmount = '';
      }
    }
    if (activeCat === 0) {
      if (capturedStep3) report.step3MapImage = capturedStep3;
      if (capturedStep6) report.step6MapImage = capturedStep6;
    }
    try {
      await saveReport(report);
      onSave();
    } catch (err) {
      console.error('[reports] 저장 오류:', err);
      alert('보고서 저장 중 오류가 발생했습니다.');
    }
  };

  const handleDownload = () => {
    const secColor =
      cat.color === 'var(--color-accent)'
        ? '#06b6d4'
        : cat.color === 'var(--color-warning)'
          ? '#f97316'
          : '#ef4444';
    const sectionHTML = activeSections
      .map((sec) => {
        let content = `<p style="font-size:12px;color:#999;">—</p>`;

        // OIL 섹션에 실 데이터 삽입
        if (activeCat === 0) {
          if (sec.id === 'oil-spread') {
            const img3 = capturedStep3
              ? `<img src="${capturedStep3}" style="width:100%;max-height:260px;object-fit:contain;border:1px solid #ddd;border-radius:6px;" />`
              : '<div style="height:60px;background:#f5f5f5;border:1px solid #ddd;border-radius:6px;display:flex;align-items:center;justify-content:center;color:#999;font-size:11px;">[미캡처]</div>';
            const img6 = capturedStep6
              ? `<img src="${capturedStep6}" style="width:100%;max-height:260px;object-fit:contain;border:1px solid #ddd;border-radius:6px;" />`
              : '<div style="height:60px;background:#f5f5f5;border:1px solid #ddd;border-radius:6px;display:flex;align-items:center;justify-content:center;color:#999;font-size:11px;">[미캡처]</div>';
            const mapsHtml = `<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px"><div><p style="font-size:11px;font-weight:bold;color:#0891b2;margin-bottom:4px;">3시간 후</p>${img3}</div><div><p style="font-size:11px;font-weight:bold;color:#0891b2;margin-bottom:4px;">6시간 후</p>${img6}</div></div>`;
            const spreadStepRows =
              oilPayload?.spreadSteps && oilPayload.spreadSteps.length > 0
                ? oilPayload.spreadSteps
                    .map(
                      (s) =>
                        `<tr><td style="padding:6px 8px;border:1px solid #ddd;text-align:center;font-weight:bold;">${s.elapsed}</td><td style="padding:6px 8px;border:1px solid #ddd;text-align:right;">${s.weathered || '—'}</td><td style="padding:6px 8px;border:1px solid #ddd;text-align:right;">${s.seaRemain || '—'}</td><td style="padding:6px 8px;border:1px solid #ddd;text-align:right;">${s.coastAttach || '—'}</td><td style="padding:6px 8px;border:1px solid #ddd;text-align:right;">${s.area || '—'}</td></tr>`,
                    )
                    .join('')
                : '';
            const stepsTable = spreadStepRows
              ? `<table style="width:100%;border-collapse:collapse;font-size:11px;margin-top:8px;"><thead><tr><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;">경과시간</th><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;">풍화량(kl)</th><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;">해상잔유량(kl)</th><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;">연안부착량(kl)</th><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;">오염해역면적(km²)</th></tr></thead><tbody>${spreadStepRows}</tbody></table>`
              : '';
            content = `${mapsHtml}${stepsTable}`;
          }
        }
        if (activeCat === 0 && sec.id === 'oil-coastal') {
          if (oilPayload) {
            const coastLength = oilPayload.pollution.coastLength;
            const hasNoCoastal =
              !coastLength || coastLength === '—' || coastLength.startsWith('0.00');
            content = hasNoCoastal
              ? `<p style="font-size:12px;">유출유의 해안 부착이 없습니다.</p>`
              : `<p style="font-size:12px;">최초 부착시간: <b>${oilPayload.coastal?.firstTime ?? '—'}</b> / 부착 해안길이: <b>${coastLength}</b></p>`;
          }
        }
        if (activeCat === 0 && sec.id === 'oil-sensitive') {
          const resources = oilPayload?.sensitiveResources;
          if (resources && resources.length > 0) {
            const headerRow = `<tr><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;text-align:left;">구분</th><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;text-align:center;">개소</th><th style="padding:6px 8px;border:1px solid #ddd;background:#f5f5f5;text-align:right;">면적</th></tr>`;
            const dataRows = resources
              .map((r) => {
                const areaText = r.totalArea != null ? `${r.totalArea.toFixed(2)} ha` : '—';
                return `<tr><td style="padding:6px 8px;border:1px solid #ddd;">${r.category}</td><td style="padding:6px 8px;border:1px solid #ddd;text-align:center;">${r.count}개소</td><td style="padding:6px 8px;border:1px solid #ddd;text-align:right;">${areaText}</td></tr>`;
              })
              .join('');
            content = `<table style="width:100%;border-collapse:collapse;font-size:12px;">${headerRow}${dataRows}</table>`;
          }
        }
        if (activeCat === 0 && oilPayload) {
          if (sec.id === 'oil-pollution') {
            const rows = [
              [
                '유출량',
                oilPayload.pollution.spillAmount,
                '풍화량',
                oilPayload.pollution.weathered,
              ],
              [
                '해상잔유량',
                oilPayload.pollution.seaRemain,
                '오염해역면적',
                oilPayload.pollution.pollutionArea,
              ],
              [
                '연안부착량',
                oilPayload.pollution.coastAttach,
                '오염해안길이',
                oilPayload.pollution.coastLength,
              ],
            ];
            const simBanner = !oilPayload.hasSimulation
              ? '<p style="font-size:10px;color:#f97316;margin-bottom:8px;">시뮬레이션이 실행되지 않아 오염량은 입력값 기준으로 표시됩니다.</p>'
              : '';
            const trs = rows
              .map(
                (r) =>
                  `<tr><td style="padding:6px 8px;border:1px solid #ddd;color:#888;">${r[0]}</td><td style="padding:6px 8px;border:1px solid #ddd;font-weight:bold;text-align:right;">${r[1]}</td><td style="padding:6px 8px;border:1px solid #ddd;color:#888;">${r[2]}</td><td style="padding:6px 8px;border:1px solid #ddd;font-weight:bold;text-align:right;">${r[3]}</td></tr>`,
              )
              .join('');
            content = `${simBanner}<table style="width:100%;border-collapse:collapse;font-size:12px;">${trs}</table>`;
          }
        }
        if (activeCat === 0 && sec.id === 'oil-tide') {
          const wx = oilPayload?.weather;
          if (wx) {
            const stationLabel = weatherSnapshot
              ? `${weatherSnapshot.stationName} 조위관측소`
              : '조위관측소';
            const capturedAt = weatherSnapshot
              ? new Date(weatherSnapshot.capturedAt).toLocaleString('ko-KR', {
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                })
              : '';
            const rows = [
              ['풍향/풍속', `${wx.windDir} / ${wx.windSpeed}`],
              ['파고', wx.waveHeight + (wx.waveMaxHeight ? ` (최대 ${wx.waveMaxHeight})` : '')],
              ['파주기', wx.wavePeriod ?? '—'],
              ['수온', wx.temp],
              ['기압', wx.pressure ?? '—'],
              ['시정', wx.visibility ?? '—'],
              ['염분', wx.salinity ?? '—'],
              ...(wx.currentDir
                ? [['유향/유속', `${wx.currentDir} / ${wx.currentSpeed ?? '—'}`]]
                : []),
            ];
            const headerHtml = `<p style="font-size:11px;font-weight:bold;color:#0891b2;margin-bottom:8px;">${stationLabel}${capturedAt ? ` <span style="font-size:10px;color:#999;font-weight:normal;">수집: ${capturedAt}</span>` : ''}</p>`;
            const trs = rows
              .map(
                (r) =>
                  `<tr><td style="padding:6px 8px;border:1px solid #ddd;color:#888;width:100px;">${r[0]}</td><td style="padding:6px 8px;border:1px solid #ddd;font-weight:bold;">${r[1]}</td></tr>`,
              )
              .join('');
            content = `${headerHtml}<table style="width:100%;border-collapse:collapse;font-size:12px;">${trs}</table>`;
          }
        }

        // HNS 섹션에 실 데이터 삽입
        if (activeCat === 1 && hnsPayload) {
          if (sec.id === 'hns-atm') {
            const mapImg = hnsPayload.mapImageDataUrl
              ? `<img src="${hnsPayload.mapImageDataUrl}" style="width:100%;max-height:300px;object-fit:contain;border:1px solid #ddd;border-radius:8px;margin-bottom:12px;" />`
              : '<div style="height:100px;background:#f5f5f5;border:1px solid #ddd;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#999;margin-bottom:12px;">[대기확산 예측 지도]</div>';
            content = `${mapImg}<table style="width:100%;border-collapse:collapse;font-size:12px;"><tr><td style="padding:8px;border:1px solid #ddd;text-align:center;"><b>${hnsPayload.atm.model}</b><br/>${hnsPayload.atm.maxDistance}</td><td style="padding:8px;border:1px solid #ddd;text-align:center;"><b>최대 농도</b><br/>${hnsPayload.maxConcentration}</td><td style="padding:8px;border:1px solid #ddd;text-align:center;"><b>AEGL-1 면적</b><br/>${hnsPayload.aeglAreas.aegl1}</td></tr></table>`;
          } else if (sec.id === 'hns-hazard') {
            content = `<table style="width:100%;border-collapse:collapse;font-size:12px;"><tr><td style="padding:8px;border:1px solid #ddd;text-align:center;color:#ef4444;"><b>AEGL-3</b><br/>${hnsPayload.hazard.aegl3} (${hnsPayload.aeglAreas.aegl3})</td><td style="padding:8px;border:1px solid #ddd;text-align:center;color:#f97316;"><b>AEGL-2</b><br/>${hnsPayload.hazard.aegl2} (${hnsPayload.aeglAreas.aegl2})</td><td style="padding:8px;border:1px solid #ddd;text-align:center;color:#eab308;"><b>AEGL-1</b><br/>${hnsPayload.hazard.aegl1} (${hnsPayload.aeglAreas.aegl1})</td></tr></table>`;
          } else if (sec.id === 'hns-substance') {
            content = `<table style="width:100%;border-collapse:collapse;font-size:12px;"><tr><td style="padding:6px 8px;border:1px solid #ddd;color:#888;">물질명</td><td style="padding:6px 8px;border:1px solid #ddd;font-weight:bold;">${hnsPayload.substance.name}</td></tr><tr><td style="padding:6px 8px;border:1px solid #ddd;color:#888;">독성기준</td><td style="padding:6px 8px;border:1px solid #ddd;color:#ef4444;font-weight:bold;">${hnsPayload.substance.toxicity}</td></tr></table>`;
          } else if (sec.id === 'hns-weather') {
            content = `<table style="width:100%;border-collapse:collapse;font-size:12px;"><tr><td style="padding:8px;border:1px solid #ddd;text-align:center;"><b>풍향</b><br/>${hnsPayload.weather.windDir}</td><td style="padding:8px;border:1px solid #ddd;text-align:center;"><b>풍속</b><br/>${hnsPayload.weather.windSpeed}</td><td style="padding:8px;border:1px solid #ddd;text-align:center;"><b>안정도</b><br/>${hnsPayload.weather.stability}</td><td style="padding:8px;border:1px solid #ddd;text-align:center;"><b>기온</b><br/>${hnsPayload.weather.temperature}</td></tr></table>`;
          }
        }

        return `<h3 style="color:${secColor};font-size:14px;margin:20px 0 8px;">${sec.icon} ${sec.title}</h3>${content}`;
      })
      .join('');
    const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${cat.reportName}</title><style>@page{size:A4;margin:20mm}body{font-family:'맑은 고딕',sans-serif;color:#1a1a1a;max-width:800px;margin:0 auto;padding:40px}table{margin:8px 0}</style></head><body><div style="text-align:center;margin-bottom:30px"><h1 style="font-size:20px;margin:0">해양환경 위기대응 통합지원시스템</h1><h2 style="font-size:16px;color:#0891b2;margin:8px 0">${cat.reportName}</h2></div>${sectionHTML}</body></html>`;
    exportAsPDF(html, cat.reportName);
  };

  return (
    <div className="flex flex-col h-full w-full">
      {/* Header */}
      <div className="px-6 py-4 border-b border-stroke bg-bg-surface">
        <h2 className="text-title-2 font-bold text-fg font-korean">보고서 생성</h2>
        <p className="text-label-2 text-fg-disabled font-korean mt-1">
          보고서 유형을 선택하고 포함할 섹션을 구성하여 보고서를 생성합니다.
        </p>

        {/* 3 카테고리 카드 */}
        <div className="flex gap-3.5 mt-4">
          {CATEGORIES.map((c, i) => {
            const isActive = activeCat === i;
            return (
              <button
                key={i}
                onClick={() => {
                  setActiveCat(i as ReportCategory);
                  setSelectedTemplate(0);
                }}
                className="flex-1 px-4 py-3.5 rounded-[10px] cursor-pointer text-center transition-[0.2s]"
                style={{
                  border: `1px solid ${isActive ? c.borderColor : 'var(--stroke-default)'}`,
                  background: isActive ? c.bgActive : 'var(--bg-card)',
                }}
              >
                <div className="text-[22px] mb-1">{c.icon}</div>
                <div
                  className="text-label-1 font-bold"
                  style={{ color: isActive ? c.color : 'var(--fg-disabled)' }}
                >
                  {c.label}
                </div>
                <div className="text-caption text-fg-disabled mt-0.5">{c.desc}</div>
              </button>
            );
          })}
        </div>
      </div>

      <div className="flex flex-1 overflow-hidden">
        {/* Left Sidebar - Template + Sections */}
        <div className="w-[250px] min-w-[250px] border-r border-stroke bg-bg-surface flex flex-col overflow-y-auto shrink-0">
          {/* 템플릿 선택 */}
          <div className="px-4 py-3 border-b border-stroke">
            <h3 className="text-label-2 font-bold text-fg-sub font-korean flex items-center gap-2">
              📄 보고서 템플릿
            </h3>
          </div>
          <div className="flex flex-col gap-1.5 px-3 py-2 border-b border-stroke">
            {cat.templates.map((tmpl, i) => (
              <button
                key={i}
                onClick={() => setSelectedTemplate(i)}
                className="flex items-center gap-2 px-3 py-2.5 rounded-lg transition-all text-left"
                style={{
                  border: `1px solid ${selectedTemplate === i ? cat.borderColor : 'var(--stroke-default)'}`,
                  background: selectedTemplate === i ? cat.bgActive : 'var(--bg-elevated)',
                }}
              >
                <span className="text-title-3">{tmpl.icon}</span>
                <span
                  className="text-label-2 font-semibold"
                  style={{ color: selectedTemplate === i ? cat.color : 'var(--fg-sub)' }}
                >
                  {tmpl.label}
                </span>
              </button>
            ))}
          </div>

          {/* 섹션 체크 */}
          <div className="px-4 py-3 border-b border-stroke">
            <h3 className="text-label-2 font-bold text-fg-sub font-korean flex items-center gap-2">
              📋 포함 섹션
            </h3>
          </div>
          <div className="flex flex-col gap-1.5 p-3">
            {sections.map((sec) => (
              <button
                key={sec.id}
                onClick={() => toggleSection(sec.id)}
                className="flex items-start gap-2.5 p-2.5 rounded-lg border transition-all text-left"
                style={{
                  borderColor: sec.checked ? cat.borderColor : 'var(--stroke-default)',
                  background: sec.checked ? cat.bgActive : 'var(--bg-elevated)',
                  opacity: sec.checked ? 1 : 0.55,
                }}
              >
                <div
                  className="w-[18px] h-[18px] rounded shrink-0 mt-[1px] flex items-center justify-center text-label-2"
                  style={{
                    background: sec.checked ? cat.color : 'var(--bg-card)',
                    color: sec.checked ? '#fff' : 'transparent',
                    border: sec.checked ? 'none' : '1px solid var(--stroke-default)',
                  }}
                >
                  ✓
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-1">
                    <span className="text-label-1">{sec.icon}</span>
                    <span
                      className="text-label-2 font-bold"
                      style={{ color: sec.checked ? 'var(--fg-default)' : 'var(--fg-disabled)' }}
                    >
                      {sec.title}
                    </span>
                  </div>
                  <p className="text-caption text-fg-disabled mt-0.5">{sec.desc}</p>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Right - Report Preview */}
        <div className="flex-1 flex flex-col overflow-hidden">
          {/* Preview Header */}
          <div className="flex items-center justify-between px-6 py-3 border-b border-stroke bg-bg-surface">
            <h3 className="text-title-4 font-bold text-fg font-korean flex items-center gap-2">
              📄 보고서 미리보기
              <span
                className="text-label-2 font-semibold px-2 py-0.5 rounded"
                style={{ background: cat.bgActive, color: cat.color }}
              >
                {cat.templates[selectedTemplate].label}
              </span>
            </h3>
            <div className="flex items-center gap-2">
              <button
                onClick={handleDownload}
                className="px-3 py-1.5 text-label-2 font-semibold rounded transition-all font-korean flex items-center gap-1.5"
                style={{
                  background: cat.bgActive,
                  border: `1px solid ${cat.borderColor}`,
                  color: cat.color,
                }}
              >
                📥 다운로드
              </button>
              <button
                onClick={handleSave}
                className="px-3 py-1.5 text-label-2 font-semibold rounded border border-stroke bg-bg-elevated text-fg hover:bg-bg-surface-hover transition-all font-korean flex items-center gap-1.5"
              >
                💾 저장
              </button>
            </div>
          </div>

          {/* Preview Content */}
          <div className="flex-1 overflow-y-auto px-6 py-5">
            {/* Report Header */}
            <div className="rounded-lg border border-stroke p-8 mb-6 bg-bg-elevated">
              <div className="text-center">
                <p className="text-label-2 text-fg-disabled font-korean mb-2">
                  해양환경 위기대응 통합지원시스템
                </p>
                <h2 className="text-[20px] font-bold text-fg font-korean mb-2">{cat.reportName}</h2>
                <p className="text-label-1 font-korean" style={{ color: cat.color }}>
                  {cat.templates[selectedTemplate].label}
                </p>
              </div>
            </div>

            {/* Dynamic Sections */}
            {activeSections.map((sec) => (
              <div
                key={sec.id}
                className="rounded-lg border border-stroke mb-4 overflow-hidden bg-bg-elevated"
              >
                <div className="px-5 py-3 border-b border-stroke">
                  <h4 className="text-title-4 font-bold text-fg font-korean flex items-center gap-2">
                    {sec.icon} {sec.title}
                  </h4>
                </div>
                <div className="p-5">
                  {/* ── 유출유 확산예측 섹션들 ── */}
                  {sec.id === 'oil-spread' && (
                    <>
                      <OilSpreadMapPanel
                        mapData={oilPayload?.mapData ?? null}
                        capturedStep3={capturedStep3}
                        capturedStep6={capturedStep6}
                        onCaptureStep3={setCapturedStep3}
                        onCaptureStep6={setCapturedStep6}
                        onResetStep3={() => setCapturedStep3(null)}
                        onResetStep6={() => setCapturedStep6(null)}
                      />
                      {oilPayload?.spreadSteps && oilPayload.spreadSteps.length > 0 && (
                        <div className="mb-4 overflow-x-auto">
                          <table className="w-full border-collapse text-label-2">
                            <thead>
                              <tr className="border-b border-stroke bg-bg-card">
                                <th className="px-3 py-2 text-center font-semibold text-fg-disabled font-korean">
                                  경과시간
                                </th>
                                <th className="px-3 py-2 text-right font-semibold text-fg-disabled font-korean">
                                  풍화량(kl)
                                </th>
                                <th className="px-3 py-2 text-right font-semibold text-fg-disabled font-korean">
                                  해상잔유량(kl)
                                </th>
                                <th className="px-3 py-2 text-right font-semibold text-fg-disabled font-korean">
                                  연안부착량(kl)
                                </th>
                                <th className="px-3 py-2 text-right font-semibold text-fg-disabled font-korean">
                                  오염해역면적(km²)
                                </th>
                              </tr>
                            </thead>
                            <tbody>
                              {oilPayload.spreadSteps.map((s, i) => (
                                <tr key={i} className="border-b border-stroke">
                                  <td className="px-3 py-2 text-center font-semibold text-accent-1 font-korean">
                                    {s.elapsed}
                                  </td>
                                  <td className="px-3 py-2 text-right font-mono text-fg">
                                    {s.weathered || '—'}
                                  </td>
                                  <td className="px-3 py-2 text-right font-mono text-fg">
                                    {s.seaRemain || '—'}
                                  </td>
                                  <td className="px-3 py-2 text-right font-mono text-fg">
                                    {s.coastAttach || '—'}
                                  </td>
                                  <td className="px-3 py-2 text-right font-mono text-fg">
                                    {s.area || '—'}
                                  </td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      )}
                      <div className="grid grid-cols-3 gap-3">
                        {[
                          {
                            label: 'KOSPS',
                            value: oilPayload?.spread.kosps || '—',
                            color: '#06b6d4',
                          },
                          {
                            label: 'OpenDrift',
                            value: oilPayload?.spread.openDrift || '—',
                            color: '#ef4444',
                          },
                          {
                            label: 'POSEIDON',
                            value: oilPayload?.spread.poseidon || '—',
                            color: '#f97316',
                          },
                        ].map((m, i) => (
                          <div
                            key={i}
                            className="bg-bg-surface border border-stroke rounded-lg p-4 text-center"
                          >
                            <p className="text-label-2 text-fg-disabled font-korean mb-1">
                              {m.label}
                            </p>
                            <p
                              className="text-[20px] font-bold font-mono"
                              style={{ color: m.color }}
                            >
                              {m.value}
                            </p>
                          </div>
                        ))}
                      </div>
                    </>
                  )}
                  {sec.id === 'oil-pollution' && (
                    <>
                      {oilPayload && !oilPayload.hasSimulation && (
                        <div
                          className="mb-3 px-3 py-2 rounded text-label-2 font-korean"
                          style={{
                            background: 'rgba(249,115,22,0.08)',
                            border: '1px solid rgba(249,115,22,0.3)',
                            color: '#f97316',
                          }}
                        >
                          시뮬레이션이 실행되지 않아 오염량은 입력값 기준으로 표시됩니다.
                        </div>
                      )}
                      <table className="w-full table-fixed border-collapse">
                        <colgroup>
                          <col style={{ width: '25%' }} />
                          <col style={{ width: '25%' }} />
                          <col style={{ width: '25%' }} />
                          <col style={{ width: '25%' }} />
                        </colgroup>
                        <tbody>
                          {[
                            [
                              '유출량',
                              oilPayload?.pollution.spillAmount || '—',
                              '풍화량',
                              oilPayload?.pollution.weathered || '—',
                            ],
                            [
                              '해상잔유량',
                              oilPayload?.pollution.seaRemain || '—',
                              '오염해역면적',
                              oilPayload?.pollution.pollutionArea || '—',
                            ],
                            [
                              '연안부착량',
                              oilPayload?.pollution.coastAttach || '—',
                              '오염해안길이',
                              oilPayload?.pollution.coastLength || '—',
                            ],
                          ].map((row, i) => (
                            <tr key={i} className="border-b border-stroke">
                              <td className="px-4 py-3 text-label-2 text-fg-disabled font-korean bg-[rgba(255,255,255,0.02)]">
                                {row[0]}
                              </td>
                              <td className="px-4 py-3 text-label-1 text-fg font-mono font-semibold text-right">
                                {row[1]}
                              </td>
                              <td className="px-4 py-3 text-label-2 text-fg-disabled font-korean bg-[rgba(255,255,255,0.02)]">
                                {row[2]}
                              </td>
                              <td className="px-4 py-3 text-label-1 text-fg font-mono font-semibold text-right">
                                {row[3]}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </>
                  )}
                  {sec.id === 'oil-sensitive' &&
                    (() => {
                      const resources = oilPayload?.sensitiveResources;
                      if (!resources || resources.length === 0) {
                        return (
                          <p className="text-label-1 text-fg-disabled font-korean italic">
                            현재 민감자원 데이터가 없습니다.
                          </p>
                        );
                      }
                      return (
                        <table className="w-full table-fixed border-collapse">
                          <colgroup>
                            <col style={{ width: '40%' }} />
                            <col style={{ width: '30%' }} />
                            <col style={{ width: '30%' }} />
                          </colgroup>
                          <thead>
                            <tr className="border-b border-stroke">
                              <th className="px-4 py-2 text-label-2 text-fg-disabled font-korean text-left bg-[rgba(255,255,255,0.02)]">
                                구분
                              </th>
                              <th className="px-4 py-2 text-label-2 text-fg-disabled font-korean text-right bg-[rgba(255,255,255,0.02)]">
                                개소
                              </th>
                              <th className="px-4 py-2 text-label-2 text-fg-disabled font-korean text-right bg-[rgba(255,255,255,0.02)]">
                                면적
                              </th>
                            </tr>
                          </thead>
                          <tbody>
                            {resources.map((r, i) => (
                              <tr key={i} className="border-b border-stroke">
                                <td className="px-4 py-3 text-label-1 text-fg font-korean">
                                  {r.category}
                                </td>
                                <td className="px-4 py-3 text-label-1 text-fg text-right">
                                  <span className="font-mono">{r.count}</span>
                                  <span className="font-korean">개소</span>
                                </td>
                                <td className="px-4 py-3 text-label-1 text-fg font-mono text-right">
                                  {r.totalArea != null ? `${r.totalArea.toFixed(2)} ha` : '—'}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      );
                    })()}
                  {sec.id === 'oil-coastal' &&
                    (() => {
                      if (!oilPayload) {
                        return (
                          <p className="text-label-1 text-fg-disabled font-korean italic">
                            현재 해안 부착 데이터가 없습니다.
                          </p>
                        );
                      }
                      const coastLength = oilPayload.pollution.coastLength;
                      const hasNoCoastal =
                        !coastLength || coastLength === '—' || coastLength.startsWith('0.00');
                      if (hasNoCoastal) {
                        return (
                          <p className="text-label-1 text-fg-sub font-korean">
                            시뮬레이션 결과 유출유의{' '}
                            <span className="font-semibold text-fg">해안 부착이 없습니다</span>.
                          </p>
                        );
                      }
                      return (
                        <p className="text-label-1 text-fg-sub font-korean">
                          최초 부착시간:{' '}
                          <span className="font-semibold text-fg">
                            {oilPayload.coastal?.firstTime ?? '—'}
                          </span>
                          {' / '}
                          부착 해안길이:{' '}
                          <span className="font-semibold text-fg">{coastLength}</span>
                        </p>
                      );
                    })()}
                  {sec.id === 'oil-defense' && (
                    <div className="text-label-1 text-fg-disabled font-korean">
                      <p className="mb-2">방제자원 배치 계획에 따른 전략을 수립합니다.</p>
                      <div className="w-full h-[100px] bg-bg-card border border-stroke rounded-lg flex items-center justify-center text-fg-disabled text-label-1 font-korean">
                        [방제자원 배치 지도]
                      </div>
                    </div>
                  )}
                  {sec.id === 'oil-tide' &&
                    (() => {
                      const wx = oilPayload?.weather;
                      if (!wx) {
                        return (
                          <p className="text-label-1 text-fg-disabled font-korean italic">
                            현재 조석·기상 데이터가 없습니다.
                          </p>
                        );
                      }
                      const stationLabel = weatherSnapshot
                        ? `${weatherSnapshot.stationName} 조위관측소`
                        : '조위관측소';
                      const capturedAt = weatherSnapshot
                        ? new Date(weatherSnapshot.capturedAt).toLocaleString('ko-KR', {
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                          })
                        : '';
                      const rows = [
                        { label: '풍향/풍속', value: `${wx.windDir} / ${wx.windSpeed}` },
                        {
                          label: '파고',
                          value:
                            wx.waveHeight + (wx.waveMaxHeight ? ` (최대 ${wx.waveMaxHeight})` : ''),
                        },
                        { label: '파주기', value: wx.wavePeriod ?? '—' },
                        { label: '수온', value: wx.temp },
                        { label: '기압', value: wx.pressure ?? '—' },
                        { label: '시정', value: wx.visibility ?? '—' },
                        { label: '염분', value: wx.salinity ?? '—' },
                        ...(wx.currentDir
                          ? [
                              {
                                label: '유향/유속',
                                value: `${wx.currentDir} / ${wx.currentSpeed ?? '—'}`,
                              },
                            ]
                          : []),
                      ];
                      return (
                        <div className="space-y-2">
                          <div className="flex items-center gap-2 mb-3">
                            <span className="text-label-2 font-semibold text-accent-1 font-korean">
                              {stationLabel}
                            </span>
                            {capturedAt && (
                              <span className="text-label-2 text-fg-disabled font-korean">
                                수집: {capturedAt}
                              </span>
                            )}
                          </div>
                          <div className="grid grid-cols-2 gap-x-6 gap-y-1.5">
                            {rows.map((row) => (
                              <div key={row.label} className="flex items-center gap-2">
                                <span className="text-label-2 text-fg-disabled font-korean w-[64px] shrink-0">
                                  {row.label}
                                </span>
                                <span className="text-label-1 font-semibold text-fg font-mono">
                                  {row.value}
                                </span>
                              </div>
                            ))}
                          </div>
                        </div>
                      );
                    })()}

                  {/* ── HNS 대기확산 섹션들 ── */}
                  {sec.id === 'hns-atm' && (
                    <>
                      {hnsPayload?.mapImageDataUrl ? (
                        <img
                          src={hnsPayload.mapImageDataUrl}
                          alt="대기확산 예측 지도"
                          className="w-full h-auto rounded-lg border border-stroke mb-4"
                          style={{ maxHeight: '300px', objectFit: 'contain' }}
                        />
                      ) : (
                        <div className="w-full h-[140px] bg-bg-card border border-stroke rounded-lg flex items-center justify-center text-fg-disabled text-label-1 font-korean mb-4">
                          [대기확산 예측 지도]
                        </div>
                      )}
                      <div className="grid grid-cols-3 gap-3">
                        {[
                          {
                            label: hnsPayload?.atm.model || 'ALOHA',
                            value: hnsPayload?.atm.maxDistance || '—',
                            color: '#f97316',
                            desc: '최대 확산거리',
                          },
                          {
                            label: '최대 농도',
                            value: hnsPayload?.maxConcentration || '—',
                            color: '#ef4444',
                            desc: '지상 1.5m 기준',
                          },
                          {
                            label: 'AEGL-1 면적',
                            value: hnsPayload?.aeglAreas.aegl1 || '—',
                            color: '#06b6d4',
                            desc: '확산 영향 면적',
                          },
                        ].map((m, i) => (
                          <div
                            key={i}
                            className="bg-bg-surface border border-stroke rounded-lg p-4 text-center"
                          >
                            <p className="text-label-2 text-fg-disabled font-korean mb-1">
                              {m.label}
                            </p>
                            <p
                              className="text-[20px] font-bold font-mono"
                              style={{ color: m.color }}
                            >
                              {m.value}
                            </p>
                            <p className="text-caption text-fg-disabled font-korean mt-1">
                              {m.desc}
                            </p>
                          </div>
                        ))}
                      </div>
                    </>
                  )}
                  {sec.id === 'hns-hazard' && (
                    <div className="grid grid-cols-3 gap-3">
                      {[
                        {
                          label: 'AEGL-3 구역',
                          value: hnsPayload?.hazard.aegl3 || '—',
                          area: hnsPayload?.aeglAreas.aegl3,
                          color: '#ef4444',
                          desc: '생명 위협',
                        },
                        {
                          label: 'AEGL-2 구역',
                          value: hnsPayload?.hazard.aegl2 || '—',
                          area: hnsPayload?.aeglAreas.aegl2,
                          color: '#f97316',
                          desc: '건강 피해',
                        },
                        {
                          label: 'AEGL-1 구역',
                          value: hnsPayload?.hazard.aegl1 || '—',
                          area: hnsPayload?.aeglAreas.aegl1,
                          color: '#eab308',
                          desc: '불쾌감',
                        },
                      ].map((h, i) => (
                        <div
                          key={i}
                          className="bg-bg-surface border border-stroke rounded-lg p-4 text-center"
                        >
                          <p
                            className="text-caption font-bold font-korean mb-1"
                            style={{ color: h.color }}
                          >
                            {h.label}
                          </p>
                          <p
                            className="text-title-1 font-bold font-mono"
                            style={{ color: h.color }}
                          >
                            {h.value}
                          </p>
                          {h.area && (
                            <p className="text-label-2 text-fg-disabled font-mono mt-0.5">
                              {h.area}
                            </p>
                          )}
                          <p className="text-caption text-fg-disabled font-korean mt-1">{h.desc}</p>
                        </div>
                      ))}
                    </div>
                  )}
                  {sec.id === 'hns-substance' && (
                    <div className="grid grid-cols-2 gap-2 text-label-2">
                      {[
                        { k: '물질명', v: hnsPayload?.substance.name || '—' },
                        { k: 'UN번호', v: hnsPayload?.substance.un || '—' },
                        { k: 'CAS번호', v: hnsPayload?.substance.cas || '—' },
                        { k: '위험등급', v: hnsPayload?.substance.class || '—' },
                      ].map((r, i) => (
                        <div
                          key={i}
                          className="flex justify-between px-3 py-2 bg-bg-surface rounded border border-stroke"
                        >
                          <span className="text-fg-disabled font-korean">{r.k}</span>
                          <span className="text-fg font-semibold font-mono">{r.v}</span>
                        </div>
                      ))}
                      <div className="col-span-2 flex justify-between px-3 py-2 bg-bg-surface rounded border border-[rgba(239,68,68,0.3)]">
                        <span className="text-fg-disabled font-korean">독성기준</span>
                        <span className="text-[var(--color-danger)] font-semibold font-mono text-label-2">
                          {hnsPayload?.substance.toxicity || '—'}
                        </span>
                      </div>
                    </div>
                  )}
                  {sec.id === 'hns-ppe' && (
                    <div className="flex flex-wrap gap-2">
                      <span className="text-fg-disabled font-korean text-label-2">—</span>
                    </div>
                  )}
                  {sec.id === 'hns-facility' && (
                    <div className="grid grid-cols-3 gap-3">
                      {[
                        { label: '인근 학교', value: '—', icon: '🏫' },
                        { label: '의료시설', value: '—', icon: '🏥' },
                        { label: '주변 인구', value: '—', icon: '👥' },
                      ].map((f, i) => (
                        <div
                          key={i}
                          className="bg-bg-surface border border-stroke rounded-lg p-4 text-center"
                        >
                          <div className="text-title-1 mb-1">{f.icon}</div>
                          <p className="text-title-3 font-bold text-fg font-mono">{f.value}</p>
                          <p className="text-caption text-fg-disabled font-korean mt-1">
                            {f.label}
                          </p>
                        </div>
                      ))}
                    </div>
                  )}
                  {sec.id === 'hns-3d' && (
                    <div className="w-full h-[160px] bg-bg-card border border-stroke rounded-lg flex items-center justify-center text-fg-disabled text-label-1 font-korean">
                      [3D 농도 분포 시각화]
                    </div>
                  )}
                  {sec.id === 'hns-weather' && (
                    <div className="grid grid-cols-4 gap-3">
                      {[
                        { label: '풍향', value: hnsPayload?.weather.windDir || '—', icon: '🌬' },
                        { label: '풍속', value: hnsPayload?.weather.windSpeed || '—', icon: '💨' },
                        {
                          label: '대기안정도',
                          value: hnsPayload?.weather.stability || '—',
                          icon: '🌡',
                        },
                        {
                          label: '기온',
                          value: hnsPayload?.weather.temperature || '—',
                          icon: '☀️',
                        },
                      ].map((w, i) => (
                        <div
                          key={i}
                          className="bg-bg-surface border border-stroke rounded-lg p-3 text-center"
                        >
                          <div className="text-title-2 mb-0.5">{w.icon}</div>
                          <p className="text-title-4 font-bold text-fg font-mono">{w.value}</p>
                          <p className="text-caption text-fg-disabled font-korean mt-1">
                            {w.label}
                          </p>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* ── 긴급구난 섹션들 ── */}
                  {sec.id === 'rescue-safety' && (
                    <div className="grid grid-cols-4 gap-3">
                      {[
                        { label: 'GM (복원력)', value: '—', color: '#f97316' },
                        { label: '경사각 (Heel)', value: '—', color: '#ef4444' },
                        { label: '트림 (Trim)', value: '—', color: '#06b6d4' },
                        { label: '안전 상태', value: '—', color: '#f97316' },
                      ].map((s, i) => (
                        <div
                          key={i}
                          className="bg-bg-surface border border-stroke rounded-lg p-3 text-center"
                        >
                          <p className="text-caption text-fg-disabled font-korean mb-1">
                            {s.label}
                          </p>
                          <p
                            className="text-title-2 font-bold font-mono"
                            style={{ color: s.color }}
                          >
                            {s.value}
                          </p>
                        </div>
                      ))}
                    </div>
                  )}
                  {sec.id === 'rescue-timeline' && (
                    <div className="flex flex-col gap-2">
                      <div className="flex items-center gap-3 px-3 py-2 bg-bg-surface rounded border border-stroke">
                        <span className="text-label-2 text-fg-disabled font-korean">—</span>
                      </div>
                    </div>
                  )}
                  {sec.id === 'rescue-casualty' && (
                    <div className="grid grid-cols-4 gap-3">
                      {[
                        { label: '총원', value: '—' },
                        { label: '구조완료', value: '—', color: '#22c55e' },
                        { label: '실종', value: '—', color: '#ef4444' },
                        { label: '부상', value: '—', color: '#f97316' },
                      ].map((c, i) => (
                        <div
                          key={i}
                          className="bg-bg-surface border border-stroke rounded-lg p-4 text-center"
                        >
                          <p className="text-caption text-fg-disabled font-korean mb-1">
                            {c.label}
                          </p>
                          <p className="text-[24px] font-bold font-mono" style={{ color: c.color }}>
                            {c.value}
                          </p>
                          <p className="text-caption text-fg-disabled font-korean mt-0.5">명</p>
                        </div>
                      ))}
                    </div>
                  )}
                  {sec.id === 'rescue-resource' && (
                    <table className="w-full text-label-2 border-collapse">
                      <thead>
                        <tr className="border-b border-stroke">
                          <th className="px-3 py-2 text-left text-fg-disabled font-korean">유형</th>
                          <th className="px-3 py-2 text-left text-fg-disabled font-korean">
                            선박/장비명
                          </th>
                          <th className="px-3 py-2 text-center text-fg-disabled font-korean">
                            도착예정
                          </th>
                          <th className="px-3 py-2 text-center text-fg-disabled font-korean">
                            상태
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr className="border-b border-stroke">
                          <td
                            colSpan={4}
                            className="px-3 py-3 text-center text-fg-disabled font-korean text-label-2"
                          >
                            —
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  )}
                  {sec.id === 'rescue-grounding' && (
                    <div className="grid grid-cols-3 gap-3">
                      {[
                        { label: '좌초 위험도', value: '—', color: '#ef4444' },
                        { label: '최근 천해', value: '—', color: '#f97316' },
                        { label: '현재 수심', value: '—', color: '#06b6d4' },
                      ].map((g, i) => (
                        <div
                          key={i}
                          className="bg-bg-surface border border-stroke rounded-lg p-4 text-center"
                        >
                          <p className="text-caption text-fg-disabled font-korean mb-1">
                            {g.label}
                          </p>
                          <p
                            className="text-title-3 font-bold font-mono"
                            style={{ color: g.color }}
                          >
                            {g.value}
                          </p>
                        </div>
                      ))}
                    </div>
                  )}
                  {sec.id === 'rescue-weather' && (
                    <div className="grid grid-cols-4 gap-3">
                      {[
                        { label: '파고', value: '—', icon: '🌊' },
                        { label: '풍속', value: '—', icon: '🌬' },
                        { label: '조류', value: '—', icon: '🌀' },
                        { label: '시정', value: '—', icon: '👁' },
                      ].map((w, i) => (
                        <div
                          key={i}
                          className="bg-bg-surface border border-stroke rounded-lg p-3 text-center"
                        >
                          <div className="text-title-2 mb-0.5">{w.icon}</div>
                          <p className="text-title-4 font-bold text-fg font-mono">{w.value}</p>
                          <p className="text-caption text-fg-disabled font-korean mt-1">
                            {w.label}
                          </p>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}

            {activeSections.length === 0 && (
              <div className="flex flex-col items-center justify-center py-20 text-fg-disabled">
                <div className="text-4xl mb-4">📋</div>
                <p className="text-body-2 font-korean">
                  왼쪽에서 보고서에 포함할 섹션을 선택하세요
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default ReportGenerator;
