const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
let steamworks = null
let steamInitialized = false

// Try to initialize Steam
function initializeSteam() {
    try {
        // Only try to load steamworks if steam_appid.txt exists
        const fs = require('fs')
        const steamAppIdPath = path.join(__dirname, '../public/steam_appid.txt')

        if (fs.existsSync(steamAppIdPath)) {
            steamworks = require('steamworks.js')
            const client = steamworks.init(480) // Test App ID - replace with your Steam App ID
            steamInitialized = true
            console.log('✅ Steam initialized successfully')
            console.log('Steam User:', client.localplayer.getName())
            console.log('Steam ID:', client.localplayer.getSteamId().steamId64)
            return client
        } else {
            console.log('ℹ️  steam_appid.txt not found, running without Steam')
            return null
        }
    } catch (error) {
        console.log('ℹ️  Steam not available:', error.message)
        steamInitialized = false
        return null
    }
}

const steamClient = initializeSteam()

function createWindow() {
    const win = new BrowserWindow({
        width: 1200,
        height: 800,
        minWidth: 800,
        minHeight: 600,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.cjs')
        },
        icon: path.join(__dirname, 'icons/icon.png'),
        title: 'Echoes of the Ash'
    })

    // In production, load the built files
    if (app.isPackaged) {
        win.loadFile(path.join(__dirname, '../dist/index.html'))
    } else {
        // In development, load from dev server
        win.loadURL('http://localhost:5173')
        win.webContents.openDevTools()
    }

    // Handle window close
    win.on('closed', () => {
        if (steamClient) {
            steamworks.runCallbacks()
        }
    })
}

// IPC Handlers
ipcMain.handle('get-steam-auth', async () => {
    if (steamInitialized && steamClient) {
        try {
            const player = steamClient.localplayer
            return {
                available: true,
                steamId: player.getSteamId().steamId64,
                steamName: player.getName()
            }
        } catch (error) {
            console.error('Error getting Steam auth:', error)
            return { available: false }
        }
    }
    return { available: false }
})

ipcMain.handle('is-steam-available', async () => {
    return steamInitialized
})

ipcMain.handle('get-platform', async () => {
    return process.platform
})

// App lifecycle
app.whenReady().then(() => {
    createWindow()

    // Run Steam callbacks periodically if Steam is initialized
    if (steamInitialized && steamClient) {
        setInterval(() => {
            try {
                steamworks.runCallbacks()
            } catch (error) {
                console.error('Error running Steam callbacks:', error)
            }
        }, 1000)
    }
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})

// Cleanup on quit
app.on('before-quit', () => {
    if (steamClient) {
        try {
            steamworks.runCallbacks()
        } catch (error) {
            console.error('Error during Steam cleanup:', error)
        }
    }
})
