import { BrowserWindow, app, ipcMain } from "electron";

let win: BrowserWindow | null = null;

const HTML = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:system-ui,sans-serif;background:#1e1e2e;color:#cdd6f4;
  display:flex;flex-direction:column;align-items:center;justify-content:center;
  height:100vh;padding:28px 32px;gap:14px;user-select:none;-webkit-app-region:drag}
h2{font-size:15px;font-weight:600;letter-spacing:.3px}
#status{font-size:13px;color:#a6adc8}
.track{width:100%;height:6px;background:#313244;border-radius:3px}
#bar{height:6px;background:#89b4fa;border-radius:3px;width:0%;transition:width .4s ease}
#btn{display:none;margin-top:6px;padding:9px 24px;background:#89b4fa;color:#1e1e2e;
  border:none;border-radius:6px;font-size:13px;font-weight:700;cursor:pointer;
  -webkit-app-region:no-drag}
#btn:hover{background:#b4befe}
</style></head><body>
<h2 id="title">Updating Sanctum</h2>
<div id="status">Downloading…</div>
<div class="track"><div id="bar"></div></div>
<button id="btn">Restart Now</button>
<script>
const {ipcRenderer}=require('electron');
ipcRenderer.on('upd-progress',(_,p)=>{
  document.getElementById('bar').style.width=p+'%';
  document.getElementById('status').textContent=p<100?'Downloading… '+p+'%':'Installing…';
});
ipcRenderer.on('upd-ready',(_,v)=>{
  document.getElementById('title').textContent='Sanctum '+v+' Ready';
  document.getElementById('status').textContent='Restart to apply the update.';
  document.getElementById('bar').style.width='100%';
  document.getElementById('btn').style.display='block';
});
ipcRenderer.on('upd-error',(_,msg)=>{
  document.getElementById('title').textContent='Update Failed';
  document.getElementById('status').textContent=msg;
  document.getElementById('bar').style.background='#f38ba8';
});
document.getElementById('btn').onclick=()=>ipcRenderer.send('upd-restart');
</script></body></html>`;

export function showUpdateWindow() {
  if (win) { win.focus(); return; }
  win = new BrowserWindow({
    width: 400,
    height: 180,
    resizable: false,
    minimizable: false,
    maximizable: false,
    fullscreenable: false,
    title: "Sanctum Update",
    frame: false,
    alwaysOnTop: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });
  win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(HTML));
  win.on("closed", () => { win = null; });
}

export function setUpdateProgress(percent: number) {
  win?.webContents.send("upd-progress", Math.round(percent));
}

export function setUpdateReady(version: string) {
  win?.webContents.send("upd-ready", version);
}

export function setUpdateError(msg: string) {
  win?.webContents.send("upd-error", msg);
}

ipcMain.on("upd-restart", () => {
  if (process.platform !== "win32") app.relaunch();
  app.exit(0);
});
