<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>{{DeckName}}</title>
  </head>
  <body>
    <h2 class="deck-title">{{DeckName}}</h2>

    <div class="wrap">
      <!-- LEFT: board image -->
      <div class="card-column">
        <div class="imgwrap" id="boardBox">{{BoardImage}}</div>
      </div>

      <!-- RIGHT: options -->
      <div class="choices" id="choices" role="group" aria-label="Cube decision">
        <button class="btn" data-key="nd" aria-pressed="false">
          No Double
        </button>
        <button class="btn" data-key="dt" aria-pressed="false">
          Double / Take
        </button>
        <button class="btn" data-key="dp" aria-pressed="false">
          Double / Pass
        </button>
        <button type="button" class="submit-btn" id="submitBtn" disabled>
          Submit
        </button>
      </div>
    </div>

    <!-- Notes for mobile -->
    <div id="iosNote" class="ios-note" style="display: none">
      After making your choice, tap to see answer.
    </div>
    <div id="androidNote" class="ios-note" style="display: none">
      After making your choice, tap the bottom “Show Answer” button.
    </div>

    <!-- Script A: environment + sizing vars -->
    <script>
      (function () {
        const isiOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
        const isAndroid = /Android/i.test(navigator.userAgent);
        if (isiOS || isAndroid) document.body.classList.add("is-ios");

        const titleEl = document.querySelector(".deck-title");
        function setTitleH() {
          const h = titleEl
            ? Math.ceil(titleEl.getBoundingClientRect().height)
            : 0;
          document.documentElement.style.setProperty("--titleH", h + 12 + "px");
        }
        function setVH() {
          const vh = window.innerHeight * 0.01;
          document.documentElement.style.setProperty("--vh", vh + "px");
        }
        function setChrome() {
          const landscape = window.matchMedia(
            "(orientation: landscape)",
          ).matches;
          const chrome = landscape ? 150 : 160;
          document.documentElement.style.setProperty(
            "--anki-chrome",
            chrome + "px",
          );
        }

        setTitleH();
        setVH();
        setChrome();
        window.addEventListener(
          "orientationchange",
          () => {
            setTimeout(() => {
              setTitleH();
              setChrome();
            }, 0);
          },
          { passive: true },
        );
      })();
    </script>

    <!-- Script B: choices, persistence, flipping, hotkeys -->
    <script>
      (function () {
        const choices = document.getElementById("choices");
        const submit = document.getElementById("submitBtn");
        const iosNote = document.getElementById("iosNote");
        const androidNote = document.getElementById("androidNote");

        const isiOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
        const isAndroid = /Android/i.test(navigator.userAgent);

        try {
          sessionStorage.removeItem("ankibg_selected_text");
          sessionStorage.removeItem("ankibg_selected_idx");
        } catch (_) {}

        let useSubmit = true;
        if (isiOS) useSubmit = false;
        if (isAndroid && typeof window.pycmd !== "function") useSubmit = false;

        if (!useSubmit && submit) {
          submit.style.display = "none";
          if (isiOS && iosNote) iosNote.style.display = "block";
          if (isAndroid && androidNote) androidNote.style.display = "block";
        }

        function persistChoice(btn) {
          try {
            if (btn) {
              const txt = btn.textContent.trim();
              const key = btn.getAttribute("data-key") || "";
              sessionStorage.setItem("ankibg_selected_text", txt);
              sessionStorage.setItem("ankibg_selected_idx", key);
            } else {
              sessionStorage.removeItem("ankibg_selected_text");
              sessionStorage.removeItem("ankibg_selected_idx");
            }
          } catch (_) {}
        }

        function setActive(btn) {
          choices.querySelectorAll(".btn.active").forEach((b) => {
            b.classList.remove("active");
            b.setAttribute("aria-pressed", "false");
          });
          if (btn) {
            btn.classList.add("active");
            btn.setAttribute("aria-pressed", "true");
          }
          persistChoice(btn);
        }

        function updateSubmitState() {
          if (!useSubmit || !submit) return;
          submit.disabled = !choices.querySelector(".btn.active");
        }

        choices.addEventListener("click", (e) => {
          const btn = e.target.closest(".btn");
          if (!btn) return;
          if (btn.classList.contains("active")) {
            btn.classList.remove("active");
            btn.setAttribute("aria-pressed", "false");
            persistChoice(null);
            updateSubmitState();
            return;
          }
          setActive(btn);
          updateSubmitState();
        });

        function showAnswer() {
          if (typeof pycmd === "function") {
            pycmd("ans");
            return;
          }
          if (window.study && typeof window.study.drawAnswer === "function") {
            window.study.drawAnswer();
            return;
          }
          window.dispatchEvent(new KeyboardEvent("keydown", { key: " " }));
        }

        if (useSubmit && submit) {
          submit.addEventListener("click", () => {
            if (submit.disabled) return;
            showAnswer();
          });
        }

        // --- Desktop keyboard shortcuts (avoid Anki's reserved keys) ---
        if (!isiOS && !isAndroid) {
          const pickByKey = (k) => {
            if (k === "n") return choices.querySelector('[data-key="nd"]');
            if (k === "c") return choices.querySelector('[data-key="dt"]');
            if (k === "p") return choices.querySelector('[data-key="dp"]');
            return null;
          };

          const onKey = (e) => {
            // ignore when typing in an input/textarea/select
            const t = e.target;
            if (t && /input|textarea|select/i.test(t.tagName)) return;

            const key = e.key.toLowerCase();
            const btn = pickByKey(key);
            if (btn) {
              e.preventDefault();
              e.stopPropagation();
              setActive(btn);
              updateSubmitState();
              return;
            }

            if (key === "enter" && useSubmit && submit && !submit.disabled) {
              e.preventDefault();
              e.stopPropagation();
              showAnswer(); // optional: you can rely on Anki's default Enter too
            }
          };

          // Capture early so Anki doesn't swallow them
          window.addEventListener("keydown", onKey, true);
        }
        updateSubmitState();
      })();
    </script>
  </body>
</html>
