Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

30.8 KB
Raw Blame
document.documentElement.classList.add("js");

const SAVED_KEY = "designtaste:saved";
const RANKING_KEY = "designtaste:ranking";
const MOTION_KEY = "designtaste:motion";

/* ---------- Motion preference ---------- */
const reduced = matchMedia("(prefers-reduced-motion: reduce)");
let paused = false;
try {
  paused = localStorage.getItem(MOTION_KEY) === "paused";
} catch {}

const motionButton = document.querySelector("#motion-toggle");
function syncMotion() {
  const isPaused = paused || reduced.matches;
  document.documentElement.classList.toggle("motion-paused", isPaused);
  if (motionButton) {
    motionButton.setAttribute("aria-pressed", String(isPaused));
    motionButton.textContent = reduced.matches
      ? "Reduced motion"
      : paused
        ? "Play scroll"
        : "Pause scroll";
    motionButton.disabled = reduced.matches;
  }
  if (isPaused) {
    document
      .querySelectorAll(".scrolling")
      .forEach((el) => el.classList.remove("scrolling"));
    document.querySelectorAll(".preview-video").forEach((v) => {
      try {
        v.pause();
        v.currentTime = 0;
      } catch {}
      v.closest(".preview")?.classList.remove("video-playing", "video-ready");
    });
    const detailVid = document.querySelector(".detail-video");
    if (detailVid && !detailVid.paused) {
      try {
        detailVid.pause();
      } catch {}
    }
  }
}
syncMotion();
reduced.addEventListener("change", syncMotion);
motionButton?.addEventListener("click", () => {
  paused = !paused;
  try {
    localStorage.setItem(MOTION_KEY, paused ? "paused" : "playing");
  } catch {}
  syncMotion();
});

/* ---------- Saved favorites (browser localStorage, ready for future login sync) ---------- */
function readSaved() {
  try {
    const raw = localStorage.getItem(SAVED_KEY);
    if (!raw) return new Set();
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return new Set(parsed.filter((x) => typeof x === "string" && x));
    }
  } catch {}
  return new Set();
}

let savedSet = readSaved();

function persistSaved() {
  try {
    localStorage.setItem(SAVED_KEY, JSON.stringify([...savedSet]));
  } catch {}
}

function syncSavedUI(animatedId = null) {
  const total = savedSet.size;
  for (const badge of document.querySelectorAll("[data-saved-count]")) {
    badge.textContent = String(total);
    badge.hidden = total === 0;
  }
  for (const btn of document.querySelectorAll("[data-save-id]")) {
    const id = btn.dataset.saveId;
    const isSaved = savedSet.has(id);
    btn.setAttribute("aria-pressed", String(isSaved));
    const cardName =
      btn.closest(".site-card")?.querySelector(".site-name")?.textContent?.replace(/\s*\(opens in a new tab\)\s*$/i, "").trim() ||
      document.querySelector(".detail-title h1")?.textContent?.trim() ||
      id;
    btn.setAttribute(
      "aria-label",
      isSaved ? `Remove ${cardName} from saved` : `Save ${cardName}`,
    );
    const label = btn.querySelector("[data-save-label]");
    if (label) label.textContent = isSaved ? "Saved" : "Save";
    if (animatedId && id === animatedId && isSaved) {
      btn.classList.remove("just-saved");
      void btn.offsetWidth;
      btn.classList.add("just-saved");
    }
  }
}

function readCachedRanking() {
  try {
    const raw = localStorage.getItem(RANKING_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return parsed.filter((x) => typeof x === "string" && x);
    }
  } catch {}
  return [];
}

let globalRank = new Map(readCachedRanking().map((id, i) => [id, i]));

function setGlobalRanking(list) {
  if (!Array.isArray(list)) return;
  const clean = list.filter((x) => typeof x === "string" && x);
  globalRank = new Map(clean.map((id, i) => [id, i]));
  try {
    localStorage.setItem(RANKING_KEY, JSON.stringify(clean));
  } catch {}
}

function syncFavoriteToServer(id, action) {
  if (typeof fetch !== "function") return;
  try {
    fetch("/api/favorites/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, action }),
      keepalive: true,
    }).catch(() => {});
  } catch {}
}

