/* ============================================================
   menu.js - Popup menu + modal pages: Share, Instructions,
   Mute toggle, Keyboard map, Other Games, About Us.
   ============================================================ */
(function (ST) {
  "use strict";

  var menu, toggle, modal, modalBody;

  function openMenu(open) {
    menu.classList.toggle("is-open", open);
    toggle.setAttribute("aria-expanded", open ? "true" : "false");
    menu.setAttribute("aria-hidden", open ? "false" : "true");
  }

  function openModal(html) {
    modalBody.innerHTML = html;
    modal.classList.add("is-open");
    modal.setAttribute("aria-hidden", "false");
  }
  function closeModal() {
    modal.classList.remove("is-open");
    modal.setAttribute("aria-hidden", "true");
  }

  /* ---------- page content ---------- */
  var Pages = {
    instructions: function () {
      return '<h2>How to Play</h2>' +
        '<p>You are <b>Snoopy</b>, waiting by the tree with your racket. ' +
        'Charlie Brown serves tennis balls at you &mdash; high, middle or low.</p>' +
        '<h3>Goal</h3>' +
        '<ul>' +
        '<li>Move Snoopy <b>UP</b> / <b>DOWN</b> the tree to line up with each ball.</li>' +
        '<li>Press <b>HIT</b> just as the ball reaches Snoopy&rsquo;s face to return it.</li>' +
        '<li>Charlie&rsquo;s balls score <b>2</b> points, Lucy&rsquo;s smashes score <b>3</b>.</li>' +
        '<li>Miss a ball and you earn a broken bottle. <b>Three misses = game over.</b></li>' +
        '</ul>' +
        '<h3>Tips</h3>' +
        '<ul>' +
        '<li>Time the swing perfectly &mdash; whiff and Snoopy is frozen until the racket resets.</li>' +
        '<li>Lucy sometimes returns your shot at <b>twice the speed</b>.</li>' +
        '<li>Every 100 points the game briefly slows down.</li>' +
        '<li>Reach 200 or 500 points (each 1000-point cycle) to clear misses; with none, ' +
        'you enter <b>CHANCE TIME</b> where balls are worth 5 and 6 points!</li>' +
        '</ul>' +
        '<h3>Start</h3>' +
        '<p>Press <b>GAME A</b> (easier) or <b>GAME B</b> (more balls, faster) to play.</p>';
    },
    keyboard: function () {
      return '<h2>Keyboard</h2>' +
        '<table>' +
        '<tr><td><b>Move Up</b></td><td><kbd>&uarr;</kbd> or <kbd>W</kbd></td></tr>' +
        '<tr><td><b>Move Down</b></td><td><kbd>&darr;</kbd> or <kbd>S</kbd></td></tr>' +
        '<tr><td><b>Hit / Return</b></td><td><kbd>Space</kbd> <kbd>Enter</kbd> <kbd>J</kbd> <kbd>&larr;</kbd></td></tr>' +
        '<tr><td><b>Game A</b></td><td><kbd>A</kbd> or <kbd>1</kbd></td></tr>' +
        '<tr><td><b>Game B</b></td><td><kbd>B</kbd> or <kbd>2</kbd></td></tr>' +
        '</table>' +
        '<p style="margin-top:16px;color:#666">On touch devices, use the red on-screen ' +
        'HIT / UP / DOWN buttons and the grey GAME A / GAME B buttons.</p>';
    },
    other: function () {
      return '<h2>Other Games</h2>' +
        '<p>We may release more retro game tributes - stay tuned</p>' +
        '<p style="color:#666">Check back at <b>snoopytennis.com</b> for news.</p>';
    },
    about: function () {
      return '<h2>About Us</h2>' +
        '<p>This is a lovingly recreated, playable tribute to Nintendo&rsquo;s 1982 ' +
        '<b>Game &amp; Watch Snoopy Tennis</b> (model SP-30) from the Wide Screen series.</p>' +
        '<p>Every character and animation is drawn live in your browser with the HTML5 ' +
        'canvas &mdash; no sprite images &mdash; to keep it crisp at any screen size and on ' +
        'any device.</p>' +
        '<p>Built as a homage for fans of classic handheld gaming. Snoopy and the Peanuts ' +
        'characters are &copy; Peanuts Worldwide LLC. This project is a non-commercial fan ' +
        'recreation and is not affiliated with Nintendo or Peanuts Worldwide.</p>' +
        '<p>Contact us at <a href="mailto:admin@snoopytennis.com">admin@snoopytennis.com</a></p>' +
        '<p>Built with Claude Code</p>' +
        '<p style="color:#666">snoopytennis.com</p>';
    }
  };

  /* ---------- actions ---------- */
  function share() {
    var data = {
      title: "Snoopy Tennis - Game & Watch",
      text: "Play a faithful browser replica of Nintendo's 1982 Snoopy Tennis!",
      url: location.href
    };
    if (navigator.share) {
      navigator.share(data).catch(function (e) { console.log("[share] cancelled", e); });
      return;
    }
    openModal(
      '<h2>Share</h2>' +
      '<p>Share Snoopy Tennis with a friend:</p>' +
      '<p><b>' + location.href + '</b></p>' +
      '<div class="share-row">' +
      '<button data-copy>Copy link</button>' +
      '<a class="share-a" target="_blank" rel="noopener" href="https://twitter.com/intent/tweet?text=' +
        encodeURIComponent(data.text) + '&url=' + encodeURIComponent(data.url) + '"><button>Share on X</button></a>' +
      '<a class="share-a" target="_blank" rel="noopener" href="https://www.facebook.com/sharer/sharer.php?u=' +
        encodeURIComponent(data.url) + '"><button>Facebook</button></a>' +
      '</div>'
    );
    var copyBtn = modalBody.querySelector("[data-copy]");
    if (copyBtn) copyBtn.addEventListener("click", function () {
      var done = function () { copyBtn.textContent = "Copied!"; };
      if (navigator.clipboard) navigator.clipboard.writeText(location.href).then(done).catch(function () { fallbackCopy(done); });
      else fallbackCopy(done);
    });
  }
  function fallbackCopy(cb) {
    try {
      var ta = document.createElement("textarea");
      ta.value = location.href; document.body.appendChild(ta); ta.select();
      document.execCommand("copy"); document.body.removeChild(ta); cb();
    } catch (e) { console.warn("[share] copy failed", e); }
  }

  function toggleMute() {
    var muted = !ST.Sound.isMuted();
    ST.Sound.setMuted(muted);
    try { localStorage.setItem("st-muted", muted ? "1" : "0"); } catch (e) {}
    updateMuteLabel();
  }
  function updateMuteLabel() {
    var item = menu.querySelector('[data-action="mute"]');
    if (item) item.textContent = ST.Sound.isMuted() ? "🔇 Sound: Off" : "🔊 Sound: On";
  }

  var actions = {
    share: share,
    instructions: function () { openModal(Pages.instructions()); },
    mute: toggleMute,
    keyboard: function () { openModal(Pages.keyboard()); },
    other: function () { openModal(Pages.other()); },
    about: function () { openModal(Pages.about()); }
  };

  function init() {
    menu = document.getElementById("popup-menu");
    toggle = document.getElementById("menu-toggle");
    modal = document.getElementById("modal");
    modalBody = modal.querySelector(".modal-body");

    toggle.addEventListener("click", function () {
      openMenu(!menu.classList.contains("is-open"));
    });

    menu.querySelectorAll(".menu-item").forEach(function (item) {
      item.addEventListener("click", function () {
        ST.Sound.ui();
        var act = item.getAttribute("data-action");
        openMenu(false);
        if (actions[act]) actions[act]();
      });
    });

    modal.querySelector(".modal-close").addEventListener("click", closeModal);
    modal.addEventListener("click", function (e) { if (e.target === modal) closeModal(); });
    document.addEventListener("keydown", function (e) {
      if (e.key === "Escape") { closeModal(); openMenu(false); }
    });
    // close menu on outside click
    document.addEventListener("pointerdown", function (e) {
      if (menu.classList.contains("is-open") && !menu.contains(e.target) && e.target !== toggle && !toggle.contains(e.target)) {
        openMenu(false);
      }
    });

    // restore mute pref
    try { if (localStorage.getItem("st-muted") === "1") ST.Sound.setMuted(true); } catch (e) {}
    updateMuteLabel();
  }

  ST.Menu = { init: init };
})(window.ST = window.ST || {});
