/**
 * GIS 모니터링 메인 애플리케이션
 */

import { GISMapController } from '../components/gis-map-controller.js';
import { GISVesselManager } from '../components/gis-vessel-manager.js';
import { GISSequentialManager } from '../components/gis-sequential-manager.js';
import { HaeguAPI, AreaAPI, TrackAPI, APIHelper } from '../api/gis-api.js';
import { 
    processVesselTracks, 
    mergeTrackPoints, 
    extractLatestPositions,
    formatDistance,
    formatSpeed,
    parseVesselId
} from '../utils/gis-utils.js';

class GISMonitoringApp {
    constructor() {
        this.mapController = new GISMapController('mapContainer');
        this.vesselManager = new GISVesselManager();
        this.sequentialManager = new GISSequentialManager();
        
        this.dataCache = {
            haegus: [],
            areas: [],
            haeguStats: {},
            areaStats: {},
            currentArea: null
        };
        
        this.isLoading = false;
        this.autoRefreshTimer = null;
        this.contextMenuTarget = null;
    }

    /**
     * 애플리케이션 초기화
     */
    async init() {
        try {
            // 지도 초기화
            await this.mapController.init();
            
            // 이벤트 핸들러 설정
            this.setupEventHandlers();
            
            // 초기 날짜 설정
            this.initDateTime();
            
            // 초기 데이터 로드
            await this.refreshData();
            
            // 자동 새로고침 시작 (5분마다)
            this.startAutoRefresh();
            
            console.log('GIS Monitoring App initialized successfully');
        } catch (error) {
            console.error('Failed to initialize GIS app:', error);
            this.showError('애플리케이션 초기화 실패');
        }
    }

    /**
     * 이벤트 핸들러 설정
     */
    setupEventHandlers() {
        // 지도 이벤트
        this.mapController.setEventHandlers({
            onAreaClick: (type, properties) => this.handleAreaClick(type, properties),
            onContextMenu: (type, properties, event) => this.showContextMenu(type, properties, event)
        });
        
        this.mapController.setupContextMenu();
        
        // 선박 관리자 이벤트
        this.vesselManager.setEventHandlers({
            onSelectionChange: (selected) => this.handleVesselSelectionChange(selected)
        });
        
        // Sequential 관리자 이벤트
        this.sequentialManager.setEventHandlers({
            onZonesChange: (zones) => this.handleZonesChange(zones)
        });
        
        // UI 이벤트
        this.setupUIEventHandlers();
    }

    /**
     * UI 이벤트 핸들러 설정
     */
    setupUIEventHandlers() {
        // 패널 토글
        $('#panelToggle').on('click', () => this.toggleControlPanel());
        
        // 새로고침
        $('#refreshBtn').on('click', () => this.refreshData());
        
        // 레이어 타입 변경
        $('#gisLayerType').on('change', () => this.refreshData());
        
        // Sequential 패널
        $('#sequentialBtn').on('click', () => this.toggleSequentialPanel());
        $('#closeSequentialBtn').on('click', () => this.toggleSequentialPanel());
        
        // 트랙 정보 패널
        $('#closeTrackPanelBtn').on('click', () => this.hideTrackPanel());
        
        // 선박 목록
        $('#hideVesselListBtn').on('click', () => this.toggleVesselList());
        $('#selectAllBtn').on('click', () => this.selectAllVessels());
        $('#deselectAllBtn').on('click', () => this.deselectAllVessels());
        $('#showTracksBtn').on('click', () => this.showSelectedTracks());
        
        // 정렬
        $('#sortBy, #sortOrder').on('change', () => this.updateVesselList());
        
        // 지도 토글
        $('#showTracks').on('change', () => this.toggleTracks());
        $('#showAllTracks').on('change', () => this.toggleAllTracks());
        $('#showHeatmap').on('change', () => this.toggleHeatmap());
        
        // 필터
        $('#applyFiltersBtn').on('click', () => this.applyFilters());
        $('#resetFiltersBtn').on('click', () => this.resetFilters());
        
        // Sequential Passage
        $('#addZoneBtn').on('click', () => this.addZone());
        $('#searchPassageBtn').on('click', () => this.searchSequentialPassage());
        $('#passageMode').on('change', () => this.handlePassageModeChange());
        
        // 구역 입력 엔터키
        $('#zoneInput').on('keypress', (e) => {
            if (e.key === 'Enter') this.addZone();
        });
        
        // 컨텍스트 메뉴
        $('#addToSequential').on('click', () => this.addToSequentialFromContext());
        $('#viewAreaDetails').on('click', () => this.viewAreaDetailsFromContext());
        $('#showAreaTracks').on('click', () => this.showAreaTracksFromContext());
        
        // 컨텍스트 메뉴 숨기기
        $(document).on('click', () => $('#contextMenu').hide());
        
        // 동적 이벤트 위임
        this.setupDynamicEventHandlers();
    }