document.addEventListener("click", (e) => {
  const btn = e.target.closest("[data-save-id]");
  if (!btn) return;
  e.preventDefault();
  e.stopPropagation();
  const id = btn.dataset.saveId;
  if (!id) return;
  const adding = !savedSet.has(id);
  if (adding) savedSet.add(id);
  else savedSet.delete(id);
  persistSaved();
  syncSavedUI(id);
  syncFavoriteToServer(id, adding ? "add" : "remove");
  if (typeof onSavedChanged === "function") onSavedChanged();
});

addEventListener("storage", (e) => {
  if (e.key !== SAVED_KEY) return;
  savedSet = readSaved();
  syncSavedUI();
  if (typeof onSavedChanged === "function") onSavedChanged();
});

syncSavedUI();

/* ---------- Hover-to-scroll & real-video previews ---------- */
const cards = [...document.querySelectorAll(".site-card")];
const previews = [...document.querySelectorAll(".preview")];

function measure(a) {
  if (a.dataset.video) {
    a.classList.remove("can-scroll");
    return 0;
  }
  const img = a.querySelector("img");
  if (!img?.naturalWidth) return 0;
  const imgHeight = img.getBoundingClientRect().height;
  const boxHeight = a.clientHeight;
  const travel = Math.max(0, Math.round(imgHeight - boxHeight));
  const scrollable = travel > 24;
  a.classList.toggle("can-scroll", scrollable);
  a.style.setProperty("--travel", scrollable ? `${-travel}px` : "0px");
  a.style.setProperty(
    "--scroll-duration",
    `${Math.min(18, Math.max(3.5, travel / 160)).toFixed(2)}s`,
  );
  return scrollable ? travel : 0;
}

for (const a of previews) {
  const img = a.querySelector("img");
  const videoSrc = a.dataset.video;

  if (videoSrc) {
    let vid = null;
    let rafId = 0;
    let active = false;

    const tickProgress = () => {
      if (!active || !vid) return;
      const pct =
        vid.duration && Number.isFinite(vid.duration)
          ? Math.min(1, Math.max(0, vid.currentTime / vid.duration))
          : 0;
      a.style.setProperty("--video-progress", pct.toFixed(4));
      rafId = requestAnimationFrame(tickProgress);
    };

    const enterVideo = () => {
      if (paused || reduced.matches) return;
      active = true;
      if (!vid) {
        vid = document.createElement("video");
        vid.className = "preview-video";
        vid.muted = true;
        vid.loop = true;
        vid.playsInline = true;
        vid.preload = "auto";
        vid.setAttribute("aria-hidden", "true");
        vid.src = videoSrc;
        vid.addEventListener("playing", () => {
          if (active) a.classList.add("video-ready");
        });
        a.insertBefore(vid, a.querySelector(".scroll-progress"));
      }
      a.classList.add("video-playing");
      try {
        const p = vid.play();
        if (p && typeof p.catch === "function") p.catch(() => {});
      } catch {}
      cancelAnimationFrame(rafId);
      rafId = requestAnimationFrame(tickProgress);
    };

    const leaveVideo = () => {
      active = false;
      cancelAnimationFrame(rafId);
      a.classList.remove("video-playing", "video-ready");
      a.style.setProperty("--video-progress", "0");
      if (vid) {
        try {
          vid.pause();
          vid.currentTime = 0;
        } catch {}
      }
    };

    a.addEventListener("pointerenter", (e) => {
      if (e.pointerType !== "touch") enterVideo();
    });
    a.addEventListener("pointerleave", leaveVideo);
    a.addEventListener("focus", enterVideo);
    a.addEventListener("blur", leaveVideo);
    img.addEventListener("error", () => {
      a.classList.add("image-unavailable");
      img.alt = "Preview unavailable — visit the website";
    });
    continue;
  }

  img.addEventListener("load", () => measure(a));
  if (img.complete) measure(a);

  const enter = () => {
    if (paused || reduced.matches) return;
    const travel = measure(a);
    if (travel > 24) a.classList.add("scrolling");
  };
  const leave = () => a.classList.remove("scrolling");

  a.addEventListener("pointerenter", (e) => {
    if (e.pointerType !== "touch") enter();
  });
  a.addEventListener("pointerleave", leave);
  a.addEventListener("focus", enter);
  a.addEventListener("blur", leave);
  img.addEventListener("error", () => {
    a.classList.add("image-unavailable");
    img.alt = "Preview unavailable — visit the website";
  });
}

