// Data layer — loads wallpeppers.json. The file is pre-enriched by
// `node scripts/enrich.js` with real palette/mood/category/suggestions per
// entry, so the runtime just reads them. If a field is missing (a freshly
// added wallpaper that hasn't been re-enriched yet) we fall back to a
// reasonable default so search/grid still work.

const MOODS = ["Calm", "Vivid", "Dark", "Light", "Warm", "Cool", "Earth", "Minimal"];

function fallbackEnrich(row, idx) {
  const collKey = (row.collections || "").toUpperCase();
  const category = collKey ? collKey[0] + collKey.slice(1).toLowerCase() : "Other";
  return {
    ...row,
    id:
      row.id ||
      `wp-${String(idx).padStart(4, "0")}-${String(row.name || "wp")
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/^-+|-+$/g, "")
        .slice(0, 24)}`,
    title: row.title || row.name || "Untitled",
    category: row.category || category,
    palette: row.palette || ["#1a1a1a", "#3a3a3a", "#5a5a5a", "#8a8a8a"],
    mood: row.mood || ["Calm"],
    aspect: row.aspect || 0.5625,
    suggestions: row.suggestions || [],
  };
}

async function loadWallpapers() {
  const res = await fetch("wallpeppers.json", { cache: "force-cache" });
  if (!res.ok) throw new Error(`Failed to load wallpeppers.json: ${res.status}`);
  const raw = await res.json();
  const items = raw.map((row, idx) => fallbackEnrich(row, idx));

  const seen = new Set();
  const cats = ["All"];
  for (const it of items) {
    if (!seen.has(it.category)) {
      seen.add(it.category);
      cats.push(it.category);
    }
  }

  return { items, categories: cats, moods: MOODS };
}

function colorDistance(a, b) {
  const ah = String(a).match(/\w\w/g) || [];
  const bh = String(b).match(/\w\w/g) || [];
  if (ah.length < 3 || bh.length < 3) return 999;
  const ar = parseInt(ah[0], 16), ag = parseInt(ah[1], 16), ab = parseInt(ah[2], 16);
  const br = parseInt(bh[0], 16), bg = parseInt(bh[1], 16), bb = parseInt(bh[2], 16);
  return Math.sqrt((ar - br) ** 2 + (ag - bg) ** 2 + (ab - bb) ** 2);
}

Object.assign(window, { loadWallpapers, MOODS, colorDistance });
