import { useState, useEffect, useRef } from 'react';
import { fetchPredictionAnalyses } from '@components/prediction/services/predictionApi';
import type { PredictionAnalysis } from '@components/prediction/services/predictionApi';
import { fetchHnsAnalyses } from '@components/hns/services/hnsApi';
import type { HnsAnalysisItem } from '@interfaces/hns/HnsInterface';
import { fetchRescueOps } from '@components/rescue/services/rescueApi';
import type { RescueOpsItem } from '@interfaces/rescue/RescueInterface';

// ── 타입 정의 ──────────────────────────────────────────
export type AnalysisModalType = 'oil' | 'hns' | 'rescue';

export type AnalysisApplyPayload =
  | { type: 'oil'; items: PredictionAnalysis[] }
  | { type: 'hns'; items: HnsAnalysisItem[] }
  | { type: 'rescue'; items: RescueOpsItem[] };

export interface AnalysisSelectModalProps {
  type: AnalysisModalType;
  isOpen: boolean;
  onClose: () => void;
  initialSelectedIds: Set<string>;
  onApply: (payload: AnalysisApplyPayload) => void;
}

type StatusTab = 'all' | 'active' | 'done';

// ── 메타 설정 ───────────────────────────────────────────
const MODAL_META: Record<AnalysisModalType, { icon: string; title: string; color: string }> = {
  oil: { icon: '🛢', title: '유출유 확산예측 분석 목록', color: 'var(--color-warning)' },
  hns: { icon: '🧪', title: 'HNS 대기확산 분석 목록', color: 'var(--color-warning)' },
  rescue: { icon: '🚨', title: '긴급구난 분석 목록', color: 'var(--color-accent)' },
};

// ── 상태 배지 ───────────────────────────────────────────
function StatusBadge({ code }: { code: string }) {
  const upper = code.toUpperCase();
  let label = code;
  let color = 'var(--fg-disabled)';
  let bg = 'rgba(107,114,128,0.1)';

  if (upper === 'ACTIVE' || upper === 'RUNNING' || upper === 'IN_PROGRESS') {
    label = '대응중';
    color = 'var(--color-warning)';
    bg = 'rgba(249,115,22,0.1)';
  } else if (
    upper === 'COMPLETED' ||
    upper === 'RESOLVED' ||
    upper === 'CLOSED' ||
    upper === 'DONE'
  ) {
    label = '완료';
    color = 'var(--fg-disabled)';
    bg = 'rgba(107,114,128,0.1)';
  } else if (upper === 'CRITICAL' || upper === 'EMERGENCY') {
    label = '긴급';
    color = 'var(--color-danger)';
    bg = 'rgba(239,68,68,0.1)';
  } else if (upper === 'INVESTIGATING') {
    label = '조사중';
    color = 'var(--color-info)';
    bg = 'rgba(59,130,246,0.1)';
  }

  return (
    <span
      style={{
        padding: '2px 6px',
        borderRadius: '3px',
        fontSize: '11px',
        fontWeight: 700,
        color,
        background: bg,
        whiteSpace: 'nowrap',
      }}
    >
      {label}
    </span>
  );
}

// ── 상태 코드 → 탭 카테고리 분류 ───────────────────────
function classifyStatus(code: string): 'active' | 'done' {
  const upper = code.toUpperCase();
  if (
    upper === 'COMPLETED' ||
    upper === 'RESOLVED' ||
    upper === 'CLOSED' ||
    upper === 'DONE'
  ) {
    return 'done';
  }
  return 'active';
}

// ── rsltData 에서 안전하게 값 추출 ──────────────────────
function rslt(data: Record<string, unknown> | null, key: string): string {
  if (!data) return '-';
  const val = data[key];
  if (val == null) return '-';
  return String(val);
}