/* ---------- Detail page recorded scroll video player ---------- */
const detailMedia = document.querySelector("[data-detail-media]");
if (detailMedia) {
  const detailVideo = detailMedia.querySelector(".detail-video");
  const detailToggle = detailMedia.querySelector("[data-detail-video-toggle]");
  const detailProgress = detailMedia.querySelector(".detail-video-progress");
  if (detailVideo && detailToggle) {
    let detailRaf = 0;
    const syncDetailBtn = () => {
      const playing = !detailVideo.paused && !detailVideo.ended;
      detailToggle.textContent = playing ? "Pause" : "Play scroll";
      detailToggle.setAttribute("aria-pressed", String(!playing));
      detailToggle.setAttribute(
        "aria-label",
        playing ? "Pause scroll preview" : "Play scroll preview",
      );
      detailMedia.classList.toggle("is-playing", playing);
    };
    const tickDetail = () => {
      if (detailProgress && detailVideo.duration) {
        const pct = Math.min(
          1,
          Math.max(0, detailVideo.currentTime / detailVideo.duration),
        );
        detailProgress.style.transform = `scaleX(${pct.toFixed(4)})`;
      }
      if (!detailVideo.paused && !detailVideo.ended) {
        detailRaf = requestAnimationFrame(tickDetail);
      }
    };
    detailVideo.addEventListener("play", () => {
      syncDetailBtn();
      cancelAnimationFrame(detailRaf);
      detailRaf = requestAnimationFrame(tickDetail);
    });
    detailVideo.addEventListener("pause", () => {
      syncDetailBtn();
      cancelAnimationFrame(detailRaf);
    });
    detailToggle.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (detailVideo.paused) {
        const p = detailVideo.play();
        if (p && typeof p.catch === "function") p.catch(() => {});
      } else {
        detailVideo.pause();
      }
    });
    if (!paused && !reduced.matches) {
      try {
        const p = detailVideo.play();
        if (p && typeof p.catch === "function") p.catch(() => syncDetailBtn());
      } catch {}
    }
    syncDetailBtn();
  }
}

let resizeFrame;
addEventListener("resize", () => {
  cancelAnimationFrame(resizeFrame);
  resizeFrame = requestAnimationFrame(() => previews.forEach(measure));
});

/* ---------- Entry reveal (desktop hover devices only to keep mobile Safari memory lean) ---------- */
if (
  "IntersectionObserver" in window &&
  matchMedia("(hover: hover) and (min-width: 760px)").matches
) {
  const observer = new IntersectionObserver(
    (entries) => {
      for (const { target, isIntersecting } of entries) {
        if (isIntersecting) {
          target.classList.remove("reveal-pending");
          target.classList.add("reveal-ready");
          observer.unobserve(target);
        }
      }
    },
    { rootMargin: "0px 0px 40px 0px", threshold: 0.05 },
  );
  if (!reduced.matches && !paused) {
    for (const c of cards) {
      if (c.getBoundingClientRect().top > innerHeight + 80) {
        c.classList.add("reveal-pending");
        observer.observe(c);
      }
    }
  }
}

/* ---------- Search, Category, Saved filter & Sorting ---------- */
let onSavedChanged = null;

const searchInputs = [
  document.querySelector("#search"),
  document.querySelector("#search-mobile"),
].filter(Boolean);
const sort = document.querySelector("#sort");
const count = document.querySelector("#result-count");
const empty = document.querySelector("#empty");
const emptyTitle = document.querySelector("#empty-title");
const emptyCopy = document.querySelector("#empty-copy");
const emptyReset = document.querySelector("#empty-reset");
const savedBrowserNote = document.querySelector("#saved-browser-note");
const loadMoreWrap = document.querySelector("#load-more-wrap");
const loadMoreBtn = document.querySelector("#load-more");
const loadSentinel = document.querySelector("#load-sentinel");
const galleryEl = document.querySelector(".gallery");
const shareListBar = document.querySelector("#share-list-bar");
const shareListForm = document.querySelector("#share-list-form");
const shareListTitle = document.querySelector("#share-list-title");
const shareListBtn = document.querySelector("#share-list-btn");
const shareListResult = document.querySelector("#share-list-result");
const sharedListBanner = document.querySelector("#shared-list-banner");
const sharedListTitleEl = document.querySelector("#shared-list-title");
const sharedListIdEl = document.querySelector("#shared-list-id");
const sharedListMetaEl = document.querySelector("#shared-list-meta");
const sharedListSaveAll = document.querySelector("#shared-list-save-all");
const sharedListCopyPrompt = document.querySelector("#shared-list-copy-prompt");
const sharedListExit = document.querySelector("#shared-list-exit");
const filters = [...document.querySelectorAll("[data-filter]")];
const savedFilterLinks = [
  ...document.querySelectorAll("[data-saved-filter], [data-nav-saved]"),
];
const toolbarH1 = document.querySelector(".toolbar-title h1");