    /**
     * 동적 생성 요소 이벤트 핸들러
     */
    setupDynamicEventHandlers() {
        // 선박 체크박스
        $(document).on('change', '.vessel-checkbox', (e) => {
            e.stopPropagation();
            const vesselId = $(e.target).data('vessel-id');
            const isChecked = this.vesselManager.toggleSelection(vesselId);
            $(e.target).closest('.vessel-item').toggleClass('selected', isChecked);
        });
        
        // 선박 아이템 클릭
        $(document).on('click', '.vessel-item', (e) => {
            if (!$(e.target).is('.vessel-checkbox')) {
                const checkbox = $(e.currentTarget).find('.vessel-checkbox');
                checkbox.prop('checked', !checkbox.prop('checked')).trigger('change');
            }
        });
        
        // Sequential 결과 선택
        $(document).on('click', '#sequentialResults .vessel-item', (e) => {
            const vesselId = $(e.currentTarget).data('vessel-id');
            this.selectSequentialVessel(vesselId);
        });
        
        // 구역 제거
        $(document).on('click', '.remove-zone', (e) => {
            const index = $(e.currentTarget).data('index');
            this.sequentialManager.removeZone(index);
            this.updateSelectedZones();
        });
    }

    /**
     * 초기 날짜 설정
     */
    initDateTime() {
        const now = new Date();
        const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        
        $('#passageStartTime').val(yesterday.toISOString().slice(0, 16));
        $('#passageEndTime').val(now.toISOString().slice(0, 16));
    }

