import { BrowserWindow, screen, nativeImage } from 'electron'
import * as path from 'path'
import * as fs from 'fs'

let mainWindow: BrowserWindow | null = null
export let baseAppUrl = ''

export function createMainWindow(): BrowserWindow {
  const cursor = screen.getCursorScreenPoint()
  const displays = screen.getAllDisplays()
  const targetDisplay = displays.find((d: Electron.Display) =>
    cursor.x >= d.bounds.x && cursor.x <= d.bounds.x + d.bounds.width &&
    cursor.y >= d.bounds.y && cursor.y <= d.bounds.y + d.bounds.height
  ) || displays[0]

  const iconPath = path.join(__dirname, '../../src/assets/icon.png')
  const appIcon = fs.existsSync(iconPath) ? nativeImage.createFromPath(iconPath) : undefined

  mainWindow = new BrowserWindow({
    x: Math.round(targetDisplay.bounds.x + targetDisplay.bounds.width / 2 - 300),
    y: targetDisplay.bounds.y,
    width: 600,
    height: 64,
    frame: false,
    transparent: true,
    alwaysOnTop: true,
    resizable: false,
    icon: appIcon,
    webPreferences: {
      preload: path.join(__dirname, '../preload/preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  })

  if (process.env.NODE_ENV === 'development' || process.argv.includes('--dev')) {
    baseAppUrl = 'http://localhost:5173'
    mainWindow.loadURL(baseAppUrl)
  } else {
    baseAppUrl = `file://${path.join(__dirname, '../../dist/index.html').replace(/\\/g, '/')}`
    mainWindow.loadFile(path.join(__dirname, '../../dist/index.html'))
  }

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  return mainWindow
}

export function getMainWindow(): BrowserWindow | null {
  return mainWindow
}

const dialogWindows: Record<string, BrowserWindow | null> = {}

export function openDialogWindow(type: string): BrowserWindow | null {
  const existing = dialogWindows[type]
  if (existing && !existing.isDestroyed()) {
    existing.focus()
    return existing
  }

  const sizes: Record<string, { width: number; height: number }> = {
    settings: { width: 640, height: 680 },
    history: { width: 1000, height: 750 },
    templates: { width: 720, height: 600 },
    rubric: { width: 750, height: 800 },
    result: { width: 600, height: 780 }
  }
  const size = sizes[type] || { width: 500, height: 500 }

  const child = new BrowserWindow({
    ...size,
    show: false,
    frame: false,
    transparent: true,
    resizable: false,
    webPreferences: {
      preload: path.join(__dirname, '../preload/preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  })

  if (process.env.NODE_ENV === 'development' || process.argv.includes('--dev')) {
    child.loadURL(`${baseAppUrl}?dialog=${type}`)
  } else {
    child.loadFile(path.join(__dirname, '../../dist/index.html'), { query: { dialog: type } })
  }
  child.show()

  dialogWindows[type] = child
  child.on('closed', () => { dialogWindows[type] = null })
  return child
}
