/* 几何习作 · 动态作品集 —— 交互逻辑（无外部依赖） */
(function () {
  "use strict";

  var works = window.WORKS || [];
  var gallery = document.getElementById("gallery");
  var lightbox = document.getElementById("lightbox");
  var lbImage = document.getElementById("lb-image");
  var lbTitle = document.getElementById("lb-title");
  var lbId = document.getElementById("lb-id");
  var lbCategory = document.getElementById("lb-category");
  var lbDescription = document.getElementById("lb-description");
  var lbSpec = document.getElementById("lb-spec");
  var filterStatus = document.getElementById("filter-status");
  var motionToggle = document.getElementById("motion-toggle");

  var currentFilter = "all";
  var lastFocusedCard = null;
  var savedScrollY = 0;
  var motionPaused = false;

  var reduceMotionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");

  /* ---------- 渲染作品卡片 ---------- */

  function createCard(work, index) {
    var card = document.createElement("article");
    card.className = "card" + (work.transparent ? " card--transparent" : "");
    card.setAttribute("tabindex", "0");
    card.setAttribute("role", "button");
    card.setAttribute("aria-label", work.title + "，" + work.category + "，点击查看大图与说明");
    card.dataset.id = work.id;
    card.dataset.category = work.category;
    card.style.setProperty("--enter-delay", (index * 55) + "ms");

    var thumb = document.createElement("div");
    thumb.className = "card-thumb";

    var img = document.createElement("img");
    img.src = work.file;
    img.alt = work.title + "（" + work.id + "）";
    img.width = work.width;
    img.height = work.height;
    img.loading = "lazy";
    img.decoding = "async";
    thumb.appendChild(img);

    var body = document.createElement("div");
    body.className = "card-body";

    var titleRow = document.createElement("div");
    titleRow.className = "card-title-row";
    var h2 = document.createElement("h2");
    h2.className = "card-title";
    h2.textContent = work.title;
    var tag = document.createElement("span");
    tag.className = "card-tag";
    tag.textContent = work.category;
    titleRow.appendChild(h2);
    titleRow.appendChild(tag);

    var meta = document.createElement("p");
    meta.className = "card-meta";
    meta.textContent = work.id + " · " + work.width + "×" + work.height;

    body.appendChild(titleRow);
    body.appendChild(meta);
    card.appendChild(thumb);
    card.appendChild(body);

    card.addEventListener("click", function () { openLightbox(work, card); });
    card.addEventListener("keydown", function (e) {
      if (e.key === "Enter" || e.key === " " || e.key === "Spacebar") {
        e.preventDefault();
        openLightbox(work, card);
      }
    });
    return card;
  }

  function renderGallery() {
    var frag = document.createDocumentFragment();
    works.forEach(function (work, i) { frag.appendChild(createCard(work, i)); });
    gallery.appendChild(frag);
  }

  /* ---------- 筛选 ---------- */

  function applyFilter(filter) {
    currentFilter = filter;
    var visibleCount = 0;
    var cards = gallery.querySelectorAll(".card");
    cards.forEach(function (card) {
      var show = filter === "all" || card.dataset.category === filter;
      card.classList.toggle("is-hidden", !show);
      if (show) visibleCount++;
    });

    document.querySelectorAll(".filter-btn").forEach(function (btn) {
      var active = btn.dataset.filter === filter;
      btn.classList.toggle("is-active", active);
      btn.setAttribute("aria-pressed", active ? "true" : "false");
    });

    filterStatus.textContent = "当前显示 " + visibleCount + " 件作品" +
      (filter === "all" ? "" : "（类别：" + filter + "）");
  }

  document.querySelectorAll(".filter-btn").forEach(function (btn) {
    btn.addEventListener("click", function () {
      applyFilter(btn.dataset.filter);
    });
  });

  /* ---------- 灯箱：大图 + 清单说明 ---------- */

  function openLightbox(work, card) {
    lastFocusedCard = card;
    savedScrollY = window.scrollY;

    lbImage.src = work.file;
    lbImage.alt = work.title + "（" + work.id + "）大图";
    lbImage.width = work.width;
    lbImage.height = work.height;
    lbTitle.textContent = work.title;
    lbId.textContent = work.id;
    lbCategory.textContent = work.category;
    lbCategory.className = "lightbox-category tag-" + (work.category === "构成" ? "form" : "color");
    lbDescription.textContent = work.description;
    lbSpec.textContent = "尺寸 " + work.width + " × " + work.height +
      " · 文件 " + work.file.split("/").pop() +
      (work.transparent ? " · 透明背景（展示于深色画板）" : " · 深色背景");

    /* 锁定背景滚动并保持原位置 */
    document.body.style.position = "fixed";
    document.body.style.top = "-" + savedScrollY + "px";
    document.body.style.left = "0";
    document.body.style.right = "0";
    document.body.style.width = "100%";

    lightbox.hidden = false;
    requestAnimationFrame(function () {
      lightbox.classList.add("is-open");
    });
    lightbox.querySelector(".lightbox-close").focus();
    document.addEventListener("keydown", onLightboxKeydown);
  }

  function closeLightbox() {
    lightbox.classList.remove("is-open");
    lightbox.hidden = true;
    document.removeEventListener("keydown", onLightboxKeydown);

    /* 恢复滚动位置与焦点，回到原处 */
    document.body.style.position = "";
    document.body.style.top = "";
    document.body.style.left = "";
    document.body.style.right = "";
    document.body.style.width = "";
    window.scrollTo(0, savedScrollY);
    if (lastFocusedCard) {
      lastFocusedCard.focus({ preventScroll: true });
    }
  }

  function onLightboxKeydown(e) {
    if (e.key === "Escape") {
      e.preventDefault();
      closeLightbox();
    } else if (e.key === "Tab") {
      /* 简易焦点圈定：面板内只有关闭按钮可聚焦 */
      e.preventDefault();
      lightbox.querySelector(".lightbox-close").focus();
    }
  }

  lightbox.addEventListener("click", function (e) {
    if (e.target.hasAttribute("data-close")) {
      closeLightbox();
    }
  });

  /* ---------- 动画暂停控制 ---------- */

  function motionDisabled() {
    return motionPaused || reduceMotionQuery.matches;
  }

  function updateMotionUI() {
    var disabled = motionDisabled();
    document.body.classList.toggle("motion-paused", motionPaused);
    document.body.classList.toggle("motion-reduced", reduceMotionQuery.matches);
    motionToggle.setAttribute("aria-pressed", motionPaused ? "true" : "false");
    motionToggle.querySelector(".motion-icon").textContent = motionPaused ? "▶" : "❚❚";
    motionToggle.querySelector(".motion-label").textContent = motionPaused ? "继续动画" : "暂停动画";
    if (disabled) {
      stopOrbs();
    } else {
      startOrbs();
    }
  }

  motionToggle.addEventListener("click", function () {
    motionPaused = !motionPaused;
    updateMotionUI();
  });

  if (typeof reduceMotionQuery.addEventListener === "function") {
    reduceMotionQuery.addEventListener("change", updateMotionUI);
  } else if (typeof reduceMotionQuery.addListener === "function") {
    reduceMotionQuery.addListener(updateMotionUI);
  }

  /* ---------- 背景球体粒子（克制、可暂停） ---------- */

  var canvas = document.getElementById("bg-canvas");
  var ctx = canvas.getContext("2d");
  var orbs = [];
  var orbRafId = 0;
  var lastFrameTime = 0;

  function resizeCanvas() {
    var dpr = Math.min(window.devicePixelRatio || 1, 2);
    canvas.width = Math.floor(window.innerWidth * dpr);
    canvas.height = Math.floor(window.innerHeight * dpr);
    canvas.style.width = window.innerWidth + "px";
    canvas.style.height = window.innerHeight + "px";
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  }

  function initOrbs() {
    orbs = [];
    var palette = ["#3a86ff", "#8338ec", "#ff006e", "#fb5607", "#ffbe0b"];
    var count = window.innerWidth < 640 ? 10 : 16;
    for (var i = 0; i < count; i++) {
      orbs.push({
        x: Math.random() * window.innerWidth,
        y: Math.random() * window.innerHeight,
        r: 40 + Math.random() * 110,
        color: palette[i % palette.length],
        vx: (Math.random() - 0.5) * 0.12,
        vy: (Math.random() - 0.5) * 0.12,
        alpha: 0.05 + Math.random() * 0.07
      });
    }
  }

  function drawOrbs() {
    ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
    for (var i = 0; i < orbs.length; i++) {
      var o = orbs[i];
      var g = ctx.createRadialGradient(o.x, o.y, 0, o.x, o.y, o.r);
      g.addColorStop(0, hexToRgba(o.color, o.alpha));
      g.addColorStop(1, hexToRgba(o.color, 0));
      ctx.fillStyle = g;
      ctx.beginPath();
      ctx.arc(o.x, o.y, o.r, 0, Math.PI * 2);
      ctx.fill();
    }
  }

  function hexToRgba(hex, a) {
    var n = parseInt(hex.slice(1), 16);
    return "rgba(" + ((n >> 16) & 255) + "," + ((n >> 8) & 255) + "," + (n & 255) + "," + a + ")";
  }

  function stepOrbs(now) {
    if (motionDisabled()) { orbRafId = 0; return; }
    /* 低帧率（约 30fps）运动，保持克制 */
    if (now - lastFrameTime < 33) {
      orbRafId = requestAnimationFrame(stepOrbs);
      return;
    }
    lastFrameTime = now;
    for (var i = 0; i < orbs.length; i++) {
      var o = orbs[i];
      o.x += o.vx;
      o.y += o.vy;
      if (o.x < -o.r) o.x = window.innerWidth + o.r;
      if (o.x > window.innerWidth + o.r) o.x = -o.r;
      if (o.y < -o.r) o.y = window.innerHeight + o.r;
      if (o.y > window.innerHeight + o.r) o.y = -o.r;
    }
    drawOrbs();
    orbRafId = requestAnimationFrame(stepOrbs);
  }

  function startOrbs() {
    if (orbRafId || motionDisabled()) return;
    lastFrameTime = 0;
    orbRafId = requestAnimationFrame(stepOrbs);
  }

  function stopOrbs() {
    if (orbRafId) {
      cancelAnimationFrame(orbRafId);
      orbRafId = 0;
    }
    /* 暂停时清空画布，避免残留 */
    ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
  }

  var resizeTimer = 0;
  window.addEventListener("resize", function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function () {
      resizeCanvas();
      initOrbs();
      if (!motionDisabled()) drawOrbs();
    }, 150);
  });

  /* ---------- 初始化 ---------- */

  renderGallery();
  applyFilter("all");
  resizeCanvas();
  initOrbs();
  updateMotionUI();
  if (!motionDisabled()) drawOrbs();
})();