// ── 모델 문자열 헬퍼 ────────────────────────────────────
function getPredModels(p: PredictionAnalysis): string {
  const models = [
    p.kospsStatus && p.kospsStatus !== 'pending' && p.kospsStatus !== 'none' ? 'KOSPS' : null,
    p.poseidonStatus && p.poseidonStatus !== 'pending' && p.poseidonStatus !== 'none'
      ? 'POSEIDON'
      : null,
    p.opendriftStatus && p.opendriftStatus !== 'pending' && p.opendriftStatus !== 'none'
      ? 'OpenDrift'
      : null,
  ]
    .filter(Boolean)
    .join('+');
  return models || '-';
}

// ── 날짜 포맷 ───────────────────────────────────────────
function fmtDate(dtm: string | null): string {
  if (!dtm) return '-';
  return dtm.slice(0, 16).replace('T', ' ');
}

/* ════════════════════════════════════════════════════
   AnalysisSelectModal
   ════════════════════════════════════════════════════ */
export function AnalysisSelectModal({
  type,
  isOpen,
  onClose,
  initialSelectedIds,
  onApply,
}: AnalysisSelectModalProps) {
  const [loading, setLoading] = useState(false);
  const [predItems, setPredItems] = useState<PredictionAnalysis[]>([]);
  const [hnsItems, setHnsItems] = useState<HnsAnalysisItem[]>([]);
  const [rescueItems, setRescueItems] = useState<RescueOpsItem[]>([]);
  const [checkedIds, setCheckedIds] = useState<Set<string>>(new Set(initialSelectedIds));
  const [statusTab, setStatusTab] = useState<StatusTab>('all');
  const [search, setSearch] = useState('');

  const backdropRef = useRef<HTMLDivElement>(null);

  // 모달 오픈 시 데이터 로드
  useEffect(() => {
    if (!isOpen) return;
    setCheckedIds(new Set(initialSelectedIds));
    setStatusTab('all');
    setSearch('');
    setLoading(true);

    const load = async () => {
      try {
        if (type === 'oil') {
          const items = await fetchPredictionAnalyses();
          setPredItems(items);
        } else if (type === 'hns') {
          const items = await fetchHnsAnalyses();
          setHnsItems(items);
        } else {
          const items = await fetchRescueOps();
          setRescueItems(items);
        }
      } catch {
        // 조용히 실패
      } finally {
        setLoading(false);
      }
    };
    void load();
  }, [isOpen, type]); // eslint-disable-line react-hooks/exhaustive-deps

  // Backdrop 클릭 닫기
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (e.target === backdropRef.current) onClose();
    };
    if (isOpen) document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const meta = MODAL_META[type];

  // ── 필터 적용 ──
  const filteredOil = predItems.filter((p) => {
    const statusCode = p.acdntSttsCd || '';
    const tabOk =
      statusTab === 'all' ||
      (statusTab === 'active' && classifyStatus(statusCode) === 'active') ||
      (statusTab === 'done' && classifyStatus(statusCode) === 'done');
    const searchOk =
      search === '' ||
      (p.acdntNm || '').toLowerCase().includes(search.toLowerCase()) ||
      (p.oilType || '').toLowerCase().includes(search.toLowerCase());
    return tabOk && searchOk;
  });

  const filteredHns = hnsItems.filter((h) => {
    const statusCode = h.execSttsCd || '';
    const tabOk =
      statusTab === 'all' ||
      (statusTab === 'active' && classifyStatus(statusCode) === 'active') ||
      (statusTab === 'done' && classifyStatus(statusCode) === 'done');
    const searchOk =
      search === '' ||
      (h.anlysNm || '').toLowerCase().includes(search.toLowerCase()) ||
      (h.sbstNm || '').toLowerCase().includes(search.toLowerCase());
    return tabOk && searchOk;
  });

  const filteredRescue = rescueItems.filter((r) => {
    const statusCode = r.sttsCd || '';
    const tabOk =
      statusTab === 'all' ||
      (statusTab === 'active' && classifyStatus(statusCode) === 'active') ||
      (statusTab === 'done' && classifyStatus(statusCode) === 'done');
    const searchOk =
      search === '' ||
      (r.vesselNm || '').toLowerCase().includes(search.toLowerCase()) ||
      (r.acdntTpCd || '').toLowerCase().includes(search.toLowerCase());
    return tabOk && searchOk;
  });

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

  const handleApply = () => {
    if (type === 'oil') {
      onApply({ type: 'oil', items: predItems.filter((p) => checkedIds.has(String(p.predRunSn ?? p.acdntSn))) });
    } else if (type === 'hns') {
      onApply({ type: 'hns', items: hnsItems.filter((h) => checkedIds.has(String(h.hnsAnlysSn))) });
    } else {
      onApply({ type: 'rescue', items: rescueItems.filter((r) => checkedIds.has(String(r.rescueOpsSn))) });
    }
  };

  const tabItems: { id: StatusTab; label: string }[] = [
    { id: 'all', label: '전체' },
    { id: 'active', label: '대응중' },
    { id: 'done', label: '완료' },
  ];

  // ── 테이블 헤더 스타일 ──
  const thStyle: React.CSSProperties = {
    padding: '8px 10px',
    textAlign: 'left',
    fontWeight: 600,
    color: 'var(--fg-disabled)',
    fontSize: '11px',
    whiteSpace: 'nowrap',
    borderBottom: '1px solid var(--stroke-default)',
    background: 'var(--bg-elevated)',
  };

  const tdStyle: React.CSSProperties = {
    padding: '8px 10px',
    fontSize: '12px',
    borderBottom: '1px solid var(--stroke-default)',
    whiteSpace: 'nowrap',
  };

  return (
    <div
      ref={backdropRef}
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 9999,
        background: 'rgba(0,0,0,0.55)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <div
        style={{
          width: 'min(900px, 95vw)',
          maxHeight: '82vh',
          display: 'flex',
          flexDirection: 'column',
          background: 'var(--bg-surface)',
          border: '1px solid var(--stroke-default)',
          borderRadius: '8px',
          overflow: 'hidden',
        }}
      >
        {/* ── Header ── */}
        <div
          style={{
            padding: '14px 16px 12px',
            borderBottom: '1px solid var(--stroke-default)',
            flexShrink: 0,
          }}
        >
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: '14px', fontWeight: 700, marginBottom: '3px' }}>
                {meta.icon} {meta.title}
              </div>
              <div style={{ fontSize: '12px', color: 'var(--fg-disabled)' }}>
                비교 분석 결과를 선택하세요 (다중 선택 가능)
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginTop: '2px' }}>
              <span style={{ fontSize: '12px', color: 'var(--fg-disabled)' }}>
                선택:{' '}
                <b style={{ color: meta.color }}>{checkedIds.size}건</b>
              </span>
              <button
                onClick={onClose}
                style={{
                  background: 'none',
                  border: 'none',
                  cursor: 'pointer',
                  color: 'var(--fg-disabled)',
                  fontSize: '16px',
                  lineHeight: 1,
                  padding: '2px',
                }}
              >
                ✕
              </button>
            </div>
          </div>
        </div>

        {/* ── Filter bar ── */}
        <div
          style={{
            padding: '10px 16px',
            borderBottom: '1px solid var(--stroke-default)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            flexShrink: 0,
            background: 'var(--bg-elevated)',
          }}
        >
          {/* Status tabs */}
          <div style={{ display: 'flex', gap: '4px' }}>
            {tabItems.map((tab) => {
              const isActive = statusTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setStatusTab(tab.id)}
                  style={{
                    padding: '4px 12px',
                    borderRadius: '4px',
                    fontSize: '12px',
                    fontWeight: isActive ? 700 : 500,
                    cursor: 'pointer',
                    border: isActive ? `1px solid ${meta.color}` : '1px solid var(--stroke-default)',
                    background: isActive ? `rgba(${type === 'rescue' ? '6,182,212' : '249,115,22'},0.1)` : 'var(--bg-surface)',
                    color: isActive ? meta.color : 'var(--fg-disabled)',
                  }}
                >
                  {tab.label}
                </button>
              );
            })}
          </div>

          {/* Search */}
          <input
            type="text"
            placeholder="검색..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            style={{
              padding: '5px 10px',
              borderRadius: '4px',
              border: '1px solid var(--stroke-default)',
              background: 'var(--bg-surface)',
              color: 'var(--fg)',
              fontSize: '12px',
              width: '180px',
              outline: 'none',
            }}
          />
        </div>

        {/* ── Table ── */}
        <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', scrollbarWidth: 'thin', scrollbarColor: 'var(--stroke-light) transparent' }}>
          {loading ? (
            <div style={{ padding: '32px', textAlign: 'center', color: 'var(--fg-disabled)', fontSize: '13px' }}>
              불러오는 중...
            </div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
              {type === 'oil' && (
                <>
                  <thead>
                    <tr>
                      <th style={{ ...thStyle, width: 36 }} />
                      <th style={{ ...thStyle, width: 64 }}>상태</th>
                      <th style={{ ...thStyle, width: 'auto' }}>분석명</th>
                      <th style={{ ...thStyle, width: 96 }}>유종</th>
                      <th style={{ ...thStyle, width: 70 }}>유출량</th>
                      <th style={{ ...thStyle, width: 160 }}>모델</th>
                      <th style={{ ...thStyle, width: 130 }}>일시</th>
                      <th style={{ ...thStyle, width: 72 }}>12h면적</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredOil.length === 0 ? (
                      <tr>
                        <td colSpan={8} style={{ ...tdStyle, textAlign: 'center', color: 'var(--fg-disabled)', padding: '24px' }}>
                          분석 결과가 없습니다
                        </td>
                      </tr>
                    ) : (
                      filteredOil.map((p) => {
                        const id = String(p.predRunSn ?? p.acdntSn);
                        const checked = checkedIds.has(id);
                        return (
                          <tr
                            key={id}
                            onClick={() => toggleId(id)}
                            style={{
                              cursor: 'pointer',
                              background: checked ? 'rgba(6,182,212,0.05)' : undefined,
                            }}
                            onMouseEnter={(e) => {
                              if (!checked) (e.currentTarget as HTMLTableRowElement).style.background = 'var(--bg-elevated)';
                            }}
                            onMouseLeave={(e) => {
                              (e.currentTarget as HTMLTableRowElement).style.background = checked ? 'rgba(6,182,212,0.05)' : '';
                            }}
                          >
                            <td style={{ ...tdStyle, textAlign: 'center' }}>
                              <input
                                type="checkbox"
                                checked={checked}
                                onChange={() => toggleId(id)}
                                onClick={(e) => e.stopPropagation()}
                                style={{ accentColor: meta.color, cursor: 'pointer' }}
                              />
                            </td>
                            <td style={tdStyle}>
                              <StatusBadge code={p.acdntSttsCd || 'active'} />
                            </td>
                            <td style={{ ...tdStyle, overflow: 'hidden', textOverflow: 'ellipsis', fontWeight: 600 }}>
                              {p.acdntNm || '-'}
                            </td>
                            <td style={{ ...tdStyle, color: 'var(--color-warning)', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis' }}>
                              {p.oilType || '-'}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)' }}>
                              {p.volume != null ? `${p.volume} kL` : '-'}
                            </td>
                            <td style={{ ...tdStyle, fontSize: '11px', color: 'var(--fg-muted)', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                              {getPredModels(p)}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: '11px' }}>
                              {fmtDate(p.runDtm || p.analysisDate)}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', color: 'var(--color-accent)' }}>
                              -
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </>
              )}

              {type === 'hns' && (
                <>
                  <thead>
                    <tr>
                      <th style={{ ...thStyle, width: 36 }} />
                      <th style={{ ...thStyle, width: 64 }}>상태</th>
                      <th style={{ ...thStyle, width: 'auto' }}>분석명</th>
                      <th style={{ ...thStyle, width: 100 }}>물질</th>
                      <th style={{ ...thStyle, width: 80 }}>최대농도</th>
                      <th style={{ ...thStyle, width: 120 }}>모델</th>
                      <th style={{ ...thStyle, width: 130 }}>일시</th>
                      <th style={{ ...thStyle, width: 64 }}>IDLH</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredHns.length === 0 ? (
                      <tr>
                        <td colSpan={8} style={{ ...tdStyle, textAlign: 'center', color: 'var(--fg-disabled)', padding: '24px' }}>
                          분석 결과가 없습니다
                        </td>
                      </tr>
                    ) : (
                      filteredHns.map((h) => {
                        const id = String(h.hnsAnlysSn);
                        const checked = checkedIds.has(id);
                        const maxConc = rslt(h.rsltData, 'maxConcentration');
                        const idlhDist = rslt(h.rsltData, 'idlhDistance');
                        return (
                          <tr
                            key={id}
                            onClick={() => toggleId(id)}
                            style={{
                              cursor: 'pointer',
                              background: checked ? 'rgba(6,182,212,0.05)' : undefined,
                            }}
                            onMouseEnter={(e) => {
                              if (!checked) (e.currentTarget as HTMLTableRowElement).style.background = 'var(--bg-elevated)';
                            }}
                            onMouseLeave={(e) => {
                              (e.currentTarget as HTMLTableRowElement).style.background = checked ? 'rgba(6,182,212,0.05)' : '';
                            }}
                          >
                            <td style={{ ...tdStyle, textAlign: 'center' }}>
                              <input
                                type="checkbox"
                                checked={checked}
                                onChange={() => toggleId(id)}
                                onClick={(e) => e.stopPropagation()}
                                style={{ accentColor: meta.color, cursor: 'pointer' }}
                              />
                            </td>
                            <td style={tdStyle}>
                              <StatusBadge code={h.execSttsCd || 'active'} />
                            </td>
                            <td style={{ ...tdStyle, maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', fontWeight: 600 }}>
                              {h.anlysNm || '-'}
                            </td>
                            <td style={{ ...tdStyle, color: 'var(--color-warning)', fontWeight: 600 }}>
                              {h.sbstNm || '-'}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', color: 'var(--color-accent)' }}>
                              {maxConc !== '-' ? `${maxConc} ppm` : '-'}
                            </td>
                            <td style={{ ...tdStyle, fontSize: '11px', color: 'var(--fg-muted)' }}>
                              {h.algoCd || '-'}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: '11px' }}>
                              {fmtDate(h.regDtm)}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', color: 'var(--color-accent)' }}>
                              {idlhDist !== '-' ? `${idlhDist} km` : '-'}
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </>
              )}

              {type === 'rescue' && (
                <>
                  <thead>
                    <tr>
                      <th style={{ ...thStyle, width: 36 }} />
                      <th style={{ ...thStyle, width: 64 }}>상태</th>
                      <th style={{ ...thStyle, width: 'auto' }}>선박명 / 사고</th>
                      <th style={{ ...thStyle, width: 100 }}>사고유형</th>
                      <th style={{ ...thStyle, width: 64 }}>GM</th>
                      <th style={{ ...thStyle, width: 64 }}>횡경사</th>
                      <th style={{ ...thStyle, width: 130 }}>일시</th>
                      <th style={{ ...thStyle, width: 56 }}>인명</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredRescue.length === 0 ? (
                      <tr>
                        <td colSpan={8} style={{ ...tdStyle, textAlign: 'center', color: 'var(--fg-disabled)', padding: '24px' }}>
                          분석 결과가 없습니다
                        </td>
                      </tr>
                    ) : (
                      filteredRescue.map((r) => {
                        const id = String(r.rescueOpsSn);
                        const checked = checkedIds.has(id);
                        const crew = r.totalCrew != null ? r.totalCrew : null;
                        const surv = r.survivors != null ? r.survivors : null;
                        const crewLabel =
                          surv != null && crew != null
                            ? `${surv}/${crew}`
                            : surv != null
                              ? String(surv)
                              : '-';
                        return (
                          <tr
                            key={id}
                            onClick={() => toggleId(id)}
                            style={{
                              cursor: 'pointer',
                              background: checked ? 'rgba(6,182,212,0.05)' : undefined,
                            }}
                            onMouseEnter={(e) => {
                              if (!checked) (e.currentTarget as HTMLTableRowElement).style.background = 'var(--bg-elevated)';
                            }}
                            onMouseLeave={(e) => {
                              (e.currentTarget as HTMLTableRowElement).style.background = checked ? 'rgba(6,182,212,0.05)' : '';
                            }}
                          >
                            <td style={{ ...tdStyle, textAlign: 'center' }}>
                              <input
                                type="checkbox"
                                checked={checked}
                                onChange={() => toggleId(id)}
                                onClick={(e) => e.stopPropagation()}
                                style={{ accentColor: meta.color, cursor: 'pointer' }}
                              />
                            </td>
                            <td style={tdStyle}>
                              <StatusBadge code={r.sttsCd || 'active'} />
                            </td>
                            <td style={{ ...tdStyle, fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis' }}>
                              {r.vesselNm || '-'}
                            </td>
                            <td style={{ ...tdStyle, fontSize: '11px' }}>
                              {r.acdntTpCd || '-'}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', color: 'var(--color-success)' }}>
                              {r.gmM != null ? `${r.gmM}m` : '-'}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', color: 'var(--color-warning)' }}>
                              {r.listDeg != null ? `${r.listDeg}°` : '-'}
                            </td>
                            <td style={{ ...tdStyle, fontFamily: 'var(--font-mono)', fontSize: '11px' }}>
                              {fmtDate(r.regDtm)}
                            </td>
                            <td style={{
                              ...tdStyle,
                              fontFamily: 'var(--font-mono)',
                              fontWeight: 600,
                              color: r.missing != null && r.missing > 0 ? 'var(--color-danger)' : 'var(--color-success)',
                            }}>
                              {crewLabel}
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </>
              )}
            </table>
          )}
        </div>

        {/* ── Footer ── */}
        <div
          style={{
            padding: '12px 16px',
            borderTop: '1px solid var(--stroke-default)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            flexShrink: 0,
            background: 'var(--bg-elevated)',
          }}
        >
          <span style={{ fontSize: '12px', color: 'var(--fg-disabled)' }}>
            선택한 분석 결과가 오른쪽 패널에 반영됩니다
          </span>
          <div style={{ display: 'flex', gap: '8px' }}>
            <button
              onClick={onClose}
              style={{
                padding: '6px 16px',
                borderRadius: '4px',
                border: '1px solid var(--stroke-default)',
                background: 'var(--bg-surface)',
                color: 'var(--fg-disabled)',
                fontSize: '13px',
                fontWeight: 600,
                cursor: 'pointer',
              }}
            >
              취소
            </button>
            <button
              onClick={handleApply}
              style={{
                padding: '6px 18px',
                borderRadius: '4px',
                border: `1px solid ${meta.color}`,
                background: `rgba(${type === 'rescue' ? '6,182,212' : '249,115,22'},0.15)`,
                color: meta.color,
                fontSize: '13px',
                fontWeight: 700,
                cursor: 'pointer',
              }}
            >
              ✓ 선택 적용
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
