const { app, BrowserWindow } = require("electron");
const fs = require("fs");
const path = require("path");

const ROOT = path.resolve(__dirname, "..");
const OUT_DIR = path.join(ROOT, "outputs", "user_guide_screenshots");

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function ensureDir(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}

async function captureScreen({ name, htmlPath, width = 1600, height = 1000, afterLoadScript = "" }) {
  const win = new BrowserWindow({
    width,
    height,
    show: false,
    backgroundColor: "#f5f5f3",
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      additionalArguments: ["--apiBase=http://127.0.0.1:5006"],
    },
  });

  await win.loadFile(htmlPath);
  await sleep(1800);

  if (afterLoadScript) {
    try {
      await win.webContents.executeJavaScript(afterLoadScript);
      await sleep(600);
    } catch (error) {
      // Keep screenshot flow robust even if one optional DOM script fails.
    }
  }

  const image = await win.webContents.capturePage();
  const outPath = path.join(OUT_DIR, name);
  fs.writeFileSync(outPath, image.toPNG());
  await win.close();
}

async function run() {
  ensureDir(OUT_DIR);

  await captureScreen({
    name: "01_login.png",
    htmlPath: path.join(ROOT, "desktop", "login.html"),
    width: 540,
    height: 760,
  });

  await captureScreen({
    name: "02_login_forgot_password.png",
    htmlPath: path.join(ROOT, "desktop", "login.html"),
    width: 620,
    height: 860,
    afterLoadScript: `
      (function() {
        const email = document.getElementById('email');
        if (email) email.value = 'kayttaja@owalgroup.com';
        const btn = document.getElementById('forgotBtn');
        if (btn) btn.click();
        const resetEmail = document.getElementById('resetEmail');
        if (resetEmail) resetEmail.value = 'kayttaja@owalgroup.com';
      })();
    `,
  });

  await captureScreen({
    name: "03_main_overview.png",
    htmlPath: path.join(ROOT, "ui", "index.html"),
    width: 1680,
    height: 1180,
  });

  await captureScreen({
    name: "04_files_added.png",
    htmlPath: path.join(ROOT, "ui", "index.html"),
    width: 1680,
    height: 1180,
    afterLoadScript: `
      (function() {
        const list = document.getElementById('fileList');
        if (!list) return;
        list.innerHTML = '';
        const items = [
          ['Muistio luonnos.docx', '124 KB'],
          ['Johtoryhma muistiinpanot.txt', '19 KB']
        ];
        for (const [name, size] of items) {
          const li = document.createElement('li');
          li.textContent = name;
          const span = document.createElement('span');
          span.className = 'muted';
          span.textContent = size;
          li.appendChild(span);
          list.appendChild(li);
        }
        const clearBtn = document.getElementById('clearFilesBtn');
        if (clearBtn) clearBtn.disabled = false;
      })();
    `,
  });

  await captureScreen({
    name: "05_settings_section.png",
    htmlPath: path.join(ROOT, "ui", "index.html"),
    width: 1680,
    height: 1180,
    afterLoadScript: `
      (function() {
        const keyInput = document.getElementById('apiKeyInput');
        if (keyInput) keyInput.value = 'Admin asettaa avaimen';
        const settingsHeading = Array.from(document.querySelectorAll('h2'))
          .find((n) => n.textContent && n.textContent.includes('Lisäasetukset'));
        if (settingsHeading) settingsHeading.scrollIntoView({ behavior: 'instant', block: 'start' });
      })();
    `,
  });

  await captureScreen({
    name: "06_change_password.png",
    htmlPath: path.join(ROOT, "ui", "index.html"),
    width: 1680,
    height: 1180,
    afterLoadScript: `
      (function() {
        const btn = document.getElementById('changePasswordBtn');
        if (btn) btn.click();
        const curr = document.getElementById('currentPasswordInput');
        const next = document.getElementById('newPasswordInput');
        const conf = document.getElementById('confirmPasswordInput');
        if (curr) curr.value = '********';
        if (next) next.value = '************';
        if (conf) conf.value = '************';
      })();
    `,
  });

  await captureScreen({
    name: "07_result_and_save.png",
    htmlPath: path.join(ROOT, "ui", "index.html"),
    width: 1680,
    height: 1180,
    afterLoadScript: `
      (function() {
        const status = document.getElementById('statusText');
        if (status) status.textContent = 'Dokumentti valmis. Tallenna Word haluttuun sijaintiin.';
        const result = document.getElementById('resultBox');
        if (result) result.hidden = false;
        const setText = (id, text) => {
          const el = document.getElementById(id);
          if (el) el.textContent = text;
        };
        setText('resultRequestedKind', 'report');
        setText('resultKind', 'report');
        setText('resultMode', 'style_polish');
        setText('resultTemplate', 'minimal_brand_layout_v1');
        setText('resultSummary', 'Tiivis yhteenveto lopputuloksesta.');
        setText('resultPath', '/Users/..../owalisaattori_report.docx');
        const saveBtn = document.getElementById('saveBtn');
        if (saveBtn) saveBtn.disabled = false;
        const delBtn = document.getElementById('deleteRunBtn');
        if (delBtn) delBtn.disabled = false;
        const statusHeading = Array.from(document.querySelectorAll('h2'))
          .find((n) => n.textContent && n.textContent.includes('Tila'));
        if (statusHeading) statusHeading.scrollIntoView({ behavior: 'instant', block: 'start' });
      })();
    `,
  });

  console.log(`Screenshots generated in: ${OUT_DIR}`);
}

app.whenReady()
  .then(run)
  .then(() => app.quit())
  .catch((error) => {
    console.error(error);
    app.quit();
    process.exit(1);
  });
