// DOM Elements Cache
const pages = document.querySelectorAll('.page');
const modals = document.querySelectorAll('.modal');
const mainApp = document.getElementById('mainApp');
const scrollNavItems = document.querySelectorAll('.scroll-nav .nav-item');

// User data from JSON
const userData = {
    name: "홍길동",
    email: "hong@example.com",
    phone: "010-1234-5678",
    bank_account: "K뱅크 947*****947",
    krdt_balance: 1250000,
    krw_balance: 150000000
};

// 사용자 상태 추적
let userState = {
    isLoggedIn: false,
    hasCompletedKYC: false,
    isNewUser: false,
    hasConnectedAccount: false
};

// Page Navigation System (for individual pages like KYC, login etc.)
function showPage(pageId) {
    // Hide all pages
    pages.forEach(page => {
        page.classList.remove('active');
    });
    
    // Hide main app
    if (mainApp) {
        mainApp.classList.add('hidden');
    }
    
    // Show the selected page
    const selectedPage = document.getElementById(pageId);
    if (selectedPage) {
        selectedPage.classList.add('active');
        
        // Scroll to top when changing pages
        selectedPage.scrollTop = 0;
    }
}

// Show Main App (scroll-based navigation)
function showMainApp() {
    // Hide all individual pages
    pages.forEach(page => {
        page.classList.remove('active');
    });
    
    // Show main app
    if (mainApp) {
        mainApp.classList.remove('hidden');
        // Scroll to home section
        scrollToSection('homeSection');
    }
}

// Scroll to specific section in main app
function scrollToSection(sectionId) {
    if (!mainApp || mainApp.classList.contains('hidden')) {
        showMainApp();
        return;
    }
    
    const section = document.getElementById(sectionId);
    if (section) {
        section.scrollIntoView({ behavior: 'smooth' });
        
        // Update navigation active state
        updateScrollNav(sectionId);
    }
}

// Update scroll navigation active state
function updateScrollNav(sectionId) {
    const sectionMap = {
        'homeSection': 0,
        'tradeSection': 1,
        'walletSection': 2,
        'moreSection': 3
    };
    
    scrollNavItems.forEach(item => {
        item.classList.remove('active');
    });
    
    const activeIndex = sectionMap[sectionId];
    if (activeIndex !== undefined && scrollNavItems[activeIndex]) {
        scrollNavItems[activeIndex].classList.add('active');
    }
}

// Tab Switching for Trade Page
function switchTab(tabName) {
    const tradeTabs = document.querySelectorAll('.trade-tabs .tab-btn');
    const allTabs = ['buy', 'sell'];
    
    // Remove active class from all tabs
    tradeTabs.forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Hide all tab content
    allTabs.forEach(tab => {
        const tabContent = document.getElementById(`${tab}Tab`);
        if (tabContent) {
            tabContent.classList.remove('active');
        }
    });
    
    // Show selected tab content and activate tab button
    const selectedTab = document.getElementById(`${tabName}Tab`);
    if (selectedTab) {
        selectedTab.classList.add('active');
    }
    
    // Find and activate the correct tab button
    if (tabName === 'buy' && tradeTabs[0]) {
        tradeTabs[0].classList.add('active');
    } else if (tabName === 'sell' && tradeTabs[1]) {
        tradeTabs[1].classList.add('active');
    }
}

// Tab Switching for Wallet Page
function switchWalletTab(tabName) {
    const walletTabs = document.querySelectorAll('.wallet-tabs .tab-btn');
    const allTabs = ['krwDeposit', 'krwWithdraw', 'krdtDeposit', 'krdtWithdraw'];
    
    // Remove active class from all tabs
    walletTabs.forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Hide all tab content
    allTabs.forEach(tab => {
        const tabContent = document.getElementById(`${tab}Tab`);
        if (tabContent) {
            tabContent.classList.remove('active');
        }
    });
    
    // Show selected tab content
    const selectedTab = document.getElementById(`${tabName}Tab`);
    if (selectedTab) {
        selectedTab.classList.add('active');
    }
    
    // Find and activate the correct tab button
    const tabIndex = allTabs.indexOf(tabName);
    if (tabIndex >= 0 && walletTabs[tabIndex]) {
        walletTabs[tabIndex].classList.add('active');
    }
}

