import store from './store.js';
import UIRenderer from './renderers/renderer.js';
import { showNotification, randomMeetingId } from '../shared/utils.js';
import chatMessage from './chat/chatmessage.js';
import { createCallViewController } from './controllers/call-view-controller.js';
import {
    bindConnectViewEvents,
    initWebSocket,
    loadUserSettings
} from './connectview.js';
import { createInviteController } from './controllers/invite-controller.js';
import { createLogger } from '../shared/logger.js';

const logger = createLogger('main');

let connectionId = '';
let currentView = 'connect';

function updateConnectionId(nextConnectionId) {
    connectionId = nextConnectionId || '';

    if (connectionId) {
        localStorage.setItem('connectionId', connectionId);
    }
}

async function switchToCallView(targetConnectionId) {
    const connectView = document.getElementById('connectView');
    const callView = document.getElementById('callView');

    if (connectView) {
        connectView.classList.add('hidden');
    }
    if (callView) {
        callView.classList.remove('hidden');
    }

    currentView = 'call';

    try {
        const renderer = new UIRenderer(store);

        await store.joinCall(targetConnectionId);
        await store.setUp(targetConnectionId);

        renderer.renderHeaderTitle();
        callViewController.bindDomEvents();

        logger.debug('Video call app initialized successfully');
        return true;
    } catch (error) {
        logger.error('Error initializing app:', error);
        showNotification('初始化失败，请刷新页面重试', 'error');
        return false;
    }
}

const inviteController = createInviteController({
    store,
    notify: showNotification,
    onAcceptConnection: switchToCallView,
    getCurrentView: () => currentView,
    getConnectionId: () => connectionId,
    setConnectionId: updateConnectionId
});

const callViewController = createCallViewController({
    store,
    chatMessage,
    notify: showNotification
});

async function handleJoinCall(targetConnectionId) {
    showNotification(`正在加入通话 (${targetConnectionId})`);
    updateConnectionId(targetConnectionId);
    await switchToCallView(targetConnectionId);
}

async function handleCreateCall() {
    showNotification('正在创建通话...');

    const nextConnectionId = randomMeetingId();
    updateConnectionId(nextConnectionId);
    await switchToCallView(nextConnectionId);
}

window.addEventListener('DOMContentLoaded', async () => {
    try {
        const connectView = document.getElementById('connectView');
        const callView = document.getElementById('callView');

        if (connectView) {
            connectView.classList.remove('hidden');
        }
        if (callView) {
            callView.classList.add('hidden');
        }

        currentView = 'connect';

        loadUserSettings();

        await initWebSocket();
        inviteController.bindSignalHandlers();
        inviteController.bindDialogEvents();
        bindConnectViewEvents(handleJoinCall, handleCreateCall);

        const savedConnectionId = localStorage.getItem('connectionId');
        if (savedConnectionId) {
            updateConnectionId(savedConnectionId);
            const connectionIdInput = document.getElementById('connectionIdInput');
            if (connectionIdInput) {
                connectionIdInput.value = savedConnectionId;
            }
        }

        const invitePayload = inviteController.getInvitePayloadFromUrl();
        if (invitePayload) {
            inviteController.showCallRequestDialog(invitePayload);
        }

        logger.debug('SPA initialized, showing connect view');
    } catch (error) {
        logger.error('Error initializing SPA:', error);
        showNotification('初始化失败，请刷新页面重试', 'error');
    }
});

export { store };
