import { useState, useEffect, useCallback, useRef } from 'react'
import { fetchRescueOps, fetchRescueScenarios } from '../services/rescueApi'
import type { RescueOpsItem, RescueScenarioItem } from '../services/rescueApi'

/* ─── Types ─── */
type Severity = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'RESOLVED'
type DetailView = 0 | 1 | 2

interface RescueScenario {
  id: string
  name: string
  severity: Severity
  timeStep: string
  datetime: string
  gm: string
  list: string
  trim: string
  buoyancy: number
  oilRate: string
  bmRatio: string
  description: string
  compartments: { name: string; status: string; color: string }[]
  assessment: { label: string; value: string; color: string }[]
  actions: { time: string; text: string; color: string }[]
}

const SEV_STYLE: Record<Severity, { bg: string; color: string; label: string }> = {
  CRITICAL: { bg: 'rgba(239,68,68,0.2)', color: '#f87171', label: 'CRITICAL' },
  HIGH: { bg: 'rgba(249,115,22,0.15)', color: '#fb923c', label: 'HIGH' },
  MEDIUM: { bg: 'rgba(251,191,36,0.15)', color: '#fbbf24', label: 'MEDIUM' },
  RESOLVED: { bg: 'rgba(34,197,94,0.15)', color: '#22c55e', label: 'RESOLVED' },
}

const SEV_COLOR: Record<Severity, string> = { CRITICAL: '#f87171', HIGH: '#fb923c', MEDIUM: '#fbbf24', RESOLVED: '#22c55e' }

/* ─── Color helpers ─── */
function gmColor(v: number) { return v < 1.0 ? 'var(--red)' : v < 1.5 ? 'var(--yellow)' : 'var(--green)' }
function listColor(v: number) { return v > 20 ? 'var(--red)' : v > 10 ? 'var(--yellow)' : 'var(--green)' }
function buoyColor(v: number) { return v < 30 ? 'var(--red)' : v < 50 ? 'var(--yellow)' : 'var(--green)' }
function oilColor(v: number) { return v > 100 ? 'var(--red)' : v > 30 ? 'var(--orange)' : v > 0 ? 'var(--yellow)' : 'var(--green)' }

/* ─── API 시나리오 → 로컬 타입 변환 ─── */
function toRescueScenario(s: RescueScenarioItem, i: number): RescueScenario {
  return {
    id: `S-${String(i + 1).padStart(2, '0')}`,
    name: s.description?.split('.')[0] ?? s.timeStep,
    severity: s.svrtCd as Severity,
    timeStep: s.timeStep,
    datetime: s.scenarioDtm
      ? new Date(s.scenarioDtm).toLocaleString('ko-KR', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
        }) + ' KST'
      : '—',
    gm: String(s.gmM ?? 0),
    list: String(s.listDeg ?? 0),
    trim: String(s.trimM ?? 0),
    buoyancy: s.buoyancyPct ?? 0,
    oilRate: s.oilRateLpm != null ? `${s.oilRateLpm} L/min` : '— L/min',
    bmRatio: s.bmRatioPct != null ? `${s.bmRatioPct}%` : '—%',
    description: s.description ?? '',
    compartments: s.compartments ?? [],
    assessment: s.assessment ?? [],
    actions: s.actions ?? [],
  }
}

/* ─── ChartData 타입 ─── */
interface ChartDataItem {
  id: string
  label: string
  gm: number
  list: number
  buoy: number
  oil: number
  bm: number
  severity: Severity
}

/* ═══════════════════════════════════════════════════════════════════
   RescueScenarioView
   ═══════════════════════════════════════════════════════════════════ */