// Tab Switching for Notice Page
function switchNoticeTab(tabName) {
    const noticeTabs = document.querySelectorAll('.notice-tabs .tab-btn');
    const allTabs = ['all', 'guide', 'event', 'maintenance'];
    
    // Remove active class from all tabs
    noticeTabs.forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Activate selected tab
    const tabIndex = allTabs.indexOf(tabName);
    if (tabIndex >= 0 && noticeTabs[tabIndex]) {
        noticeTabs[tabIndex].classList.add('active');
    }
    
    // Filter notices based on selected category
    filterNotices(tabName);
}

// Filter notices based on category
function filterNotices(category) {
    const notices = document.querySelectorAll('.notice-item');
    
    notices.forEach(notice => {
        const categoryElement = notice.querySelector('.notice-category');
        if (categoryElement) {
            const noticeCategory = categoryElement.textContent.toLowerCase();
            
            if (category === 'all') {
                notice.style.display = 'block';
            } else {
                // Map Korean categories to English tab names
                const categoryMap = {
                    '안내': 'guide',
                    '이벤트': 'event', 
                    '점검': 'maintenance'
                };
                
                const mappedCategory = categoryMap[noticeCategory] || noticeCategory;
                
                if (mappedCategory === category) {
                    notice.style.display = 'block';
                } else {
                    notice.style.display = 'none';
                }
            }
        }
    });
}

// Modal Functions
function showModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
        // Prevent scrolling of the background
        document.body.style.overflow = 'hidden';
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
        // Restore scrolling
        document.body.style.overflow = '';
    }
}

// K뱅크 계좌 연결 기능
function connectAccount() {
    // Simulate account connection
    userState.hasConnectedAccount = true;
    
    // Hide connection section and show asset display
    const connectionSection = document.getElementById('accountConnectionSection');
    const assetDisplay = document.getElementById('assetDisplay');
    
    if (connectionSection) {
        connectionSection.style.display = 'none';
    }
    
    if (assetDisplay) {
        assetDisplay.classList.remove('hidden');
    }
    
    // Show success message
    alert('K뱅크 계좌 연결이 완료되었습니다!');
}

// KRDT 출금 처리 (TTC 주소 검증)
function processWithdraw() {
    const addressInput = document.getElementById('withdrawAddress');
    if (!addressInput) return;
    
    const address = addressInput.value.trim();
    
    if (!address) {
        alert('출금 주소를 입력해주세요.');
        return;
    }
    
    // TTC로 시작하는지 확인
    if (address.startsWith('TTC')) {
        // 성공 모달 표시
        showModal('withdrawSuccessModal');
    } else {
        // 오류 모달 표시
        showModal('withdrawErrorModal');
    }
}

// Phone verification functions
function sendVerificationCode() {
    const verifyBtns = document.querySelectorAll('.verify-btn');
    const verificationGroups = document.querySelectorAll('.verification-group');
    
    verifyBtns.forEach(btn => {
        btn.textContent = '인증번호 재발송';
    });
    
    verificationGroups.forEach(group => {
        group.classList.remove('hidden');
    });
    
    // Show success message
    alert('인증번호가 발송되었습니다.');
}

// 토마토 One-ID 로그인 처리
function handleTomatoLogin(event) {
    event.preventDefault();
    const form = event.target;
    const phone = form.querySelector('input[type="tel"]').value;
    const password = form.querySelector('input[type="password"]').value;
    
    if (phone && password) {
        userState.isLoggedIn = true;
        
        // 기존 회원인지 신규 회원인지 확인 (시뮬레이션)
        // 실제로는 서버에서 확인해야 함
        if (userState.isNewUser) {
            // 신규 회원이면 KYC 모달 표시
            showModal('kycRequiredModal');
        } else {
            // 기존 회원이면서 KYC 미완료시 KYC 모달 표시
            if (!userState.hasCompletedKYC) {
                showModal('kycRequiredModal');
            } else {
                // KYC 완료된 기존 회원은 바로 홈으로
                showMainApp();
            }
        }
    } else {
        alert('휴대폰번호와 비밀번호를 입력해주세요.');
    }
}