if (searchInputs.length && sort) {
  const PAGE_SIZE = 36;
  let visibleLimit = PAGE_SIZE;
  let totalMatched = cards.length;
  let category =
    filters.find((x) => x.hasAttribute("aria-current"))?.dataset.filter || "";
  let savedOnly = false;
  let activeList = null; // { id, title, ids: string[], set: Set, order: Map }
  let activeListError = "";
  let query = "";
  const initialOrder = new Map(cards.map((c, i) => [c, i]));

  function syncSearchValues(val, source = null) {
    query = val;
    for (const input of searchInputs) {
      if (input !== source && input.value !== val) input.value = val;
    }
  }

  function apply(updateURL = true, resetLimit = false) {
    if (resetLimit) visibleLimit = PAGE_SIZE;
    const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
    const orderedCards = galleryEl
      ? [...galleryEl.querySelectorAll(".site-card")]
      : cards;
    let matched = 0;

    for (const c of orderedCards) {
      const hiddenByList = activeList && !activeList.set.has(c.dataset.id);
      const hiddenBySaved =
        !activeList && savedOnly && !savedSet.has(c.dataset.id);
      const hiddenByCat =
        !activeList && !savedOnly && category && c.dataset.category !== category;
      const hiddenByQuery = !words.every((w) => c.dataset.search.includes(w));
      const matches = !(
        hiddenByList ||
        hiddenBySaved ||
        hiddenByCat ||
        hiddenByQuery
      );
      if (matches) {
        matched++;
        const withinPage = matched <= visibleLimit;
        c.hidden = !withinPage;
        if (withinPage && updateURL) {
          c.classList.remove("reveal-pending");
          c.classList.add("reveal-ready");
        }
      } else {
        c.hidden = true;
      }
    }

    totalMatched = matched;

    if (loadMoreWrap && loadMoreBtn) {
      const remaining = Math.max(0, matched - visibleLimit);
      loadMoreWrap.hidden = remaining === 0;
      if (remaining > 0) {
        loadMoreBtn.textContent = `Load more (${remaining} remaining)`;
      }
    }

    if (count) {
      count.textContent = `${matched}`;
    }
    if (toolbarH1) {
      toolbarH1.textContent = activeList
        ? activeList.title || "Shared list"
        : savedOnly
          ? "Saved"
          : category || "Websites";
    }
    if (savedBrowserNote) {
      savedBrowserNote.hidden = !savedOnly || Boolean(activeList);
    }
    if (shareListBar) {
      shareListBar.hidden = !(savedOnly && !activeList && savedSet.size > 0);
    }
    if (sharedListBanner) {
      sharedListBanner.hidden = !activeList;
      if (activeList) {
        if (sharedListTitleEl) {
          sharedListTitleEl.textContent = activeList.title || "Shared list";
        }
        if (sharedListIdEl) sharedListIdEl.textContent = activeList.id;
        if (sharedListMetaEl) {
          sharedListMetaEl.textContent = `${activeList.ids.length} saved reference${activeList.ids.length === 1 ? "" : "s"} — pass ID "${activeList.id}" to your AI agent via the DesignTaste MCP.`;
        }
        if (sharedListCopyPrompt) {
          sharedListCopyPrompt.dataset.copyText = `Use my DesignTaste saved list "${activeList.id}" via the DesignTaste MCP (https://designtaste.wtf/api/mcp/) as visual direction.`;
        }
      }
    }

    if (empty) {
      empty.hidden = matched !== 0;
      if (matched === 0) {
        if (activeListError) {
          emptyTitle.textContent = "Shared list not found.";
          emptyCopy.textContent = activeListError;
        } else if (savedOnly && !words.length) {
          emptyTitle.textContent = "No saved websites yet.";
          emptyCopy.textContent =
            "Tap the heart button on any design to save it here in your browser.";
        } else {
          emptyTitle.textContent = "No matching websites.";
          emptyCopy.textContent =
            "Try a different keyword, style, or category.";
        }
      }
    }

    for (const a of filters) {
      if (!savedOnly && !activeList && a.dataset.filter === category) {
        a.setAttribute("aria-current", "page");
      } else {
        a.removeAttribute("aria-current");
      }
    }

    for (const link of savedFilterLinks) {
      if (savedOnly && !activeList) {
        link.setAttribute("aria-current", "page");
        link.classList.add("is-active");
      } else {
        link.removeAttribute("aria-current");
        link.classList.remove("is-active");
      }
    }

    if (updateURL) {
      const path =
        savedOnly || activeList
          ? "/"
          : filters
              .find((x) => x.dataset.filter === category)
              ?.getAttribute("href") || "/";
      const url = new URL(path, location.origin);
      if (activeList) url.searchParams.set("list", activeList.id);
      else if (savedOnly) url.searchParams.set("saved", "1");
      if (query.trim()) url.searchParams.set("q", query.trim());
      if (sort.value !== "popular") url.searchParams.set("sort", sort.value);
      history.replaceState(null, "", url.pathname + url.search);
    }
  }

  function popularScore(card) {
    const id = card.dataset.id;
    if (activeList && activeList.order.has(id)) {
      return activeList.order.get(id);
    }
    if (globalRank.has(id)) return globalRank.get(id);
    if (savedSet.has(id)) return 1000000 + initialOrder.get(card);
    return 2000000 + initialOrder.get(card);
  }

  function order() {
    const sorted = [...cards].sort((a, b) =>
      sort.value === "az"
        ? a
            .querySelector(".site-name")
            .textContent.localeCompare(
              b.querySelector(".site-name").textContent,
            )
        : sort.value === "newest"
          ? b.dataset.date.localeCompare(a.dataset.date) ||
            initialOrder.get(a) - initialOrder.get(b)
          : sort.value === "curated"
            ? initialOrder.get(a) - initialOrder.get(b)
            : popularScore(a) - popularScore(b),
    );
    const parent = document.querySelector(".gallery");
    sorted.forEach((c) => parent.append(c));
  }

  async function loadSharedList(listId) {
    activeListError = "";
    if (!/^dt_[a-z0-9]{6,16}$/i.test(listId) || typeof fetch !== "function") {
      activeList = { id: listId, title: "", ids: [], set: new Set(), order: new Map() };
      activeListError = "Check that the list ID starts with dt_ and try again.";
      apply(false, true);
      return;
    }
    try {
      const res = await fetch(`/api/lists/?id=${encodeURIComponent(listId)}`, {
        headers: { Accept: "application/json" },
      });
      const json = await res.json().catch(() => null);
      if (!res.ok || !json?.ok || !json.list) {
        activeList = { id: listId, title: "", ids: [], set: new Set(), order: new Map() };
        activeListError = json?.message || "This shared list could not be found.";
        apply(false, true);
        return;
      }
      const ids = Array.isArray(json.list.ids) ? json.list.ids : [];
      activeList = {
        id: json.list.id,
        title: json.list.title || "",
        ids,
        set: new Set(ids),
        order: new Map(ids.map((id, i) => [id, i])),
      };
      order();
      apply(false, true);
    } catch {
      activeList = { id: listId, title: "", ids: [], set: new Set(), order: new Map() };
      activeListError = "Could not load this shared list right now.";
      apply(false, true);
    }
  }

  function restore() {
    const params = new URLSearchParams(location.search);
    const listParam = (params.get("list") || "").trim().toLowerCase();
    activeList = null;
    activeListError = "";
    savedOnly = !listParam && params.get("saved") === "1";
    category =
      savedOnly || listParam
        ? ""
        : filters.find((a) => new URL(a.href).pathname === location.pathname)
            ?.dataset.filter || "";
    syncSearchValues(params.get("q") || "");
    sort.value = ["popular", "curated", "az", "newest"].includes(
      params.get("sort"),
    )
      ? params.get("sort")
      : "popular";
    order();
    apply(false);
    if (listParam) loadSharedList(listParam);
  }

  onSavedChanged = () => {
    if (shareListResult && savedOnly) shareListResult.hidden = true;
    if (savedOnly) apply(false);
  };

  shareListForm?.addEventListener("submit", async (e) => {
    e.preventDefault();
    if (!savedSet.size || !shareListBtn || !shareListResult) return;
    shareListBtn.disabled = true;
    const prev = shareListBtn.textContent;
    shareListBtn.textContent = "Creating…";
    shareListResult.hidden = true;
    try {
      const res = await fetch("/api/lists/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ids: [...savedSet],
          title: shareListTitle?.value?.trim() || "",
        }),
      });
      const json = await res.json().catch(() => ({}));
      shareListResult.hidden = false;
      shareListResult.replaceChildren();
      if (res.ok && json.ok) {
        shareListResult.className = "share-list-result is-success";
        const pill = document.createElement("code");
        pill.className = "list-id-pill";
        pill.textContent = json.id;
        shareListResult.append(pill);

        const mkCopy = (label, text) => {
          const b = document.createElement("button");
          b.type = "button";
          b.className = "btn btn-ghost btn-sm";
          b.dataset.copyText = text;
          b.textContent = label;
          return b;
        };
        shareListResult.append(
          mkCopy("Copy ID", json.id),
          mkCopy("Copy link", json.url),
          mkCopy("Copy agent prompt", json.mcpPrompt),
        );
      } else {
        shareListResult.className = "share-list-result is-error";
        shareListResult.textContent =
          json.message || "Could not create shareable list right now.";
      }
    } catch {
      shareListResult.hidden = false;
      shareListResult.className = "share-list-result is-error";
      shareListResult.textContent =
        "Network error creating shareable list. Please try again.";
    } finally {
      shareListBtn.disabled = false;
      shareListBtn.textContent = prev;
    }
  });

  sharedListSaveAll?.addEventListener("click", () => {
    if (!activeList?.ids?.length) return;
    for (const id of activeList.ids) {
      if (!savedSet.has(id)) {
        savedSet.add(id);
        syncFavoriteToServer(id, "add");
      }
    }
    persistSaved();
    syncSavedUI();
    sharedListSaveAll.textContent = "Saved all!";
    setTimeout(() => {
      sharedListSaveAll.textContent = "Save all locally";
    }, 1800);
  });

  sharedListExit?.addEventListener("click", (e) => {
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    e.preventDefault();
    activeList = null;
    activeListError = "";
    savedOnly = false;
    category = "";
    order();
    apply(true, true);
  });

  function loadMore() {
    if (visibleLimit >= totalMatched) return;
    visibleLimit += PAGE_SIZE;
    apply(false, false);
  }

  loadMoreBtn?.addEventListener("click", loadMore);

  if ("IntersectionObserver" in window && loadSentinel) {
    const pageObserver = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) loadMore();
      },
      { rootMargin: "700px 0px" },
    );
    pageObserver.observe(loadSentinel);
  }

  for (const input of searchInputs) {
    input.form?.addEventListener("submit", (e) => e.preventDefault());
    input.addEventListener("input", () => {
      syncSearchValues(input.value, input);
      apply(true, true);
    });
  }

  sort.addEventListener("change", () => {
    order();
    apply(true, true);
  });

  for (const a of filters) {
    a.addEventListener("click", (e) => {
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
      e.preventDefault();
      activeList = null;
      activeListError = "";
      savedOnly = false;
      category = a.dataset.filter;
      apply(true, true);
    });
  }

  for (const link of savedFilterLinks) {
    link.addEventListener("click", (e) => {
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
      e.preventDefault();
      activeList = null;
      activeListError = "";
      savedOnly = !savedOnly;
      if (savedOnly) category = "";
      apply(true, true);
    });
  }

  emptyReset?.addEventListener("click", (e) => {
    e.preventDefault();
    activeList = null;
    activeListError = "";
    savedOnly = false;
    category = "";
    syncSearchValues("");
    sort.value = "popular";
    order();
    apply(true, true);
  });

  addEventListener("popstate", restore);

  addEventListener("keydown", (e) => {
    if (
      e.key === "/" &&
      !e.ctrlKey &&
      !e.metaKey &&
      !e.altKey &&
      !/INPUT|TEXTAREA|SELECT/.test(document.activeElement?.tagName)
    ) {
      e.preventDefault();
      const target =
        searchInputs.find((el) => el.offsetParent !== null) || searchInputs[0];
      target?.focus();
    }
  });

  restore();

  if (typeof fetch === "function") {
    fetch("/api/favorites/", { headers: { Accept: "application/json" } })
      .then((res) => (res.ok ? res.json() : null))
      .then((json) => {
        if (!json || !Array.isArray(json.ranking)) return;
        setGlobalRanking(json.ranking);
        if (
          sort.value === "popular" &&
          (window.scrollY || 0) < 160 &&
          !document.querySelector(".preview.scrolling")
        ) {
          order();
          apply(false);
        }
      })
      .catch(() => {});
  }
}

