import "./style.css";
import "./app.css";
import { StartLogin, LoggedIn } from "../wailsjs/go/main/App";
import { EventsOn } from "../wailsjs/runtime/runtime";

// 临时登录验证 UI：在共享 web 界面接入（A2）前，用它端到端验证 D1
// loopback OAuth 流程。点登录 → Go 起 loopback + 开系统浏览器 → 授权回跳 →
// Go 换 token → oauth:success / oauth:error 事件回到这里。
document.querySelector("#app")!.innerHTML = `
    <main class="login-demo">
        <h1>cdrop 桌面端</h1>
        <p class="status" id="status">检查登录状态……</p>
        <button class="btn" id="loginBtn" disabled>登录 cdrop</button>
        <p class="hint">登录会在系统浏览器中打开授权页，完成后自动返回。</p>
    </main>
`;

const statusEl = document.getElementById("status") as HTMLElement;
const loginBtn = document.getElementById("loginBtn") as HTMLButtonElement;

function setStatus(text: string): void {
    statusEl.innerText = text;
}

loginBtn.addEventListener("click", () => {
    setStatus("已在系统浏览器中打开授权页，请完成登录……");
    loginBtn.disabled = true;
    StartLogin();
});

EventsOn("oauth:success", (payload: { expiresIn: number }) => {
    setStatus(`登录成功，access token 有效期约 ${payload.expiresIn} 秒。`);
    loginBtn.innerText = "重新登录";
    loginBtn.disabled = false;
});

EventsOn("oauth:error", (payload: { detail: string }) => {
    setStatus(`登录失败：${payload.detail}`);
    loginBtn.disabled = false;
});

LoggedIn()
    .then((yes) => {
        setStatus(yes ? "已登录。" : "尚未登录。");
        loginBtn.disabled = false;
    })
    .catch(() => {
        setStatus("尚未登录。");
        loginBtn.disabled = false;
    });