// 회원가입 완료 후 로그인 시뮬레이션
function simulateLoginAfterSignup() {
    userState.isLoggedIn = true;
    userState.isNewUser = true;
    userState.hasCompletedKYC = false;
    
    // KYC 모달 표시
    showModal('kycRequiredModal');
}

// 전체 동의 체크박스 처리
function handleAllAgree() {
    const allAgreeCheckbox = document.getElementById('allAgree');
    const checkboxes = document.querySelectorAll('.terms-section input[type="checkbox"]:not(#allAgree)');
    
    if (allAgreeCheckbox) {
        allAgreeCheckbox.addEventListener('change', function() {
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
    
    // 개별 체크박스 변경 시 전체 동의 상태 업데이트
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            if (allAgreeCheckbox) {
                const allChecked = Array.from(checkboxes).every(cb => cb.checked);
                allAgreeCheckbox.checked = allChecked;
            }
        });
    });
}

// KYC 완료 처리
function completeKYC() {
    userState.hasCompletedKYC = true;
    showMainApp();
}

// Logout function
function logout() {
    userState.isLoggedIn = false;
    userState.hasCompletedKYC = false;
    userState.isNewUser = false;
    userState.hasConnectedAccount = false;
    showPage('loginPage');
}

// Copy wallet address function
function copyWalletAddress() {
    const address = document.querySelector('.address');
    const copyBtn = document.querySelector('.copy-btn');
    
    if (address && copyBtn) {
        try {
            // Use modern clipboard API if available
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(address.textContent).then(() => {
                    showCopySuccess(copyBtn);
                }).catch(() => {
                    fallbackCopy(address.textContent, copyBtn);
                });
            } else {
                fallbackCopy(address.textContent, copyBtn);
            }
        } catch (err) {
            console.error('Failed to copy text: ', err);
        }
    }
}

// Fallback copy function
function fallbackCopy(text, copyBtn) {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    
    try {
        document.execCommand('copy');
        showCopySuccess(copyBtn);
    } catch (err) {
        console.error('Fallback copy failed: ', err);
    }
    
    document.body.removeChild(textarea);
}

// Show copy success feedback
function showCopySuccess(copyBtn) {
    const originalText = copyBtn.textContent;
    copyBtn.textContent = '복사 완료';
    copyBtn.classList.add('btn--primary');
    copyBtn.classList.remove('btn--outline');
    
    setTimeout(() => {
        copyBtn.textContent = originalText;
        copyBtn.classList.remove('btn--primary');
        copyBtn.classList.add('btn--outline');
    }, 2000);
}

// Handle touch events for better mobile experience
function handleTouchEvents() {
    // Add touch feedback for buttons
    const buttons = document.querySelectorAll('.btn, .nav-item, .menu-item');
    
    buttons.forEach(button => {
        button.addEventListener('touchstart', function() {
            this.style.opacity = '0.7';
        });
        
        button.addEventListener('touchend', function() {
            setTimeout(() => {
                this.style.opacity = '';
            }, 100);
        });
        
        button.addEventListener('touchcancel', function() {
            this.style.opacity = '';
        });
    });
}

// Prevent zoom on iOS inputs
function preventZoom() {
    const inputs = document.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.style.fontSize = '16px';
        });
        
        input.addEventListener('blur', function() {
            this.style.fontSize = '';
        });
    });
}

// Intersection Observer for scroll navigation
function setupScrollObserver() {
    if (!mainApp) return;
    
    const sections = document.querySelectorAll('.app-section');
    const observer = new IntersectionObserver(
        (entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
                    updateScrollNav(entry.target.id);
                }
            });
        },
        {
            threshold: [0.5],
            rootMargin: '-100px 0px -100px 0px'
        }
    );
    
    sections.forEach(section => {
        observer.observe(section);
    });
}