    /**
     * 데이터 새로고침
     */
    async refreshData() {
        if (this.isLoading) return;
        
        this.showLoading(true);
        
        try {
            const timeRange = $('#gisTimeRange').val();
            const layerType = $('#gisLayerType').val();
            
            // 병렬 데이터 로딩
            const promises = [];
            
            if (layerType === 'haegu' || layerType === 'both') {
                promises.push(this.loadHaeguData(timeRange));
            }
            
            if (layerType === 'area' || layerType === 'both') {
                promises.push(this.loadAreaData(timeRange));
            }
            
            await Promise.all(promises);
            
            // 레이어 업데이트
            this.updateMapLayers();
            
        } catch (error) {
            console.error('Failed to refresh data:', error);
            this.showError('데이터 로드 실패');
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * Haegu 데이터 로드
     */
    async loadHaeguData(timeRange) {
        const [boundaries, stats] = await APIHelper.parallel([
            HaeguAPI.getBoundaries(),
            HaeguAPI.getVesselStats(timeRange)
        ]);
        
        this.dataCache.haegus = boundaries;
        this.dataCache.haeguStats = stats;
        
        this.mapController.updateHaeguLayer(boundaries, stats);
    }

    /**
     * Area 데이터 로드
     */
    async loadAreaData(timeRange) {
        const [boundaries, stats] = await APIHelper.parallel([
            AreaAPI.getBoundaries(),
            AreaAPI.getVesselStats(timeRange)
        ]);
        
        this.dataCache.areas = boundaries;
        this.dataCache.areaStats = stats;
        
        this.mapController.updateAreaLayer(boundaries, stats);
    }

    /**
     * 레이어 업데이트
     */
    updateMapLayers() {
        const layerType = $('#gisLayerType').val();
        
        if (layerType === 'haegu') {
            this.mapController.removeLayer('area-layer');
        } else if (layerType === 'area') {
            this.mapController.removeLayer('haegu-layer');
        }
    }

    /**
     * 구역 클릭 처리
     */
    handleAreaClick(type, properties) {
        this.showAreaDetails(type, properties);
    }

    /**
     * 구역 상세 정보 표시
     */
    showAreaDetails(type, properties) {
        this.dataCache.currentArea = { type, properties };
        
        const areaName = type === 'haegu' ? 
            `Haegu ${properties.haegu_no}` : 
            (properties.area_name || properties.area_id);
        
        $('#trackPanelTitle').text(areaName);
        $('#trackPanelContent').html(this.generateAreaDetailsHTML(type, properties));
        $('#trackInfoPanel').show();
    }

    /**
     * 구역 상세 정보 HTML 생성
     */
    generateAreaDetailsHTML(type, properties) {
        const id = type === 'haegu' ? properties.haegu_no : properties.area_id;
        
        return `
            <div class="mb-3">
                <p><strong>활성 선박:</strong> ${properties.vessel_count || 0}척</p>
                <p><strong>총 이동거리:</strong> ${formatDistance(properties.total_distance)}</p>
            </div>
            <div class="d-grid gap-2">
                <button class="btn btn-primary btn-sm" onclick="GISApp.showVesselList('${type}', '${id}')">
                    <i class="bi bi-list"></i> 선박 목록 보기
                </button>
                <button class="btn btn-success btn-sm" onclick="GISApp.showVesselPositions('${type}', '${id}')">
                    <i class="bi bi-geo-fill"></i> 현재 위치 표시
                </button>
                <button class="btn btn-warning btn-sm" onclick="GISApp.showAreaAllTracks('${type}', '${id}')">
                    <i class="bi bi-map"></i> 구역 내 모든 트랙
                </button>
            </div>
        `;
    }

    /**
     * 선박 목록 표시
     */
    async showVesselList(type, id) {
        const timeRange = $('#gisTimeRange').val();
        $('#vesselListTitle').text(`${type === 'haegu' ? 'Haegu ' + id : 'Area ' + id} 선박 목록`);
        
        this.toggleVesselList(true);
        this.showLoading(true);
        
        try {
            await this.vesselManager.loadVesselList(type, id, timeRange);
            this.updateVesselList();
        } catch (error) {
            console.error('Failed to load vessel list:', error);
            $('#vesselListContent').html('<div class="text-danger">선박 목록 로드 실패</div>');
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * 선박 위치 표시
     */
    async showVesselPositions(type, id) {
        this.showLoading(true);
        
        try {
            const timeRange = $('#gisTimeRange').val();
            const tracks = await TrackAPI.getByArea(type, id, timeRange);
            const positions = extractLatestPositions(tracks);
            
            this.mapController.updatePositionLayer(positions);
            
            if (positions.length > 0) {
                this.mapController.fitBounds(positions.map(p => p.position));
            }
        } catch (error) {
            console.error('Failed to load vessel positions:', error);
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * 구역 내 모든 트랙 표시
     */
    async showAreaAllTracks(type, id) {
        this.showLoading(true);
        
        try {
            const period = $('#trackPeriod').val();
            const tracks = await TrackAPI.getByArea(type, id, period);
            
            const vesselTracks = processVesselTracks(tracks);
            const processedTracks = [];
            
            Object.values(vesselTracks).forEach(vessel => {
                const allPoints = mergeTrackPoints(vessel.tracks);
                
                if (allPoints.length > 0) {
                    processedTracks.push({
                        path: allPoints,
                        vessel_id: vessel.vessel_id,
                        distance: vessel.total_distance,
                        avg_speed: vessel.avg_speed,
                        selected: false
                    });
                }
            });
            
            $('#showTracks').prop('checked', true);
            this.mapController.updateTrackLayer(processedTracks);
            
            if (processedTracks.length > 0) {
                const allPoints = processedTracks.flatMap(t => t.path);
                this.mapController.fitBounds(allPoints);
            }
            
            this.hideTrackPanel();
            
        } catch (error) {
            console.error('Failed to load area tracks:', error);
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * 선박 목록 업데이트
     */
    updateVesselList() {
        const sortBy = $('#sortBy').val();
        const sortOrder = $('#sortOrder').val();
        
        this.vesselManager.setSort(sortBy, sortOrder);
        const html = this.vesselManager.renderVesselList();
        $('#vesselListContent').html(html);
        
        this.updateSelectedCount();
    }

    /**
     * 선택 카운트 업데이트
     */
    updateSelectedCount() {
        const count = this.vesselManager.getSelectedCount();
        const $count = $('#selectedCount');
        
        if (count > 0) {
            $count.text(count).show();
        } else {
            $count.hide();
        }
    }

    /**
     * 선박 선택 변경 처리
     */
    handleVesselSelectionChange(selected) {
        this.updateSelectedCount();
    }

    /**
     * 전체 선박 선택
     */
    selectAllVessels() {
        this.vesselManager.selectAll();
        this.updateVesselList();
    }

    /**
     * 전체 선박 선택 해제
     */
    deselectAllVessels() {
        this.vesselManager.deselectAll();
        this.updateVesselList();
    }

    /**
     * 선택된 선박 트랙 표시
     */
    async showSelectedTracks() {
        const selected = this.vesselManager.getSelectedVessels();
        
        if (selected.size === 0) {
            alert('선박을 선택하세요');
            return;
        }
        
        this.showLoading(true);
        
        try {
            const period = $('#trackPeriod').val();
            const tracks = await this.vesselManager.loadSelectedTracks(period);
            
            $('#showTracks').prop('checked', true);
            this.mapController.updateTrackLayer(tracks);
            
            if (tracks.length > 0) {
                const allPoints = tracks.flatMap(t => t.path);
                this.mapController.fitBounds(allPoints);
            }
            
            this.toggleVesselList(false);
            
        } catch (error) {
            console.error('Failed to load selected tracks:', error);
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * 트랙 토글
     */
    toggleTracks() {
        const show = $('#showTracks').is(':checked');
        
        if (!show) {
            this.mapController.removeLayer('track-layer');
            this.vesselManager.clearSelection();
        }
    }

    /**
     * 전체 트랙 토글
     */
    async toggleAllTracks() {
        const show = $('#showAllTracks').is(':checked');
        
        if (show) {
            await this.loadAllTracks();
        } else {
            this.mapController.removeLayer('all-tracks-layer');
        }
    }

    /**
     * 전체 트랙 로드
     */
    async loadAllTracks() {
        this.showLoading(true);
        
        try {
            const timeRange = $('#trackPeriod').val();
            const layerType = $('#gisLayerType').val();
            const allTracks = [];
            
            const loadPromises = [];
            
            if (layerType === 'haegu' || layerType === 'both') {
                Object.entries(this.dataCache.haeguStats).forEach(([haeguNo, stats]) => {
                    if (stats.vessel_count > 0) {
                        loadPromises.push(
                            HaeguAPI.getTracks(haeguNo, timeRange)
                                .then(tracks => allTracks.push(...tracks))
                        );
                    }
                });
            }
            
            if (layerType === 'area' || layerType === 'both') {
                Object.entries(this.dataCache.areaStats).forEach(([areaId, stats]) => {
                    if (stats.vessel_count > 0) {
                        loadPromises.push(
                            AreaAPI.getTracks(areaId, timeRange)
                                .then(tracks => allTracks.push(...tracks))
                        );
                    }
                });
            }
            
            await Promise.all(loadPromises);
            
            const vesselTracks = processVesselTracks(allTracks);
            const processedTracks = [];
            
            Object.values(vesselTracks).forEach(vessel => {
                const allPoints = mergeTrackPoints(vessel.tracks);
                
                if (allPoints.length > 0) {
                    processedTracks.push({
                        path: allPoints,
                        vessel_id: vessel.vessel_id,
                        distance: vessel.total_distance,
                        avg_speed: vessel.avg_speed,
                        selected: false
                    });
                }
            });
            
            this.mapController.updateTrackLayer(processedTracks, 'all-tracks-layer');
            
        } catch (error) {
            console.error('Failed to load all tracks:', error);
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * 히트맵 토글
     */
    toggleHeatmap() {
        const show = $('#showHeatmap').is(':checked');
        
        if (show) {
            // 히트맵 기능 구현 예정
            alert('히트맵 기능은 준비 중입니다');
            $('#showHeatmap').prop('checked', false);
        }
    }

    /**
     * 필터 적용
     */
    applyFilters() {
        const filters = {
            minSpeed: parseFloat($('#minSpeedFilter').val()) || 0,
            maxSpeed: parseFloat($('#maxSpeedFilter').val()) || 50,
            minDist: parseFloat($('#minDistFilter').val()) || 0,
            maxDist: parseFloat($('#maxDistFilter').val()) || 200
        };
        
        this.vesselManager.setFilters(filters);
        this.updateVesselList();
    }

    /**
     * 필터 초기화
     */
    resetFilters() {
        $('#minSpeedFilter').val(0);
        $('#maxSpeedFilter').val(50);
        $('#minDistFilter').val(0);
        $('#maxDistFilter').val(200);
        
        this.vesselManager.resetFilters();
        this.updateVesselList();
    }

    /**
     * Sequential Passage 패널 토글
     */
    toggleSequentialPanel() {
        $('#sequentialPanel').toggle();
        
        if ($('#sequentialPanel').is(':visible')) {
            this.updateSelectedZones();
        }
    }

    /**
     * 구역 추가
     */
    addZone() {
        const zoneId = $('#zoneInput').val().trim();
        
        if (!zoneId) {
            alert('구역 ID를 입력하세요');
            return;
        }
        
        const result = this.sequentialManager.addZone(zoneId);
        
        if (result.success) {
            $('#zoneInput').val('');
            this.updateSelectedZones();
        } else {
            alert(result.message);
        }
    }

    /**
     * 선택된 구역 업데이트
     */
    updateSelectedZones() {
        const html = this.sequentialManager.renderZones();
        $('#selectedZones').html(html);
        
        const zones = this.sequentialManager.getZones();
        const $selector = $('#zoneSelector');
        
        if (zones.length > 0) {
            $selector.addClass('has-zones');
        } else {
            $selector.removeClass('has-zones');
        }
    }

    /**
     * 구역 변경 처리
     */
    handleZonesChange(zones) {
        this.updateSelectedZones();
    }

    /**
     * 통과 모드 변경 처리
     */
    handlePassageModeChange() {
        const mode = $('#passageMode').val();
        this.sequentialManager.setMode(mode);
        
        if (mode === 'sequential') {
            this.sequentialManager.setMaxZones(3);
        } else {
            this.sequentialManager.setMaxZones(10);
        }
    }

    /**
     * Sequential Passage 검색
     */
    async searchSequentialPassage() {
        const mode = $('#passageMode').val();
        const type = $('#passageZoneType').val();
        const startTime = $('#passageStartTime').val();
        const endTime = $('#passageEndTime').val();
        
        const validation = this.sequentialManager.validateSearchParams(startTime, endTime);
        
        if (!validation.valid) {
            alert(validation.errors.join('\n'));
            return;
        }
        
        this.showLoading(true);
        
        try {
            await this.sequentialManager.search(mode, type, startTime, endTime);
            const html = this.sequentialManager.renderResults();
            $('#sequentialResults').html(html);
        } catch (error) {
            console.error('Sequential passage search failed:', error);
            alert('검색 실패: ' + error.message);
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * Sequential 선박 선택
     */
    async selectSequentialVessel(vesselId) {
        const { sigSrcCd, targetId } = parseVesselId(vesselId);
        const startTime = $('#passageStartTime').val();
        const endTime = $('#passageEndTime').val();
        
        this.showLoading(true);
        
        try {
            const response = await TrackAPI.getVesselTracks({
                startTime: APIHelper.formatTimestamp(startTime),
                endTime: APIHelper.formatTimestamp(endTime),
                vessels: [{ sigSrcCd, targetId }]
            });
            
            if (response && response.length > 0) {
                const vesselTrack = response[0];
                
                const trackData = [{
                    path: vesselTrack.geometry,
                    vessel_id: vesselTrack.vesselId,
                    distance: vesselTrack.totalDistance,
                    avg_speed: vesselTrack.avgSpeed,
                    max_speed: vesselTrack.maxSpeed,
                    selected: true
                }];
                
                $('#showTracks').prop('checked', true);
                this.mapController.updateTrackLayer(trackData);
                
                if (vesselTrack.geometry.length > 0) {
                    this.mapController.fitBounds(vesselTrack.geometry);
                }
                
                // 선택 표시
                $('#sequentialResults .vessel-item').removeClass('selected');
                $(`#sequentialResults .vessel-item[data-vessel-id="${vesselId}"]`).addClass('selected');
            } else {
                alert('해당 기간에 트랙이 없습니다');
            }
        } catch (error) {
            console.error('Failed to load vessel track:', error);
            alert('트랙 로드 실패');
        } finally {
            this.showLoading(false);
        }
    }

    /**
     * 컨텍스트 메뉴 표시
     */
    showContextMenu(type, properties, event) {
        this.contextMenuTarget = { type, properties };
        
        const $menu = $('#contextMenu');
        const $addItem = $('#addToSequential');
        
        // Sequential 추가 가능 여부 확인
        const zoneId = type === 'haegu' ? 
            properties.haegu_no.toString() : 
            properties.area_id;
        
        if (!this.sequentialManager.canAddZone()) {
            $addItem.addClass('disabled').html('<i class="bi bi-x-circle"></i> 최대 구역 도달');
        } else if (this.sequentialManager.hasZone(zoneId)) {
            $addItem.addClass('disabled').html('<i class="bi bi-check-circle"></i> 이미 추가됨');
        } else {
            $addItem.removeClass('disabled').html('<i class="bi bi-plus-circle"></i> Sequential에 추가');
        }
        
        // 메뉴 위치 설정
        $menu.css({
            left: event.clientX + 'px',
            top: event.clientY + 'px',
            display: 'block'
        });
    }

    /**
     * 컨텍스트 메뉴: Sequential에 추가
     */
    addToSequentialFromContext() {
        if (!this.contextMenuTarget || $('#addToSequential').hasClass('disabled')) return;
        
        const { type, properties } = this.contextMenuTarget;
        const zoneId = type === 'haegu' ? 
            properties.haegu_no.toString() : 
            properties.area_id;
        
        const result = this.sequentialManager.addZone(zoneId);
        
        if (result.success) {
            // Sequential 패널 표시
            if (!$('#sequentialPanel').is(':visible')) {
                $('#sequentialPanel').show();
            }
            
            // 구역 타입 설정
            $('#passageZoneType').val(type === 'haegu' ? 'GRID' : 'AREA');
            
            this.updateSelectedZones();
        }
        
        $('#contextMenu').hide();
    }

    /**
     * 컨텍스트 메뉴: 상세 정보 보기
     */
    viewAreaDetailsFromContext() {
        if (!this.contextMenuTarget) return;
        
        const { type, properties } = this.contextMenuTarget;
        this.showAreaDetails(type, properties);
        $('#contextMenu').hide();
    }

    /**
     * 컨텍스트 메뉴: 구역 트랙 표시
     */
    showAreaTracksFromContext() {
        if (!this.contextMenuTarget) return;
        
        const { type, properties } = this.contextMenuTarget;
        const id = type === 'haegu' ? properties.haegu_no : properties.area_id;
        
        this.showAreaAllTracks(type, id);
        $('#contextMenu').hide();
    }

    /**
     * 패널 토글
     */
    toggleControlPanel() {
        const $panel = $('#controlPanel');
        const $icon = $('#panelToggle i');
        
        $panel.toggleClass('collapsed');
        
        if ($panel.hasClass('collapsed')) {
            $icon.removeClass('bi-chevron-left').addClass('bi-chevron-right');
        } else {
            $icon.removeClass('bi-chevron-right').addClass('bi-chevron-left');
        }
    }

    /**
     * 선박 목록 토글
     */
    toggleVesselList(show) {
        const $section = $('#vesselListSection');
        
        if (show === undefined) {
            $section.toggleClass('expanded');
        } else {
            $section.toggleClass('expanded', show);
        }
    }

    /**
     * 트랙 패널 숨기기
     */
    hideTrackPanel() {
        $('#trackInfoPanel').hide();
    }

    /**
     * 로딩 표시
     */
    showLoading(show) {
        this.isLoading = show;
        $('#loadingOverlay').css('display', show ? 'flex' : 'none');
    }

    /**
     * 에러 표시
     */
    showError(message) {
        console.error(message);
        // Toast 또는 Alert 구현 가능
    }

    /**
     * 자동 새로고침 시작
     */
    startAutoRefresh() {
        this.stopAutoRefresh();
        
        this.autoRefreshTimer = setInterval(() => {
            if (!this.isLoading) {
                this.refreshData();
            }
        }, 5 * 60 * 1000); // 5분
    }

    /**
     * 자동 새로고침 중지
     */
    stopAutoRefresh() {
        if (this.autoRefreshTimer) {
            clearInterval(this.autoRefreshTimer);
            this.autoRefreshTimer = null;
        }
    }

    /**
     * 정리
     */
    destroy() {
        this.stopAutoRefresh();
        $(document).off();
    }
}

// 전역 인스턴스 생성
let GISApp;

// DOM 준비 완료 시 실행
$(document).ready(() => {
    GISApp = new GISMonitoringApp();
    GISApp.init().catch(error => {
        console.error('Failed to start GIS Monitoring App:', error);
    });
    
    // 전역 함수 노출 (레거시 호환성)
    window.GISApp = {
        showVesselList: (type, id) => GISApp.showVesselList(type, id),
        showVesselPositions: (type, id) => GISApp.showVesselPositions(type, id),
        showAreaAllTracks: (type, id) => GISApp.showAreaAllTracks(type, id)
    };
});