"use strict";

(function () {
  const state = {
    actionUuid: "",
    pluginVersion: "1.1.2",
    guideByUuid: {},
    manifestByUuid: {},
    ws: null
  };

  const el = {
    name: document.getElementById("shortcut-name"),
    category: document.getElementById("shortcut-category"),
    combo: document.getElementById("shortcut-combo"),
    use: document.getElementById("shortcut-use"),
    howList: document.getElementById("shortcut-how-list"),
    when: document.getElementById("shortcut-when"),
    whenList: document.getElementById("shortcut-when-list"),
    source: document.getElementById("shortcut-source"),
    footer: document.getElementById("footer-text"),
    warningCard: document.getElementById("setting-required-card"),
    readyCard: document.getElementById("ready-card"),
    setupNote: document.getElementById("setup-note"),
    setupSteps: document.getElementById("setup-steps"),
    setupVerifyWrap: document.getElementById("setup-verify-wrap"),
    setupVerify: document.getElementById("setup-verify"),
    setupTroubleshootWrap: document.getElementById("setup-troubleshoot-wrap"),
    setupTroubleshoot: document.getElementById("setup-troubleshoot"),
    copyEmailBtn: document.getElementById("copy-email-btn"),
    openMailBtn: document.getElementById("open-mail-btn")
  };

  function getBaseMeta(uuid) {
    const manifestMeta = state.manifestByUuid[uuid] || {};
    return {
      name: manifestMeta.name || "Shortcut",
      category: manifestMeta.category || "General",
      shortcut: manifestMeta.shortcut || "-",
      source: manifestMeta.source || "Shortcut action",
      use: manifestMeta.use || "shortcut execution",
      useBullets: [],
      when: manifestMeta.when || "speed matters more than menu navigation",
      whenBullets: [],
      settingRequired: Boolean(manifestMeta.settingRequired),
      setupNote: "This shortcut needs Photoshop keyboard setup before it can run.",
      setupSteps: [],
      setupVerify: [],
      setupTroubleshoot: []
    };
  }

  function extractActionUuid(actionInfoObj) {
    if (!actionInfoObj || typeof actionInfoObj !== "object") return "";
    if (typeof actionInfoObj.action === "string") return actionInfoObj.action;
    if (typeof actionInfoObj.Action === "string") return actionInfoObj.Action;
    return "";
  }

  function sendOpenUrl(url) {
    if (!state.ws || state.ws.readyState !== 1 || !url) return;
    state.ws.send(JSON.stringify({
      event: "openUrl",
      payload: { url: url }
    }));
  }

  function renderList(target, items) {
    target.innerHTML = "";
    if (!Array.isArray(items) || items.length === 0) return;
    items.forEach(function (item) {
      if (!item) return;
      const li = document.createElement("li");
      li.textContent = String(item);
      target.appendChild(li);
    });
  }

  function render() {
    const base = getBaseMeta(state.actionUuid);
    const guide = state.guideByUuid[state.actionUuid] || {};
    const data = Object.assign({}, base, guide);

    el.name.textContent = data.name;
    el.category.textContent = data.category || "General";
    el.combo.textContent = data.shortcut || "-";
    el.use.textContent = data.use || "shortcut execution";
    renderList(el.howList, data.useBullets);
    el.when.textContent = data.when || "speed matters more than menu navigation";
    renderList(el.whenList, data.whenBullets);
    el.source.textContent = data.source ? `Source: ${data.source}` : "Source: Shortcut action";

    const required = Boolean(data.settingRequired);
    el.warningCard.classList.toggle("hidden", !required);
    el.readyCard.classList.toggle("hidden", required);

    el.setupNote.textContent = data.setupNote || "This shortcut needs Photoshop keyboard setup before it can run.";
    renderList(el.setupSteps, data.setupSteps);
    renderList(el.setupVerify, data.setupVerify);
    renderList(el.setupTroubleshoot, data.setupTroubleshoot);
    el.setupVerifyWrap.classList.toggle("hidden", !required || !Array.isArray(data.setupVerify) || data.setupVerify.length === 0);
    el.setupTroubleshootWrap.classList.toggle("hidden", !required || !Array.isArray(data.setupTroubleshoot) || data.setupTroubleshoot.length === 0);

    el.footer.textContent =
      `Bravent® All rights reserved 2025. · Bravent Hub Photoshop+© v${state.pluginVersion}`;
  }

  async function loadAssets() {
    const [guideRes, manifestRes] = await Promise.all([
      fetch("./shortcut-guides.json"),
      fetch("../manifest.json")
    ]);

    if (guideRes.ok) {
      state.guideByUuid = await guideRes.json();
    }

    if (manifestRes.ok) {
      const manifest = await manifestRes.json();
      state.pluginVersion = manifest.Version || state.pluginVersion;

      const map = {};
      (manifest.Actions || []).forEach(function (action) {
        const uuid = action.UUID;
        const tooltip = String(action.Tooltip || "");
        const shortcutMatch = tooltip.match(/\(([^)]+)\)/);
        map[uuid] = {
          name: action.Name || "Shortcut",
          shortcut: shortcutMatch ? shortcutMatch[1] : "-",
          source: "Manifest shortcut",
          category: "General",
          use: "shortcut execution",
          when: "speed matters more than menu navigation",
          settingRequired: tooltip.indexOf("[SETTING REQUIRED]") !== -1
        };
      });
      state.manifestByUuid = map;
    }
  }

  async function init() {
    try {
      await loadAssets();
    } catch (_) {
      // Keep graceful fallback rendering.
    }
    render();
  }

  window.connectElgatoStreamDeckSocket = function (port, uuid, registerEvent, info, actionInfo) {
    try {
      const actionInfoObj = JSON.parse(actionInfo || "{}");
      state.actionUuid = extractActionUuid(actionInfoObj);
    } catch (_) {
      state.actionUuid = "";
    }

    if (port && uuid && registerEvent) {
      try {
        state.ws = new WebSocket(`ws://127.0.0.1:${port}`);
        state.ws.onopen = function () {
          state.ws.send(JSON.stringify({ event: registerEvent, uuid: uuid }));
        };
      } catch (_) {
        state.ws = null;
      }
    }

    init();
  };

  el.copyEmailBtn.addEventListener("click", function () {
    const mail = "sixth@bravent.co";
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(mail).catch(function () {});
    }
  });

  el.openMailBtn.addEventListener("click", function () {
    sendOpenUrl("mailto:sixth@bravent.co");
  });

  // Fallback for local preview/debug outside Stream Dock.
  init();
})();

