/* global React, L, useI18n */
// ===========================================================
// 앱 업데이트 — 시작 시 확인, 사용자가 업데이트/미루기 선택
// (자동 다운로드·재시작 없음 — Rust install_app_update 는 사용자 동의 후만)
// ===========================================================

const UPDATE_DEFER_KEY = "todoary.update.deferred";
const SUPPORT_EMAIL = "dinglediary@gmail.com";

function isTauriApp() {
  return !!(window.__TAURI__?.core?.invoke || window.__TAURI_INTERNALS__);
}

async function promptUpdateFlow(info, { respectDefer = true } = {}) {
  const invoke = window.__TAURI__?.core?.invoke;
  if (!invoke || !info?.version) return { ok: true, available: false };

  if (respectDefer) {
    try {
      if (sessionStorage.getItem(UPDATE_DEFER_KEY) === info.version) {
        return { ok: true, available: true, deferred: true };
      }
    } catch (_) {}
  }

  let message = L("update.prompt", {
    current: info.current_version || "?",
    version: info.version,
  });
  const notes = (info.body || "").trim();
  if (notes) message += "\n\n" + notes.slice(0, 400);

  const ok = await (window.dialog?.confirm
    ? window.dialog.confirm(message, {
      okLabel: L("update.yes"),
      cancelLabel: L("update.later"),
    })
    : Promise.resolve(confirm(message)));

  if (!ok) {
    if (respectDefer) {
      try { sessionStorage.setItem(UPDATE_DEFER_KEY, info.version); } catch (_) {}
    }
    return { ok: true, available: true, declined: true };
  }

  if (window.dialog?.alert) {
    await window.dialog.alert(L("update.installing"));
  }

  await invoke("install_app_update");
  return { ok: true, available: true, installed: true };
}

async function checkAndPromptUpdate(options = {}) {
  const invoke = window.__TAURI__?.core?.invoke;
  if (!invoke) return { ok: false, error: "not-tauri" };
  try {
    const info = await invoke("check_for_update");
    if (!info?.version) return { ok: true, available: false };
    return await promptUpdateFlow(info, options);
  } catch (e) {
    return { ok: false, error: String(e?.message || e || "") };
  }
}

function UpdaterWatcher() {
  useI18n();
  const ranRef = React.useRef(false);

  React.useEffect(() => {
    if (!isTauriApp() || ranRef.current) return;
    ranRef.current = true;

    let cancelled = false;
    (async () => {
      try {
        const r = await checkAndPromptUpdate({ respectDefer: true });
        if (cancelled || r.ok) return;
        if (window.dialog?.alert) {
          await window.dialog.alert(L("update.fail", { msg: r.error || "" }));
        }
      } catch (e) {
        console.warn("updater:", e);
        if (!cancelled && window.dialog?.alert) {
          await window.dialog.alert(L("update.fail", {
            msg: String(e?.message || e || ""),
          }));
        }
      }
    })();

    return () => { cancelled = true; };
  }, []);

  return null;
}

window.UpdaterWatcher = UpdaterWatcher;
window.todoaryUpdater = {
  checkAndPrompt: checkAndPromptUpdate,
  supportEmail: SUPPORT_EMAIL,
};