/* ---------- Clipboard Copy Helper ---------- */
document.addEventListener("click", async (e) => {
  const btn = e.target.closest("[data-copy-text]");
  if (!btn) return;
  const text = btn.dataset.copyText;
  if (!text) return;
  try {
    await navigator.clipboard.writeText(text);
    const prev = btn.textContent;
    btn.textContent = "Copied!";
    setTimeout(() => {
      btn.textContent = prev;
    }, 1600);
  } catch {}
});

/* ---------- Submit Modal & Form Handler ---------- */
const dialog = document.querySelector("#submit-modal");

function openSubmitModal() {
  if (!dialog || typeof dialog.showModal !== "function") return false;
  if (!dialog.open) dialog.showModal();
  dialog.querySelector('input[name="url"]')?.focus();
  return true;
}

document.addEventListener("click", (e) => {
  const trigger = e.target.closest("[data-open-submit]");
  if (trigger) {
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    if (location.pathname === "/submit/") return;
    if (openSubmitModal()) e.preventDefault();
    return;
  }
  if (e.target.closest("[data-close-submit]")) {
    dialog?.close();
  }
});

dialog?.addEventListener("click", (e) => {
  if (e.target === dialog) dialog.close();
});

for (const form of document.querySelectorAll("[data-submit-form]")) {
  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const status = form.querySelector(".submit-status");
    const submitBtn = form.querySelector('button[type="submit"]');
    const data = Object.fromEntries(new FormData(form).entries());

    if (!String(data.url || "").trim()) {
      status.hidden = false;
      status.className = "submit-status is-error";
      status.textContent = "Please enter a website URL.";
      form.querySelector('input[name="url"]')?.focus();
      return;
    }

    submitBtn.disabled = true;
    const prevLabel = submitBtn.textContent;
    submitBtn.textContent = "Submitting…";
    status.hidden = true;

    try {
      const res = await fetch("/api/submit/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const json = await res.json().catch(() => ({}));
      status.hidden = false;
      if (res.ok && json.ok) {
        status.className = "submit-status is-success";
        status.replaceChildren();
        status.append(
          document.createTextNode(
            json.message || "Submitted — added to the curation queue.",
          ),
        );
        if (json.issueUrl) {
          status.append(document.createTextNode(" "));
          const link = document.createElement("a");
          link.href = json.issueUrl;
          link.target = "_blank";
          link.rel = "noopener noreferrer";
          link.textContent = "View submission →";
          status.append(link);
        } else if (json.siteUrl) {
          status.append(document.createTextNode(" "));
          const link = document.createElement("a");
          link.href = json.siteUrl;
          link.textContent = "View in gallery →";
          status.append(link);
        }
        form.reset();
      } else {
        status.className = "submit-status is-error";
        status.replaceChildren();
        status.append(
          document.createTextNode(
            json.message || "Could not submit right now.",
          ),
        );
        if (json.fallbackUrl) {
          status.append(document.createTextNode(" "));
          const link = document.createElement("a");
          link.href = json.fallbackUrl;
          link.target = "_blank";
          link.rel = "noopener noreferrer";
          link.textContent = "Submit via GitHub →";
          status.append(link);
        }
      }
    } catch {
      status.hidden = false;
      status.className = "submit-status is-error";
      status.textContent =
        "Network error submitting the site. Please try again.";
    } finally {
      submitBtn.disabled = false;
      submitBtn.textContent = prevLabel;
    }
  });
}

/* ---------- Legacy hash redirect compatibility ---------- */
if (location.pathname === "/" && location.hash) {
  const id = location.hash.match(/^#design\/([a-z0-9-]+)$/)?.[1];
  if (id && cards.some((c) => c.dataset.id === id)) {
    location.replace(`/sites/${id}/`);
  } else if (
    /^#(?:account|library|skill|brief|collection|directory)/.test(location.hash)
  ) {
    history.replaceState(null, "", location.pathname + location.search);
  }
}