// Initialize event listeners
function initializeEventListeners() {
    // 토마토 One-ID 로그인 폼 처리
    const loginForm = document.querySelector('.login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', handleTomatoLogin);
    }
    
    // Phone verification buttons
    const verifyBtns = document.querySelectorAll('.verify-btn');
    verifyBtns.forEach(btn => {
        btn.addEventListener('click', sendVerificationCode);
    });
    
    // Copy wallet address button
    const copyBtn = document.querySelector('.copy-btn');
    if (copyBtn) {
        copyBtn.addEventListener('click', copyWalletAddress);
    }
    
    // Scroll navigation click handlers
    scrollNavItems.forEach((item, index) => {
        item.addEventListener('click', () => {
            const sections = ['homeSection', 'tradeSection', 'walletSection', 'moreSection'];
            scrollToSection(sections[index]);
        });
    });
    
    // Close modal when clicking outside of it
    window.addEventListener('click', function(event) {
        const modals = document.querySelectorAll('.modal');
        modals.forEach(modal => {
            if (event.target === modal) {
                modal.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
    });
    
    // Back button handlers
    const backButtons = document.querySelectorAll('.back-btn');
    backButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const currentPage = this.closest('.page');
            if (currentPage) {
                // Navigate back to appropriate page based on current page
                switch(currentPage.id) {
                    case 'signupPage':
                        showPage('loginPage');
                        break;
                    case 'signupCompletePage':
                        showPage('signupPage');
                        break;
                    case 'kycStep1Page':
                        showMainApp();
                        break;
                    case 'kycStep2Page':
                        showPage('kycStep1Page');
                        break;
                    case 'kycStep3Page':
                        showPage('kycStep2Page');
                        break;
                    case 'kycCompletePage':
                        showMainApp();
                        break;
                    case 'profilePage':
                    case 'securityPage':
                    case 'noticePage':
                    case 'supportPage':
                        showMainApp();
                        break;
                    default:
                        showMainApp();
                }
            }
        });
    });
    
    // 전체 동의 체크박스 처리
    handleAllAgree();
    
    // Initialize touch events and mobile optimizations
    handleTouchEvents();
    preventZoom();
    
    // 페이지별 특별 처리
    setupPageSpecificHandlers();
    
    // Setup scroll observer for navigation
    setupScrollObserver();
}

// 페이지별 특별 이벤트 처리
function setupPageSpecificHandlers() {
    // 회원가입 완료 페이지에서 확인 버튼 클릭 시 로그인 시뮬레이션
    const signupCompleteBtn = document.querySelector('#signupCompletePage .btn--primary');
    if (signupCompleteBtn) {
        signupCompleteBtn.addEventListener('click', function() {
            // 로그인 페이지로 이동하면서 신규 회원으로 설정
            userState.isNewUser = true;
            showPage('loginPage');
        });
    }
    
    // KYC 완료 페이지에서 거래 시작 버튼
    const kycCompleteBtn = document.querySelector('#kycCompletePage .btn--primary');
    if (kycCompleteBtn) {
        kycCompleteBtn.addEventListener('click', function() {
            completeKYC();
        });
    }
    
    // 아이디 촬영 버튼 시뮬레이션
    const idBtns = document.querySelectorAll('.id-btn');
    idBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            alert('신분증 촬영이 완료되었습니다.');
            this.textContent = '신분증 촬영 완료';
            this.classList.remove('btn--outline');
            this.classList.add('btn--secondary');
        });
    });
    
    // 매수/매도 버튼들
    const tradeButtons = document.querySelectorAll('#buyTab .btn--primary, #sellTab .btn--primary');
    tradeButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const isKYCComplete = userState.hasCompletedKYC;
            if (!isKYCComplete) {
                showModal('kycRequiredModal');
            } else {
                if (this.textContent.includes('매수')) {
                    showModal('buyModal');
                } else {
                    showModal('sellModal');
                }
            }
        });
    });
    
    // 입출금 버튼들 (출금 제외)
    const walletButtons = document.querySelectorAll('.wallet-tab-content .btn--primary:not([onclick*="processWithdraw"])');
    walletButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            alert('처리가 완료되었습니다.');
        });
    });
}