export function RescueScenarioView() {
  const [ops, setOps] = useState<RescueOpsItem[]>([])
  const [apiScenarios, setApiScenarios] = useState<RescueScenarioItem[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedIncident, setSelectedIncident] = useState(0)
  const [checked, setChecked] = useState<Set<string>>(new Set())
  const [selectedId, setSelectedId] = useState('')
  const [sortBy, setSortBy] = useState<'time' | 'risk'>('time')
  const [detailView, setDetailView] = useState<DetailView>(0)
  const [newScnModalOpen, setNewScnModalOpen] = useState(false)

  const loadScenarios = useCallback(async (opsSn: number) => {
    setLoading(true)
    try {
      const items = await fetchRescueScenarios(opsSn)
      setApiScenarios(items)
    } catch (err) {
      console.error('[rescue] 시나리오 조회 실패:', err)
    } finally {
      setLoading(false)
    }
  }, [])

  const loadOps = useCallback(async () => {
    try {
      const items = await fetchRescueOps()
      setOps(items)
      if (items.length > 0) {
        loadScenarios(items[0].rescueOpsSn)
      } else {
        setLoading(false)
      }
    } catch (err) {
      console.error('[rescue] 구난 작전 목록 조회 실패:', err)
      setLoading(false)
    }
  }, [loadScenarios])

  useEffect(() => { loadOps() }, [loadOps])

  useEffect(() => {
    if (ops.length > 0 && ops[selectedIncident]) {
      loadScenarios(ops[selectedIncident].rescueOpsSn)
    }
  }, [selectedIncident, ops, loadScenarios])

  /* API 시나리오 → 로컬 타입 변환 */
  const scenarios: RescueScenario[] = apiScenarios.map(toRescueScenario)

  /* checked / selectedId: apiScenarios 변경 시 초기화 */
  useEffect(() => {
    setChecked(new Set(scenarios.map(s => s.id)))
    if (scenarios.length > 0) setSelectedId(scenarios[0].id)
  }, [apiScenarios]) // eslint-disable-line react-hooks/exhaustive-deps

  /* chartData: scenarios에서 파생 */
  const chartData: ChartDataItem[] = scenarios.map(s => ({
    id: s.id,
    label: s.timeStep,
    gm: parseFloat(s.gm),
    list: parseFloat(s.list),
    buoy: s.buoyancy,
    oil: parseFloat(s.oilRate),
    bm: parseFloat(s.bmRatio),
    severity: s.severity,
  }))

  const selected = scenarios.find(s => s.id === selectedId)

  const sorted = [...scenarios].sort((a, b) => {
    if (sortBy === 'risk') {
      const order: Record<Severity, number> = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, RESOLVED: 3 }
      return order[a.severity] - order[b.severity]
    }
    return 0
  })

  const toggleCheck = (id: string) => {
    setChecked(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id); else next.add(id)
      return next
    })
  }

  return (
    <div className="flex flex-col flex-1 w-full h-full overflow-hidden bg-bg-0">
      {/* ── Header ── */}
      <div className="px-5 py-3.5 border-b border-border flex items-center justify-between shrink-0">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-[10px] flex items-center justify-center text-lg border border-[rgba(6,182,212,.3)]" style={{ background: 'linear-gradient(135deg,rgba(6,182,212,.2),rgba(59,130,246,.15))' }}>📊</div>
          <div>
            <div className="text-[15px] font-bold">긴급구난 시나리오 관리</div>
            <div className="text-[10px] text-text-3 mt-0.5">시간 단계별 시나리오 비교·검토 및 구난 의사결정 지원 (SFR-009)</div>
          </div>
        </div>
        <div className="flex gap-2 items-center">
          <select value={selectedIncident} onChange={e => setSelectedIncident(Number(e.target.value))} className="px-3 py-1.5 rounded-md border border-border bg-bg-3 text-[10px] outline-none">
            {ops.map((op, i) => <option key={op.rescueOpsSn} value={i}>{op.opsCd} · {op.vesselNm}</option>)}
          </select>
          <button onClick={() => setNewScnModalOpen(true)} className="px-3.5 py-1.5 rounded-md border-none text-white text-[10px] font-bold cursor-pointer" style={{ background: 'linear-gradient(135deg,var(--cyan),#3b82f6)' }}>+ 신규 시나리오</button>
        </div>
      </div>

      {/* ── Content: Left List + Right Detail ── */}
      <div className="flex flex-1 overflow-hidden">

        {/* ═══ LEFT: 시나리오 목록 ═══ */}
        <div className="w-[360px] min-w-[360px] bg-bg-1 border-r border-border flex flex-col overflow-hidden">
          {/* Sort bar */}
          <div className="px-3.5 py-2.5 border-b border-border flex items-center justify-between">
            <div className="text-[11px] font-bold">📋 시나리오 목록 <span className="font-normal text-text-3 text-[9px]">({scenarios.length}개)</span></div>
            <div className="flex gap-1">
              {(['time', 'risk'] as const).map(s => (
                <button key={s} onClick={() => setSortBy(s)} className="px-2 py-px rounded text-[9px] font-semibold cursor-pointer" style={{ border: `1px solid ${sortBy === s ? 'rgba(6,182,212,.4)' : 'var(--bd)'}`, background: sortBy === s ? 'rgba(6,182,212,.08)' : 'var(--bg3)', color: sortBy === s ? 'var(--cyan)' : 'var(--t3)' }}>{s === 'time' ? '시간순' : '위험도순'}</button>
              ))}
            </div>
          </div>

          {/* Card list */}
          <div className="flex-1 overflow-y-auto px-3 py-2.5 flex flex-col gap-2 scrollbar-thin">
            {loading && scenarios.length === 0 && (
              <div className="text-center py-10 text-[11px] text-text-3">시나리오 로딩 중...</div>
            )}
            {sorted.map(sc => {
              const isSel = selectedId === sc.id
              const sev = SEV_STYLE[sc.severity]
              return (
                <div key={sc.id} onClick={() => setSelectedId(sc.id)} className={`hns-scn-card${isSel ? ' sel' : ''} p-3 rounded-md cursor-pointer transition-all`}
                  style={{ border: `1px solid ${isSel ? 'rgba(6,182,212,.35)' : 'var(--bd)'}`, background: isSel ? 'rgba(6,182,212,.04)' : 'var(--bg3)' }}>
                  {/* Top: checkbox + ID + severity */}
                  <div className="flex items-center gap-2 mb-2">
                    <input type="checkbox" checked={checked.has(sc.id)} onChange={e => { e.stopPropagation(); toggleCheck(sc.id) }} className="accent-[var(--cyan)]" />
                    <span className="text-xs font-extrabold font-mono" style={{ color: isSel ? 'var(--cyan)' : 'var(--t1)' }}>{sc.id}</span>
                    <span className="px-1.5 py-px rounded text-[8px] font-bold font-mono" style={{ background: sev.bg, color: sev.color }}>{sev.label}</span>
                    <span className="ml-auto text-[9px] text-text-3 font-mono">{sc.timeStep}</span>
                  </div>
                  {/* Name + time */}
                  <div className="text-[11px] font-bold mb-1">{sc.name}</div>
                  <div className="text-[9px] text-text-3 font-mono mb-2">{sc.datetime}</div>
                  {/* KPI grid */}
                  <div className="grid grid-cols-4 gap-1 mb-2 text-[8px] text-center">
                    <div className="py-1 bg-bg-0 rounded">
                      <div className="text-text-3">GM</div>
                      <div className="font-bold font-mono" style={{ color: gmColor(parseFloat(sc.gm)) }}>{sc.gm}m</div>
                    </div>
                    <div className="py-1 bg-bg-0 rounded">
                      <div className="text-text-3">횡경사</div>
                      <div className="font-bold font-mono" style={{ color: listColor(parseFloat(sc.list)) }}>{sc.list}°</div>
                    </div>
                    <div className="py-1 bg-bg-0 rounded">
                      <div className="text-text-3">부력</div>
                      <div className="font-bold font-mono" style={{ color: buoyColor(sc.buoyancy) }}>{sc.buoyancy}%</div>
                    </div>
                    <div className="py-1 bg-bg-0 rounded">
                      <div className="text-text-3">유출</div>
                      <div className="font-bold font-mono" style={{ color: oilColor(parseFloat(sc.oilRate)) }}>{sc.oilRate.split(' ')[0]}</div>
                    </div>
                  </div>
                  {/* Description */}
                  <div className="text-[9px] text-text-2 leading-[1.5]">{sc.description}</div>
                </div>
              )
            })}
          </div>

          {/* Bottom actions */}
          <div className="px-3.5 py-2.5 border-t border-border flex gap-1.5">
            <button onClick={() => setDetailView(1)} className="flex-1 py-2 rounded-md border-none text-white text-[10px] font-bold cursor-pointer" style={{ background: 'linear-gradient(135deg,var(--cyan),#3b82f6)' }}>📊 선택 시나리오 비교</button>
            <button className="px-3.5 py-2 rounded-md border border-border bg-bg-3 text-text-2 text-[10px] font-semibold cursor-pointer">📄 보고서</button>
          </div>
        </div>

        {/* ═══ RIGHT: 상세/비교 ═══ */}
        <div className="flex-1 min-w-0 flex flex-col overflow-hidden">
          {/* Detail tabs */}
          <div className="flex border-b border-border shrink-0">
            {(['📋 시나리오 상세', '📊 비교 차트', '🗺 지도 오버레이'] as const).map((label, i) => (
              <button key={i} onClick={() => setDetailView(i as DetailView)} className="rsc-atab flex-1 py-2.5 px-1 border-none cursor-pointer transition-all text-[10px]" style={{ background: detailView === i ? 'rgba(6,182,212,.04)' : 'transparent', color: detailView === i ? 'var(--cyan)' : 'var(--t3)', fontWeight: detailView === i ? 700 : 600, borderBottom: `2px solid ${detailView === i ? 'var(--cyan)' : 'transparent'}` }}>{label}</button>
            ))}
          </div>

          {/* View content */}
          <div className="flex-1 overflow-y-auto scrollbar-thin">

            {/* ─── VIEW 0: 시나리오 상세 ─── */}
            {detailView === 0 && selected && (
              <div className="p-5">
                {/* Gradient header */}
                <div className="px-5 py-4 rounded-[10px] border border-[rgba(6,182,212,.2)] mb-4" style={{ background: 'linear-gradient(135deg,rgba(6,182,212,.06),rgba(239,68,68,.04))' }}>
                  <div className="flex items-center gap-2.5 mb-2.5">
                    <span className="text-base font-extrabold font-mono text-primary-cyan">{selected.id}</span>
                    <span className="text-sm font-bold">{selected.name}</span>
                    <span className="px-2 py-px rounded text-[9px] font-bold font-mono" style={{ background: SEV_STYLE[selected.severity].bg, color: SEV_STYLE[selected.severity].color }}>{selected.severity}</span>
                    <span className="ml-auto text-[10px] text-text-3 font-mono">{selected.datetime}</span>
                  </div>
                  {/* 6 KPI cards */}
                  <div className="grid gap-2 text-[8px] text-center" style={{ gridTemplateColumns: 'repeat(6,1fr)' }}>
                    {[
                      { label: 'GM (복원심)', value: `${selected.gm}m`, color: gmColor(parseFloat(selected.gm)) },
                      { label: '횡경사 (List)', value: `${selected.list}°`, color: listColor(parseFloat(selected.list)) },
                      { label: '종경사 (Trim)', value: `${selected.trim}m`, color: parseFloat(selected.trim) > 3 ? 'var(--red)' : 'var(--t1)' },
                      { label: '잔존부력', value: `${selected.buoyancy}%`, color: buoyColor(selected.buoyancy) },
                      { label: '유출률', value: selected.oilRate, color: oilColor(parseFloat(selected.oilRate)) },
                      { label: 'BM 비율', value: selected.bmRatio, color: parseFloat(selected.bmRatio) > 100 ? 'var(--red)' : parseFloat(selected.bmRatio) > 85 ? 'var(--orange)' : 'var(--green)' },
                    ].map(kpi => (
                      <div key={kpi.label} className="px-1 py-2 bg-bg-3 rounded-md border border-border">
                        <div className="text-text-3 mb-1">{kpi.label}</div>
                        <div className="text-lg font-extrabold font-mono" style={{ color: kpi.color }}>{kpi.value}</div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 2-column: 침수구획 + 구난판단 */}
                <div className="grid grid-cols-2 gap-4 mb-4">
                  {/* 침수 구획 */}
                  <div className="bg-bg-3 border border-border rounded-md p-3.5">
                    <div className="text-[11px] font-bold text-primary-cyan mb-2.5">🚢 침수 구획 상태</div>
                    <div className="flex flex-col gap-1.5">
                      {selected.compartments.map((c, i) => (
                        <div key={i} className="flex items-center justify-between px-2.5 py-1.5 bg-bg-0 rounded" style={{ borderLeft: `3px solid ${c.color}` }}>
                          <span className="text-[9px]">{c.name}</span>
                          <span className="text-[9px] font-semibold font-mono" style={{ color: c.color }}>{c.status}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                  {/* 구난 판단 */}
                  <div className="bg-bg-3 border border-border rounded-md p-3.5">
                    <div className="text-[11px] font-bold text-status-red mb-2.5">⚠️ 구난 판단 요약</div>
                    <div className="flex flex-col gap-1.5">
                      {selected.assessment.map((a, i) => (
                        <div key={i} className="px-2.5 py-2 bg-bg-0 rounded" style={{ borderLeft: `3px solid ${a.color}` }}>
                          <div className="text-[9px] font-bold" style={{ color: a.color }}>{a.label}</div>
                          <div className="text-[9px] text-text-2 mt-0.5">{a.value}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                {/* 대응 조치 이력 */}
                <div className="bg-bg-3 border border-border rounded-md p-3.5">
                  <div className="text-[11px] font-bold text-status-orange mb-2.5">📋 대응 조치 이력</div>
                  <div className="flex flex-col gap-1.5">
                    {selected.actions.map((a, i) => (
                      <div key={i} className="flex items-center gap-2.5 px-2.5 py-1.5 bg-bg-0 rounded">
                        <span className="text-[10px] font-bold font-mono min-w-[40px]" style={{ color: a.color }}>{a.time}</span>
                        <div className="w-1.5 h-1.5 rounded-full shrink-0" style={{ background: a.color }} />
                        <span className="text-[9px]">{a.text}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* ─── VIEW 1: 비교 차트 ─── */}
            {detailView === 1 && <ScenarioComparison chartData={chartData} />}

            {/* ─── VIEW 2: 지도 오버레이 ─── */}
            {detailView === 2 && (
              <div className="p-5">
                <div className="bg-bg-3 border border-border rounded-[10px] p-5 text-center">
                  <div className="text-[32px] opacity-30 mb-2.5">🗺</div>
                  <div className="text-[13px] font-bold mb-1.5">GIS 기반 시나리오 비교</div>
                  <div className="text-[10px] text-text-3 leading-relaxed mb-4">선택된 시나리오의 침수 구역을 지도 위에 오버레이하여 비교합니다.</div>
                  <div className="flex gap-2 justify-center flex-wrap">
                    {scenarios.map(sc => (
                      <div key={sc.id} className="px-3 py-1.5 rounded-md text-[9px]" style={{ border: `1px solid ${SEV_STYLE[sc.severity].color}40`, background: SEV_STYLE[sc.severity].bg }}>
                        <span className="font-bold" style={{ color: SEV_STYLE[sc.severity].color }}>{sc.id}</span>
                        <span className="text-text-2 ml-1.5">{sc.name}</span>
                      </div>
                    ))}
                  </div>
                  <div className="mt-4 p-[30px] bg-bg-0 rounded-md border border-dashed border-border">
                    <div className="text-[11px] text-text-3">지도 뷰 영역 — 구난 분석 지도와 연동하여 침수 구역 오버레이 표시</div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ═══ 신규 시나리오 모달 ═══ */}
      {newScnModalOpen && <NewScenarioModal ops={ops} onClose={() => setNewScnModalOpen(false)} />}
    </div>
  )
}

/* ═══ 신규 시나리오 생성 모달 ═══ */
function NewScenarioModal({ ops, onClose }: { ops: RescueOpsItem[]; onClose: () => void }) {
  const overlayRef = useRef<HTMLDivElement>(null)
  const [submitting, setSubmitting] = useState(false)
  const [done, setDone] = useState(false)

  const handleSubmit = () => {
    setSubmitting(true)
    setTimeout(() => { setSubmitting(false); setDone(true) }, 2000)
  }

  /* ── shared className helpers ── */
  const labelCls = 'text-[9px] text-text-3 block mb-1'
  const inputCls = 'w-full px-3 py-2 rounded-md border border-border bg-bg-0 text-[11px] outline-none'
  const numCls = `${inputCls} font-mono`
  const sectionIcon = (n: number) => (
    <div className="w-[18px] h-[18px] rounded-[5px] flex items-center justify-center text-[9px] font-bold text-primary-cyan" style={{ background: 'rgba(6,182,212,.12)' }}>{n}</div>
  )
  const sectionTitleCls = 'text-[11px] font-bold text-primary-cyan mb-2.5 flex items-center gap-1.5'

  return (
    <div ref={overlayRef} onClick={e => { if (e.target === overlayRef.current) onClose() }}
      className="fixed inset-0 z-[9999] flex items-center justify-center" style={{ background: 'rgba(0,0,0,.65)', backdropFilter: 'blur(6px)' }}>
      <div className="bg-bg-1 border border-[rgba(6,182,212,.3)] rounded-[14px] w-[700px] max-h-[88vh] flex flex-col overflow-hidden" style={{ boxShadow: '0 24px 80px rgba(0,0,0,.6)' }}>

        {/* ── 헤더 ── */}
        <div className="px-6 pt-5 pb-4 border-b border-border shrink-0 relative overflow-hidden">
          <div className="absolute top-0 left-0 right-0 h-0.5" style={{ background: 'linear-gradient(90deg,#06b6d4,#3b82f6,#8b5cf6)' }} />
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div className="w-9 h-9 rounded-[10px] flex items-center justify-center text-lg" style={{ background: 'linear-gradient(135deg,rgba(6,182,212,.15),rgba(59,130,246,.08))' }}>🚨</div>
              <div>
                <div className="text-[15px] font-bold">신규 긴급구난 시나리오 생성</div>
                <div className="text-[10px] text-text-3 mt-0.5">선박 사고 조건 및 구난 분석 파라미터를 설정합니다 (SFR-009)</div>
              </div>
            </div>
            <span onClick={onClose} className="text-lg cursor-pointer text-text-3 p-1">✕</span>
          </div>
        </div>

        {/* ── 본문 스크롤 ── */}
        <div className="flex-1 overflow-y-auto px-6 py-5 flex flex-col gap-[18px] scrollbar-thin">

          {/* ① 기본 정보 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(1)} 기본 정보</div>
            <div className="grid grid-cols-2 gap-2.5">
              <div>
                <label className={labelCls}>시나리오명 <span className="text-[#f87171]">*</span></label>
                <input type="text" placeholder="예: T+3h 기관실 침수 확대" className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>연계 사고 <span className="text-[#f87171]">*</span></label>
                <select defaultValue="0" className={inputCls}>
                  {ops.map((op, i) => <option key={op.rescueOpsSn} value={i}>{op.opsCd} · {op.vesselNm}</option>)}
                  <option value="new">+ 신규 사고 등록...</option>
                </select>
              </div>
              <div>
                <label className={labelCls}>시간 단계 (Time Step) <span className="text-[#f87171]">*</span></label>
                <select defaultValue="T+3h" className={inputCls}>
                  {['T+0h (사고 발생 직후)', 'T+1h', 'T+2h', 'T+3h', 'T+6h', 'T+12h', 'T+24h', 'T+48h'].map(t => <option key={t} value={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>기준 시각</label>
                <input type="datetime-local" defaultValue="2024-10-27T13:30" className={inputCls} />
              </div>
            </div>
          </div>

          {/* ② 선박 정보 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(2)} 선박 정보</div>
            <div className="grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>선박명 <span className="text-[#f87171]">*</span></label>
                <input type="text" defaultValue="M/V SEA GUARDIAN" className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>선종 <span className="text-[#f87171]">*</span></label>
                <select defaultValue="화물선 (Cargo)" className={inputCls}>
                  {['유조선 (Tanker)', '화물선 (Cargo)', '컨테이너선 (Container)', '여객선 (Passenger)', '어선 (Fishing)', 'LNG선', '케미컬선 (Chemical)', '기타'].map(v => <option key={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>총톤수 (GT)</label>
                <input type="number" defaultValue={45000} step={100} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>선체 길이 (m)</label>
                <input type="number" defaultValue={189} step={1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>흘수 (m)</label>
                <input type="number" defaultValue={8.5} step={0.1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>승선 인원</label>
                <input type="number" defaultValue={22} step={1} min={0} className={numCls} />
              </div>
            </div>
            <div className="mt-2 grid grid-cols-2 gap-2.5">
              <div>
                <label className={labelCls}>적재 화물</label>
                <input type="text" placeholder="예: 일반화물, 벙커C 450kL" className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>연료유 종류 · 탑재량</label>
                <input type="text" defaultValue="벙커C 450kL / MGO 80kL" className={inputCls} />
              </div>
            </div>
          </div>

          {/* ③ 사고 조건 · 선체 상태 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(3)} 사고 조건 · 선체 상태</div>
            <div className="grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>사고 유형 <span className="text-[#f87171]">*</span></label>
                <select defaultValue="충돌 (Collision)" className={inputCls}>
                  {['충돌 (Collision)', '좌초 (Grounding)', '침수 (Flooding)', '기관고장 (Engine Failure)', '화재 (Fire)', '전복 (Capsizing)', '구조손상 (Structural)'].map(v => <option key={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>손상 구역</label>
                <select defaultValue="우현 중앙 (Starboard Mid)" className={inputCls}>
                  {['선수부 (Bow)', '우현 중앙 (Starboard Mid)', '좌현 중앙 (Port Mid)', '선미부 (Stern)', '기관실 (Engine Room)', '선저 (Bottom)', '복수 구역'].map(v => <option key={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>파공 크기 (㎡)</label>
                <input type="number" defaultValue={2.8} step={0.1} min={0} className={numCls} />
              </div>
            </div>
            <div className="mt-2 grid grid-cols-4 gap-2.5">
              <div>
                <label className={labelCls}>횡경사 (°)</label>
                <input type="number" defaultValue={8.5} step={0.5} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>종경사 (°)</label>
                <input type="number" defaultValue={2.1} step={0.1} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>건현 (m)</label>
                <input type="number" defaultValue={3.2} step={0.1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>GM (m)</label>
                <input type="number" defaultValue={1.8} step={0.1} className={numCls} />
              </div>
            </div>
            {/* 침수 상태 */}
            <div className="mt-2.5 px-3.5 py-2.5 rounded-md border border-[rgba(239,68,68,.12)]" style={{ background: 'rgba(239,68,68,.04)' }}>
              <div className="text-[9px] font-bold text-[#f87171] mb-2">💧 침수 상태</div>
              <div className="grid grid-cols-4 gap-2">
                <div>
                  <label className="text-[8px] text-text-3 block mb-px">침수 구역 수</label>
                  <select defaultValue="2개" className="w-full px-2 py-1.5 rounded border border-border bg-bg-0 text-[10px] outline-none">
                    {['1개', '2개', '3개', '4개 이상'].map(v => <option key={v}>{v}</option>)}
                  </select>
                </div>
                <div>
                  <label className="text-[8px] text-text-3 block mb-px">침수량 (톤)</label>
                  <input type="number" defaultValue={850} step={50} min={0} className="w-full px-2 py-1.5 rounded border border-border bg-bg-0 text-[10px] font-mono outline-none" />
                </div>
                <div>
                  <label className="text-[8px] text-text-3 block mb-px">침수 진행률 (t/h)</label>
                  <input type="number" defaultValue={120} step={10} min={0} className="w-full px-2 py-1.5 rounded border border-border bg-bg-0 text-[10px] font-mono outline-none" />
                </div>
                <div>
                  <label className="text-[8px] text-text-3 block mb-px">배수 능력 (t/h)</label>
                  <input type="number" defaultValue={80} step={10} min={0} className="w-full px-2 py-1.5 rounded border border-border bg-bg-0 text-[10px] font-mono outline-none" />
                </div>
              </div>
            </div>
          </div>

          {/* ④ 사고 위치 · 해상 조건 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(4)} 사고 위치 · 해상 조건</div>
            <div className="grid gap-2.5 items-end" style={{ gridTemplateColumns: '1fr 1fr auto' }}>
              <div>
                <label className={labelCls}>위도 (Lat)</label>
                <input type="text" defaultValue="34.5832" className={`${inputCls} font-mono`} />
              </div>
              <div>
                <label className={labelCls}>경도 (Lon)</label>
                <input type="text" defaultValue="128.4217" className={`${inputCls} font-mono`} />
              </div>
              <button className="px-3.5 py-2 rounded-md border border-[rgba(6,182,212,.3)] text-primary-cyan text-[10px] font-semibold cursor-pointer whitespace-nowrap" style={{ background: 'rgba(6,182,212,.08)' }}>📍 지도에서 선택</button>
            </div>
            <div className="mt-2 grid grid-cols-4 gap-2.5">
              <div>
                <label className={labelCls}>풍향 / 풍속 <span className="text-[#f87171]">*</span></label>
                <div className="flex gap-1">
                  <select defaultValue="SW" className="flex-1 p-2 rounded-md border border-border bg-bg-0 text-[10px] outline-none">
                    {['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].map(d => <option key={d}>{d}</option>)}
                  </select>
                  <input type="number" defaultValue={12.5} step={0.5} min={0} className="w-[60px] p-2 rounded-md border border-border bg-bg-0 text-[10px] font-mono outline-none text-center" />
                </div>
              </div>
              <div>
                <label className={labelCls}>파고 (m) <span className="text-[#f87171]">*</span></label>
                <input type="number" defaultValue={2.5} step={0.1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>조류 방향 / 유속</label>
                <div className="flex gap-1">
                  <select defaultValue="NE" className="flex-1 p-2 rounded-md border border-border bg-bg-0 text-[10px] outline-none">
                    {['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].map(d => <option key={d}>{d}</option>)}
                  </select>
                  <input type="number" defaultValue={1.2} step={0.1} min={0} className="w-[60px] p-2 rounded-md border border-border bg-bg-0 text-[10px] font-mono outline-none text-center" />
                </div>
              </div>
              <div>
                <label className={labelCls}>수심 (m)</label>
                <input type="number" defaultValue={25} step={1} min={0} className={numCls} />
              </div>
            </div>
            <div className="mt-1.5 grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>시정 (km)</label>
                <input type="number" defaultValue={8} step={1} min={0} className={numCls} />
              </div>
              <div>
                <label className={labelCls}>해상 상태 (Douglas)</label>
                <select defaultValue="3 — 거침 (Moderate)" className={inputCls}>
                  {['0 — 평온 (Calm)', '1 — 잔잔 (Smooth)', '2 — 약간 거침 (Slight)', '3 — 거침 (Moderate)', '4 — 다소 높음 (Rough)', '5 — 높음 (Very rough)', '6 — 매우 높음 (High)'].map(v => <option key={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>수온 (°C)</label>
                <input type="number" defaultValue={17.2} step={0.5} className={numCls} />
              </div>
            </div>
          </div>

          {/* ⑤ 구난 분석 설정 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(5)} 구난 분석 설정</div>
            <div className="grid grid-cols-3 gap-2.5">
              <div>
                <label className={labelCls}>분석 모델 <span className="text-[#f87171]">*</span></label>
                <select defaultValue="R&D 긴급구난 종합분석" className={inputCls}>
                  {['R&D 긴급구난 종합분석', 'HECSALV (Salvage)', 'NAPA Emergency', '수동 입력 (직접 판단)'].map(v => <option key={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>예측 시간</label>
                <select defaultValue="12시간" className={inputCls}>
                  {['6시간', '12시간', '24시간', '48시간', '72시간'].map(v => <option key={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>분석 항목</label>
                <div className="flex flex-wrap gap-1 mt-0.5">
                  {['복원성', '예인력', '인양력', '유출 위험'].map(item => (
                    <label key={item} className="flex items-center gap-px text-[8px] text-text-2 cursor-pointer">
                      <input type="checkbox" defaultChecked style={{ accentColor: 'var(--cyan)', transform: 'scale(.85)' }} />{item}
                    </label>
                  ))}
                </div>
              </div>
            </div>
            {/* R&D 연계 분석 */}
            <div className="mt-2.5 px-3.5 py-2.5 flex flex-col gap-1.5 rounded-md border border-[rgba(249,115,22,.12)]" style={{ background: 'rgba(249,115,22,.04)' }}>
              <div className="text-[9px] font-bold text-status-orange">🔗 R&D 연계 분석</div>
              <div className="flex gap-3">
                <label className="flex items-center gap-1 text-[9px] text-text-2 cursor-pointer">
                  <input type="checkbox" style={{ accentColor: 'var(--orange)' }} /> 유출유 확산예측 동시 실행
                </label>
                <label className="flex items-center gap-1 text-[9px] text-text-2 cursor-pointer">
                  <input type="checkbox" style={{ accentColor: 'var(--orange)' }} /> HNS 대기확산 연계 분석
                </label>
              </div>
              <div className="text-[8px] text-text-3 leading-[1.5]">화물 유출 가능성이 있는 경우, 긴급구난 분석 결과와 확산예측을 동시에 수행하여 종합 대응 판단을 지원합니다</div>
            </div>
          </div>

          {/* ⑥ 비고 */}
          <div>
            <div className={sectionTitleCls}>{sectionIcon(6)} 비고</div>
            <textarea placeholder="시나리오 설명, 가정 조건, 현장 상황 특이사항 등을 기록합니다..." className="w-full h-[60px] px-3 py-2.5 rounded-md border border-border bg-bg-0 text-[10px] outline-none resize-y leading-relaxed scrollbar-thin" />
          </div>
        </div>

        {/* ── 하단 버튼 ── */}
        <div className="px-6 py-4 border-t border-border shrink-0 flex gap-2 items-center">
          <div className="flex-1 text-[9px] text-text-3 leading-[1.5]">
            <span className="text-[#f87171]">*</span> 필수 입력 항목 · 해상 조건은 기상청/조사원 API 연계 시 자동 갱신
          </div>
          <button onClick={onClose} className="px-5 py-2.5 rounded-md border border-border bg-bg-3 text-text-2 text-xs font-semibold cursor-pointer">취소</button>
          {done ? (
            <button onClick={onClose} className="px-7 py-2.5 rounded-md border-none text-white text-xs font-bold cursor-pointer" style={{ background: 'linear-gradient(135deg,#22c55e,#10b981)', boxShadow: '0 4px 16px rgba(34,197,94,.3)' }}>✅ 생성 완료 — 닫기</button>
          ) : (
            <button onClick={handleSubmit} disabled={submitting} className="px-7 py-2.5 rounded-md border-none text-xs font-bold" style={{ background: submitting ? 'var(--bg3)' : 'linear-gradient(135deg,#06b6d4,#3b82f6)', color: submitting ? 'var(--t3)' : '#fff', cursor: submitting ? 'wait' : 'pointer', boxShadow: submitting ? 'none' : '0 4px 16px rgba(6,182,212,.3)' }}>
              {submitting ? '⏳ 분석 중...' : '🚨 시나리오 생성 · 분석 실행'}
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

/* ═══ 비교 차트 컴포넌트 ═══ */
function ScenarioComparison({ chartData }: { chartData: ChartDataItem[] }) {
  const W = 480, H = 180, PX = 50, PY = 20
  const pw = W - PX * 2, ph = H - PY * 2
  const xStep = chartData.length > 1 ? pw / (chartData.length - 1) : pw

  if (chartData.length === 0) {
    return (
      <div className="p-10 text-center text-[11px] text-text-3">
        비교할 시나리오 데이터가 없습니다.
      </div>
    )
  }

  return (
    <div className="p-5">
      {/* Chart 1: GM 추이 */}
      <div className="bg-bg-3 border border-border rounded-[10px] p-4 mb-4">
        <div className="text-[11px] font-bold text-primary-cyan mb-2.5">📈 GM (복원심) 변화 추이 (m)</div>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxHeight: 180 }}>
          {/* Grid */}
          {[0, 0.5, 1.0, 1.5, 2.0].map(v => {
            const y = PY + ph - (v / 2.0) * ph
            return <g key={v}><line x1={PX} x2={W - PX} y1={y} y2={y} stroke="rgba(255,255,255,.06)" /><text x={PX - 6} y={y + 3} textAnchor="end" fill="var(--t3)" fontSize={8} fontFamily="var(--fM)">{v}</text></g>
          })}
          {/* GM=1.0 threshold */}
          <line x1={PX} x2={W - PX} y1={PY + ph - (1.0 / 2.0) * ph} y2={PY + ph - (1.0 / 2.0) * ph} stroke="rgba(239,68,68,.4)" strokeDasharray="4" />
          <text x={W - PX + 4} y={PY + ph - (1.0 / 2.0) * ph + 3} fill="var(--red)" fontSize={7}>GM=1.0 위험</text>
          {/* Area */}
          <polygon points={`${PX},${PY + ph} ${chartData.map((d, i) => `${PX + i * xStep},${PY + ph - (d.gm / 2.0) * ph}`).join(' ')} ${PX + (chartData.length - 1) * xStep},${PY + ph}`} fill="rgba(6,182,212,.08)" />
          {/* Line + dots */}
          <polyline points={chartData.map((d, i) => `${PX + i * xStep},${PY + ph - (d.gm / 2.0) * ph}`).join(' ')} fill="none" stroke="var(--cyan)" strokeWidth={2} />
          {chartData.map((d, i) => (
            <g key={d.id}>
              <circle cx={PX + i * xStep} cy={PY + ph - (d.gm / 2.0) * ph} r={4} fill={SEV_COLOR[d.severity]} stroke="#0d1117" strokeWidth={1.5} />
              <text x={PX + i * xStep} y={PY + ph + 14} textAnchor="middle" fill="var(--t3)" fontSize={8} fontFamily="var(--fK)">{d.label}</text>
              <text x={PX + i * xStep} y={PY + ph - (d.gm / 2.0) * ph - 8} textAnchor="middle" fill="var(--t1)" fontSize={8} fontFamily="var(--fM)" fontWeight={700}>{d.gm}</text>
            </g>
          ))}
        </svg>
      </div>

      {/* Charts 2 & 3: 2-column */}
      <div className="grid grid-cols-2 gap-4 mb-4">
        {/* Chart 2: 횡경사 변화 */}
        <div className="bg-bg-3 border border-border rounded-[10px] p-4">
          <div className="text-[11px] font-bold text-status-orange mb-2.5">📉 횡경사 (List) 변화 (°)</div>
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxHeight: 160 }}>
            {[0, 5, 10, 15, 20, 25].map(v => {
              const y = PY + ph - (v / 25) * ph
              return <g key={v}><line x1={PX} x2={W - PX} y1={y} y2={y} stroke="rgba(255,255,255,.06)" /><text x={PX - 6} y={y + 3} textAnchor="end" fill="var(--t3)" fontSize={7} fontFamily="var(--fM)">{v}</text></g>
            })}
            <line x1={PX} x2={W - PX} y1={PY + ph - (15 / 25) * ph} y2={PY + ph - (15 / 25) * ph} stroke="rgba(239,68,68,.3)" strokeDasharray="4" />
            <polyline points={chartData.map((d, i) => `${PX + i * xStep},${PY + ph - (d.list / 25) * ph}`).join(' ')} fill="none" stroke="var(--orange)" strokeWidth={2} />
            {chartData.map((d, i) => (
              <g key={d.id}>
                <circle cx={PX + i * xStep} cy={PY + ph - (d.list / 25) * ph} r={3.5} fill={SEV_COLOR[d.severity]} stroke="#0d1117" strokeWidth={1.5} />
                <text x={PX + i * xStep} y={PY + ph + 14} textAnchor="middle" fill="var(--t3)" fontSize={7} fontFamily="var(--fK)">{d.label}</text>
              </g>
            ))}
          </svg>
        </div>

        {/* Chart 3: 유출률 변화 (bar) */}
        <div className="bg-bg-3 border border-border rounded-[10px] p-4">
          <div className="text-[11px] font-bold text-status-red mb-2.5">📊 유출률 변화 (L/min)</div>
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxHeight: 160 }}>
            {[0, 50, 100, 150, 200].map(v => {
              const y = PY + ph - (v / 200) * ph
              return <g key={v}><line x1={PX} x2={W - PX} y1={y} y2={y} stroke="rgba(255,255,255,.06)" /><text x={PX - 6} y={y + 3} textAnchor="end" fill="var(--t3)" fontSize={7} fontFamily="var(--fM)">{v}</text></g>
            })}
            {chartData.map((d, i) => {
              const barW = xStep * 0.5
              const barH = (d.oil / 200) * ph
              return (
                <g key={d.id}>
                  <rect x={PX + i * xStep - barW / 2} y={PY + ph - barH} width={barW} height={barH} rx={3} fill={SEV_COLOR[d.severity]} opacity={0.7} />
                  <text x={PX + i * xStep} y={PY + ph - barH - 4} textAnchor="middle" fill="var(--t1)" fontSize={8} fontFamily="var(--fM)" fontWeight={700}>{d.oil}</text>
                  <text x={PX + i * xStep} y={PY + ph + 14} textAnchor="middle" fill="var(--t3)" fontSize={7} fontFamily="var(--fK)">{d.label}</text>
                </g>
              )
            })}
          </svg>
        </div>
      </div>

      {/* Chart 4: 비교 테이블 */}
      <div className="bg-bg-3 border border-border rounded-[10px] p-4">
        <div className="text-[11px] font-bold mb-2.5">📋 시나리오 종합 비교표</div>
        <table className="w-full border-collapse text-[9px]">
          <thead>
            <tr style={{ background: 'rgba(6,182,212,.06)' }}>
              <th className="py-[7px] px-2 text-left border-b-2 border-[var(--bdL)] text-primary-cyan">지표</th>
              {chartData.map(d => (
                <th key={d.id} className="py-[7px] px-2 text-center border-b-2 border-[var(--bdL)]" style={{ color: SEV_COLOR[d.severity] }}>{d.id}<br /><span className="font-normal text-[8px] text-text-3">{d.label}</span></th>
              ))}
            </tr>
          </thead>
          <tbody>
            {[
              { label: 'GM (m)', key: 'gm', fmt: (d: ChartDataItem) => d.gm.toFixed(1), clr: (d: ChartDataItem) => gmColor(d.gm) },
              { label: '횡경사 (°)', key: 'list', fmt: (d: ChartDataItem) => `${d.list}°`, clr: (d: ChartDataItem) => listColor(d.list) },
              { label: '잔존부력 (%)', key: 'buoy', fmt: (d: ChartDataItem) => `${d.buoy}%`, clr: (d: ChartDataItem) => buoyColor(d.buoy) },
              { label: '유출률 (L/min)', key: 'oil', fmt: (d: ChartDataItem) => `${d.oil}`, clr: (d: ChartDataItem) => oilColor(d.oil) },
              { label: 'BM 비율 (%)', key: 'bm', fmt: (d: ChartDataItem) => `${d.bm}%`, clr: (d: ChartDataItem) => d.bm > 100 ? 'var(--red)' : d.bm > 85 ? 'var(--orange)' : 'var(--green)' },
              { label: '위험 등급', key: 'sev', fmt: (d: ChartDataItem) => d.severity, clr: (d: ChartDataItem) => SEV_COLOR[d.severity] },
            ].map(row => (
              <tr key={row.label} style={{ borderBottom: '1px solid rgba(255,255,255,.04)' }}>
                <td className="py-1.5 px-2 font-semibold text-text-2">{row.label}</td>
                {chartData.map(d => (
                  <td key={d.id} className="py-1.5 px-2 text-center font-mono font-bold" style={{ color: row.clr(d) }}>{row.fmt(d)}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
