/**
 * 선박 범례 컴포넌트
 * - 선박 종류별 아이콘 및 카운트 표시
 * - 선박 표시 On/Off 토글
 * - 선박 종류별 필터 토글
 */
import { memo } from 'react';
import { shallow } from 'zustand/shallow';
import useShipStore from '../../stores/shipStore';
import {
  SIGNAL_KIND_CODE_FISHING,
  SIGNAL_KIND_CODE_KCGV,
  SIGNAL_KIND_CODE_PASSENGER,
  SIGNAL_KIND_CODE_CARGO,
  SIGNAL_KIND_CODE_TANKER,
  SIGNAL_KIND_CODE_GOV,
  SIGNAL_KIND_CODE_NORMAL,
  SIGNAL_KIND_CODE_BUOY,
} from '../../types/constants';
import './ShipLegend.scss';

// 선박 종류별 SVG 아이콘
import fishingIcon from '../../assets/img/shipKindIcons/fishing.svg';
import passIcon from '../../assets/img/shipKindIcons/pass.svg';
import cargoIcon from '../../assets/img/shipKindIcons/cargo.svg';
import hazardIcon from '../../assets/img/shipKindIcons/hazard.svg';
import govIcon from '../../assets/img/shipKindIcons/gov.svg';
import kcgvIcon from '../../assets/img/shipKindIcons/kcgv.svg';
import bouyIcon from '../../assets/img/shipKindIcons/bouy.svg';
import etcIcon from '../../assets/img/shipKindIcons/etc.svg';

/**
 * 선박 종류 코드 → 아이콘 매핑
 */
const SHIP_KIND_ICONS = {
  [SIGNAL_KIND_CODE_FISHING]: fishingIcon,
  [SIGNAL_KIND_CODE_KCGV]: kcgvIcon,
  [SIGNAL_KIND_CODE_PASSENGER]: passIcon,
  [SIGNAL_KIND_CODE_CARGO]: cargoIcon,
  [SIGNAL_KIND_CODE_TANKER]: hazardIcon,
  [SIGNAL_KIND_CODE_GOV]: govIcon,
  [SIGNAL_KIND_CODE_NORMAL]: etcIcon,
  [SIGNAL_KIND_CODE_BUOY]: bouyIcon,
};

/**
 * 범례 항목 설정
 */
const LEGEND_ITEMS = [
  { code: SIGNAL_KIND_CODE_FISHING, label: '어선' },
  { code: SIGNAL_KIND_CODE_PASSENGER, label: '여객선' },
  { code: SIGNAL_KIND_CODE_CARGO, label: '화물선' },
  { code: SIGNAL_KIND_CODE_TANKER, label: '유조선' },
  { code: SIGNAL_KIND_CODE_GOV, label: '관공선' },
  { code: SIGNAL_KIND_CODE_KCGV, label: '경비함정' },
  { code: SIGNAL_KIND_CODE_BUOY, label: '어망/부이' },
  { code: SIGNAL_KIND_CODE_NORMAL, label: '기타' },
];

/**
 * 선박 범례 항목
 */
const LegendItem = memo(({ code, label, count, icon, isVisible, onToggle }) => {
  // 부이는 회전하지 않음
  const isBuoy = code === SIGNAL_KIND_CODE_BUOY;

  return (
    <li className={`legend-item ${!isVisible ? 'disabled' : ''}`}>
      <div className="legend-info" onClick={() => onToggle(code)}>
        <span className="legend-icon">
          <img
            src={icon}
            alt={label}
            style={{ transform: isBuoy ? 'rotate(0deg)' : 'rotate(45deg)' }}
          />
        </span>
        <span className="legend-label">{label}</span>
      </div>
      <span className="legend-count">{count}</span>
    </li>
  );
});

/**
 * 선박 범례 컴포넌트
 */
const ShipLegend = memo(() => {
  // 셀렉터 사용: 구독 중인 값이 실제로 바뀔 때만 리렌더
  // useShipStore() 전체 구독 → featuresVersion 변경마다 리렌더되는 문제 방지
  const { kindCounts, kindVisibility, isShipVisible, totalCount, isConnected } =
    useShipStore(
      (state) => ({
        kindCounts: state.kindCounts,
        kindVisibility: state.kindVisibility,
        isShipVisible: state.isShipVisible,
        totalCount: state.totalCount,
        isConnected: state.isConnected,
      }),
      shallow
    );
  const toggleKindVisibility = useShipStore((state) => state.toggleKindVisibility);
  const toggleShipVisible = useShipStore((state) => state.toggleShipVisible);

  return (
    <article className="ship-legend">
      {/* 헤더 - 전체 On/Off */}
      <div className="legend-header">
        <div className="legend-title">
          <span className={`connection-status ${isConnected ? 'connected' : ''}`} />
          <span>선박 현황</span>
        </div>
        <label className="toggle-switch">
          <input
            type="checkbox"
            checked={isShipVisible}
            onChange={toggleShipVisible}
          />
          <span className="slider" />
        </label>
      </div>

      {/* 선박 종류별 목록 */}
      <ul className="legend-list">
        {LEGEND_ITEMS.map((item) => (
          <LegendItem
            key={item.code}
            code={item.code}
            label={item.label}
            count={kindCounts[item.code] || 0}
            icon={SHIP_KIND_ICONS[item.code]}
            isVisible={kindVisibility[item.code]}
            onToggle={toggleKindVisibility}
          />
        ))}
      </ul>

      {/* 푸터 - 전체 카운트 */}
      <div className="legend-footer">
        <span>전체</span>
        <span className="total-count">{totalCount}</span>
      </div>
    </article>
  );
});

export default ShipLegend;