// Update user interface with data
function updateUserInterface() {
    // Set user name in profile
    const profileNames = document.querySelectorAll('.profile-info h3, .home-header h2');
    profileNames.forEach(el => {
        if (el.textContent.includes('님')) {
            el.textContent = `안녕하세요, ${userData.name}님`;
        } else {
            el.textContent = `${userData.name}님`;
        }
    });
    
    // Set email in profile
    const profileEmails = document.querySelectorAll('.profile-info p');
    profileEmails.forEach(el => {
        if (el.textContent.includes('@') || el.textContent === '') {
            el.textContent = userData.email;
        }
    });
    
    // Update balance display
    const krwElements = document.querySelectorAll('.asset-value');
    if (krwElements[0]) {
        krwElements[0].textContent = userData.krw_balance.toLocaleString() + '원';
    }
    if (krwElements[1]) {
        krwElements[1].textContent = userData.krdt_balance.toLocaleString();
    }
    
    // Set bank account info
    const accountInfos = document.querySelectorAll('.account-info p');
    accountInfos.forEach(el => {
        if (el.textContent.includes('947')) {
            el.textContent = userData.bank_account;
        }
    });
    
    // Set KRDT balance for selling
    const balanceAmounts = document.querySelectorAll('.balance-amount');
    balanceAmounts.forEach(el => {
        el.textContent = userData.krdt_balance.toLocaleString() + ' KRDT';
    });
    
    // Update member info page
    const infoValues = document.querySelectorAll('.info-value');
    if (infoValues[0]) infoValues[0].textContent = userData.name;
    if (infoValues[1]) infoValues[1].textContent = userData.email;
    if (infoValues[2]) infoValues[2].textContent = userData.phone;
    if (infoValues[3]) infoValues[3].textContent = userData.bank_account;
}

// Handle orientation changes for better mobile experience
function handleOrientationChange() {
    window.addEventListener('orientationchange', function() {
        // Force a layout recalculation after orientation change
        setTimeout(() => {
            const mobileContainer = document.querySelector('.mobile-device-container');
            if (mobileContainer) {
                mobileContainer.style.transform = 'translateZ(0)';
                setTimeout(() => {
                    mobileContainer.style.transform = '';
                }, 50);
            }
        }, 100);
    });
}

// Update status bar time
function updateStatusBarTime() {
    const timeElement = document.querySelector('.time');
    if (timeElement) {
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        timeElement.textContent = `${hours}:${minutes}`;
    }
}

// Initialize the application
function initializeApp() {
    // Set default page to login
    showPage('loginPage');
    
    // Initialize all event listeners
    initializeEventListeners();
    
    // Update UI with user data
    updateUserInterface();
    
    // Handle orientation changes
    handleOrientationChange();
    
    // Update status bar time
    updateStatusBarTime();
    
    // Update time every minute
    setInterval(updateStatusBarTime, 60000);
    
    // Console message for debugging
    console.log('코인통 KRDT 토마토 One-ID 모바일 앱이 성공적으로 초기화되었습니다');
}

// Start the application when DOM is fully loaded
document.addEventListener('DOMContentLoaded', initializeApp);

// Make functions available globally for onclick handlers
window.showPage = showPage;
window.showMainApp = showMainApp;
window.scrollToSection = scrollToSection;
window.switchTab = switchTab;
window.switchWalletTab = switchWalletTab;
window.switchNoticeTab = switchNoticeTab;
window.showModal = showModal;
window.closeModal = closeModal;
window.logout = logout;
window.sendVerificationCode = sendVerificationCode;
window.connectAccount = connectAccount;
window.processWithdraw = processWithdraw;