import { useState, useRef } from 'react';
import { sanitizeHtml } from '@common/utils/sanitize';
import { SystemOverviewPanel } from './contents/SystemOverviewPanel';
import { KospsPanel } from './contents/KospsPanel';
import { PoseidonPanel } from './contents/PoseidonPanel';
import { OpenDriftPanel } from './contents/OpenDriftPanel';
import { LagrangianPanel } from './contents/LagrangianPanel';
import { WeatheringPanel } from './contents/WeatheringPanel';
import { OceanInputPanel } from './contents/OceanInputPanel';
import { VerificationPanel } from './contents/VerificationPanel';
import { EnsemblePanel } from './contents/EnsemblePanel';
import { RoadmapPanel } from './contents/RoadmapPanel';
/* eslint-disable react-refresh/only-export-components */

const theoryTabs: { id: number; icon: string; name: string; nameColor?: string }[] = [
  { id: 0, icon: '🌊', name: '시스템 개요' },
  { id: 7, icon: '🔷', name: 'KOSPS', nameColor: '#06b6d4' },
  { id: 8, icon: '🔴', name: 'POSEIDON', nameColor: '#ef4444' },
  { id: 9, icon: '🔵', name: 'OpenDrift', nameColor: '#3b82f6' },
  { id: 1, icon: '🧭', name: '입자추적법' },
  { id: 2, icon: '🔁', name: '풍화 프로세스' },
  { id: 3, icon: '🌊', name: '해양환경 입력' },
  { id: 4, icon: '✅', name: '모델 검증' },
  { id: 5, icon: '⚡', name: '앙상블', nameColor: '#a855f7' },
  { id: 6, icon: '🚀', name: '발전 방향' },
];

export function OilSpillTheoryView() {
  const [activePanel, setActivePanel] = useState(0);
  const contentRef = useRef<HTMLDivElement>(null);

  const handleExportPDF = () => {
    if (!contentRef.current) return;

    // 컨텐츠를 복제하고 PDF 버튼 제거
    const clone = contentRef.current.cloneNode(true) as HTMLElement;
    clone.querySelectorAll('[data-html2pdf-ignore]').forEach((el) => el.remove());
    // XSS 방지: innerHTML을 살균 처리
    const content = sanitizeHtml(clone.innerHTML);

    // 현재 페이지의 모든 스타일시트를 복사
    const styles = Array.from(document.querySelectorAll('style, link[rel="stylesheet"]'))
      .map((el) => el.outerHTML)
      .join('\n');

    // document.write 대신 Blob URL 사용 (보안 강화)
    const fullHtml = `<!DOCTYPE html>
<html><head><meta charset="utf-8"/>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;">
<title>유출유 확산 모델 이론 및 검증</title>
${styles}
<style>
  :root {
    --t1: #ffffff !important;
    --t2: #d0d6e6 !important;
    --t3: #a8b0c8 !important;
  }
  @media print {
    @page { size: A4; margin: 10mm; }
    body { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
  }
  body { background: var(--bg-base); color: var(--fg-default); font-family: 'Noto Sans KR', sans-serif; padding: 20px 24px; }
</style>
</head><body>${content}</body></html>`;

    const blob = new Blob([fullHtml], { type: 'text/html; charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const win = window.open(url, '_blank');
    if (win) {
      win.addEventListener('afterprint', () => URL.revokeObjectURL(url));
      setTimeout(() => {
        win.document.title = '유출유_확산모델_이론_및_검증';
        win.print();
      }, 500);
    }
    setTimeout(() => URL.revokeObjectURL(url), 30000);
  };

  return (
    <div className="flex flex-col h-full overflow-hidden bg-bg-base">
      <div
        className="flex-1 overflow-y-auto scrollbar-thin p-5"
        ref={contentRef}
        style={{ scrollbarGutter: 'stable' }}
      >
        {/* 헤더 */}
        <div className="flex items-center justify-between mb-5">
          <div className="flex items-center gap-3">
            <div className="w-[42px] h-[42px] rounded-[10px] bg-bg-elevated border border-stroke flex items-center justify-center text-heading-3">
              📐
            </div>
            <div>
              <div className="text-title-2 font-bold text-fg">유출유 확산 모델 이론 및 검증</div>
              <div className="flex items-center gap-2.5 mt-1 flex-wrap">
                <span className="text-label-2 font-medium text-fg-sub">🔷 KOSPS</span>
                <span className="text-label-2 font-medium text-fg-sub">🔴 POSEIDON</span>
                <span className="text-label-2 font-medium text-fg-sub">🔵 OpenDrift</span>
                <span className="text-label-2 font-medium text-fg-sub">⚡ 앙상블</span>
                <span className="text-label-2 text-fg-default">라그랑지안 입자추적 이론 기반</span>
              </div>
            </div>
          </div>
          <button
            onClick={handleExportPDF}
            data-html2pdf-ignore
            className="px-3.5 py-1.5 rounded-sm text-label-2 font-semibold cursor-pointer text-color-accent"
            style={{
              border: '1px solid rgba(6,182,212,.3)',
              background: 'rgba(6,182,212,.08)',
            }}
          >
            📤 PDF 내보내기
          </button>
        </div>

        {/* 내부 네비게이션 탭 */}
        <div className="flex gap-0.5 rounded-lg p-1 mb-5 bg-bg-card border border-stroke">
          {theoryTabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActivePanel(tab.id)}
              className={`flex-1 py-2 px-1 text-label-1 font-medium rounded-md transition-all duration-150 cursor-pointer border ${
                activePanel === tab.id
                  ? 'border-stroke-light bg-bg-elevated text-fg'
                  : 'border-transparent bg-bg-card text-fg-default hover:text-fg-sub'
              }`}
            >
              {tab.icon} {tab.name}
            </button>
          ))}
        </div>

        {activePanel === 0 && <SystemOverviewPanel />}
        {activePanel === 7 && <KospsPanel />}
        {activePanel === 8 && <PoseidonPanel />}
        {activePanel === 9 && <OpenDriftPanel />}
        {activePanel === 1 && <LagrangianPanel />}
        {activePanel === 2 && <WeatheringPanel />}
        {activePanel === 3 && <OceanInputPanel />}
        {activePanel === 4 && <VerificationPanel />}
        {activePanel === 5 && <EnsemblePanel />}
        {activePanel === 6 && <RoadmapPanel />}
      </div>
    </div>
  );
}

/* ═══ 공통 스타일 유틸 ═══ */
export const card = 'rounded-[10px] p-[14px] mb-4';
export const cardBg = 'bg-bg-card border border-stroke';
export const labelStyle = (color: string) =>
  ({ fontSize: 'var(--font-size-title-3)', fontWeight: 700, color, marginBottom: '10px' }) as const;
export const bodyText = 'text-label-1 text-fg-sub leading-[1.8]';
export const codeBox = 'bg-bg-base rounded-sm p-[10px] font-mono text-label-1 leading-loose';
export const tag = (color: string) =>
  ({
    padding: '3px 8px',
    borderRadius: '4px',
    fontSize: 'var(--font-size-label-2)',
    color,
    background: `${color}14`,
    border: `1px solid ${color}30`,
  }) as const;
