// Experimental Archive: one page, masonry grid. A main toggle switches between
// things I've made and things I enjoy; "Made" can be filtered by category.
// Loaded only by "Archive Masonry.html", after About.jsx, so it overrides
// window.Playground there while the live site keeps the original.

const { useState: useStateAM, useMemo: useMemoAM, useEffect: useEffectAM } = React;

// Width-to-height ratios of each item's media, measured once and cached so the
// grid can be balanced before (and after) images finish loading.
// Seeded from src/archive-ratios.js (measured ahead of time) so the grid can
// lay out in its final arrangement before any image downloads. Anything not
// in the preset is still measured on the fly below.
const AM_RATIOS = Object.assign({}, window.AM_PRESET_RATIOS || {});
function useMediaRatios(list) {
  const [, bump] = useStateAM(0);
  useEffectAM(() => {
    let alive = true;
    list.forEach((it) => {
      const k = it.videoSrc || it.src;
      if (!k || AM_RATIOS[k]) return;
      const done = (w, h) => {if (w && h) {AM_RATIOS[k] = w / h;if (alive) bump((n) => n + 1);}};
      if (it.videoSrc) {
        const v = document.createElement("video");
        v.preload = "metadata";v.muted = true;
        v.onloadedmetadata = () => done(v.videoWidth, v.videoHeight);
        v.src = it.videoSrc;
      } else {
        const im = new Image();
        im.onload = () => done(im.naturalWidth, im.naturalHeight);
        im.src = it.src;
      }
    });
    return () => {alive = false;};
  }, [list]);
  return AM_RATIOS;
}

// 3 / 2 / 1 columns, matching the old breakpoints.
function useColumnCount() {
  const get = () => window.innerWidth <= 900 ? 2 : 3;
  const [n, setN] = useStateAM(get);
  useEffectAM(() => {
    const on = () => setN(get());
    window.addEventListener("resize", on);
    return () => window.removeEventListener("resize", on);
  }, []);
  return n;
}
const INTO = "Things I'm into";
const FEATURED = "Featured";

// Misc items sorted into the two halves, with a category for "Made".
const AM_MISC = {
  dragonDance: { side: "enjoy" },
  sleight: { side: "enjoy" },
  keychains: { side: "made", cat: "Tinkering", featured: true },
  tinkering: { side: "made", cat: "Tinkering", featured: true },
  redEnvelope: { side: "made", cat: "Tinkering" },
  dormScan: { side: "made", cat: "Tinkering" },
  wallMaze: { side: "made", cat: "Tinkering" },
  spongeBed: { side: "made", cat: "Tinkering" },
  matcha: { side: "enjoy" },
  espresso: { side: "enjoy" },
  games: { side: "enjoy" },
  concerts: { side: "enjoy" }
};

function buildArchiveItems() {
  const C = window.PLAYGROUND_CATEGORIES || {};
  const made = [], enjoy = [];
  (C.branding && C.branding.projects || []).forEach((p) => {
    const kinds = p.kinds || [p.kind];
    // UX/UI, Graphic and Branding all roll up into one "Design" category.
    made.push({ key: "d-" + p.slug, cats: ["Design"], tag: "Design", featured: true, title: p.title, sub: p.blurb, src: p.src, href: "design/" + p.slug });
  });
  (C.photography && C.photography.items || []).forEach((it, i) => {
    made.push({ key: "p-" + i, cats: ["Photography"], tag: "Photography", title: it.imgTitle, sub: it.imgCaption, src: it.src, videoSrc: it.videoSrc });
  });
  (C.misc && C.misc.items || []).forEach((it, i) => {
    const m = AM_MISC[it.label] || { side: "made", cat: "Other" };
    const row = { key: "m-" + i, cats: m.cat ? [m.cat] : [], tag: m.cat || "", featured: !!m.featured, title: it.imgTitle, sub: it.imgCaption, src: it.src, videoSrc: it.videoSrc };
    (m.side === "enjoy" ? enjoy : made).push(row);
  });
  // The home page emoji cards are already "things I'm into".
  // Skip emoji cards that repeat something already in the list (e.g. dragon dance).
  const seen = new Set(enjoy.map((x) => (x.title || "").toLowerCase().trim()));
  (window.EMOJIS || []).forEach((e, i) => {
    if (!e.img && !e.video) return;
    if (seen.has((e.title || "").toLowerCase().trim())) return;
    enjoy.push({ key: "e-" + i, cats: [], tag: "", title: e.title, sub: e.body, src: e.img, videoSrc: e.video });
  });
  // Interleave so design, photos and misc mix instead of arriving in blocks.
  const mix = (arr) => {
    const groups = {};
    arr.forEach((x) => {(groups[x.key[0]] = groups[x.key[0]] || []).push(x);});
    const lists = Object.values(groups), out = [];
    for (let i = 0; lists.some((l) => l.length > i); i++) lists.forEach((l) => {if (l[i]) out.push(l[i]);});
    return out;
  };
  return { made: mix(made), enjoy };
}

function MasonryCard({ item, onOpen, showTag = true, ratio, eager }) {
  // The media box is sized to the real image up front (a soft gray tile), and
  // the image fades in once loaded. Already-cached images skip the fade.
  const [loaded, setLoaded] = useStateAM(false);
  const ref = React.useRef(null);
  useEffectAM(() => {
    const el = ref.current;
    if (!el) return;
    if (el.tagName === "IMG" ? el.complete && el.naturalWidth : el.readyState >= 2) setLoaded(true);
  }, []);
  return (
    <article className={"am-card" + (item.href ? " is-link" : " is-zoom")} role="button" tabIndex={0}
    aria-label={(item.href ? "Open " : "View full screen: ") + (item.title || "item")}
    onClick={() => onOpen(item)}
    onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {e.preventDefault();onOpen(item);}}}>
      <div className={"am-media" + (loaded ? " is-loaded" : "")} style={ratio ? { aspectRatio: String(ratio) } : undefined}>
        {item.videoSrc ?
        <video ref={ref} src={item.videoSrc} autoPlay muted loop playsInline preload={eager ? "auto" : "metadata"} onLoadedData={() => setLoaded(true)} /> :
        item.src ?
        <img ref={ref} src={item.src} alt={item.title || ""} decoding="async" loading={eager ? "eager" : "lazy"} fetchpriority={eager ? "high" : undefined}
        onLoad={() => setLoaded(true)} onError={() => setLoaded(true)} /> :
        <div className="am-ph" />}
        {/* Hover cue for what a click does: projects open their page,
            everything else opens full screen. */}
        <span className={"zoom-badge am-badge" + (item.href ? " is-link" : "")} aria-hidden="true">
          {item.href ?
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3.5 8h9M9 4.5 12.5 8 9 11.5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" /></svg> :
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>}
        </span>
      </div>
      <div className="am-text">
        <div className="am-title">{item.title}</div>
        {showTag && item.tag && <div className="am-tag">{item.tag}</div>}
      </div>
    </article>);

}

function ArchiveMasonry({ onNavigate, initialCat }) {
  const data = useMemoAM(buildArchiveItems, []);
  const [cat, setCat] = useStateAM(initialCat || FEATURED);
  // Remember the filter, so "Back to Archive" on a project page returns here.
  useEffectAM(() => {
    try {sessionStorage.setItem("archiveLastCat", cat);} catch (e) {}
    window.__archiveLastCat = cat;
  }, [cat]);
  const [zoomed, setZoomed] = useStateAM(null);
  const Nav = window.SiteNav,Footer = window.SiteFooter,Lightbox = window.Lightbox;

  const cats = useMemoAM(() => {
    const order = ["Design", "Photography", "Tinkering"];
    const have = new Set(data.made.flatMap((x) => x.cats));
    return [FEATURED, ...order.filter((c) => have.has(c)), INTO];
  }, [data]);

  const list = cat === INTO ? data.enjoy :
  // Featured is hand-picked: set `featured: true` on an item to include it.
  cat === FEATURED ? data.made.filter((x) => x.featured) :
  data.made.filter((x) => x.cats.includes(cat));

  const ratios = useMediaRatios(list);
  const colCount = useColumnCount();

  const shown = cat;

  // One-time hint, shown on a visitor's first time on this page.
  const HINT_KEY = "am-filter-hint-seen";
  const [hint, setHint] = useStateAM(false);
  useEffectAM(() => {
    let seen = false;
    try {seen = localStorage.getItem(HINT_KEY) === "1";} catch (e) {}
    if (seen) return;
    const t = setTimeout(() => setHint(true), 1500); // once the bar has slid in
    return () => clearTimeout(t);
  }, []);
  const dismissHint = () => {
    setHint(false);
    try {localStorage.setItem(HINT_KEY, "1");} catch (e) {}
  };

  // Position of the sliding pill, measured from the displayed option.
  const chipsRef = React.useRef(null);
  const [slide, setSlide] = useStateAM({ x: 0, w: 0 });
  const [arrowX, setArrowX] = useStateAM(56);
  React.useLayoutEffect(() => {
    const measure = () => {
      const box = chipsRef.current;
      const btn = box && box.querySelector('[data-cat="' + CSS.escape(shown) + '"]');
      if (!btn) return;
      setSlide({ x: btn.offsetLeft, w: btn.offsetWidth });
      const first = box.querySelector("[data-cat]");
      if (first) setArrowX(box.offsetLeft + first.offsetLeft + first.offsetWidth / 2);
      // Keep the selected option in view if the bar scrolls sideways.
      const l = btn.offsetLeft, r = l + btn.offsetWidth;
      if (l < box.scrollLeft || r > box.scrollLeft + box.clientWidth) box.scrollTo({ left: l - 12, behavior: "smooth" });
    };
    measure();
    window.addEventListener("resize", measure);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(measure);
    return () => window.removeEventListener("resize", measure);
  }, [shown, cats]);

  // Everything in the current view that opens full screen (not project
  // pages), in grid order, so the lightbox arrows step through it like the
  // About page galleries.
  const zoomables = list.filter((x) => !x.href);
  const open = (item) => {
    if (item.href) {onNavigate(item.href);return;}
    setZoomed(Math.max(0, zoomables.indexOf(item)));
  };

  return (
    <div className="am-page" style={{ minHeight: "100vh", background: "var(--paper)", display: "flex", flexDirection: "column" }}>
      {/* Nav matches the Archive's wider grid, like case studies do with theirs. */}
      <Nav onNavigate={onNavigate} current="playground" autoHide={true} contentMaxWidth={1680} />
      <div className="am-wrap">
        <header style={{ maxWidth: 640 }}>
          <h1 style={{ margin: 0, fontWeight: 700, fontSize: 40, lineHeight: 1.08, letterSpacing: "-0.04em" }}>
            Welcome to my Archive! 
          </h1>
          <p style={{ margin: "12px 0 0", fontWeight: 300, fontSize: 15, lineHeight: "23px", letterSpacing: "-0.02em", color: "rgb(var(--ink-rgb) / 0.72)" }}>
            A place where things other than my case studies live...
          </p>
        </header>

        <div className="am-controls">
          {hint &&
          <span className="am-hint" role="status" style={{ "--arrow-x": arrowX + "px" }}>
              <span className="theme-hint-text">Filter by category</span>
              <button className="theme-hint-close" onClick={dismissHint} aria-label="Dismiss hint">
                <svg width="10" height="10" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                  <path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
                </svg>
              </button>
            </span>
          }
          <div className="am-chips" ref={chipsRef} role="tablist">
            {/* One purple pill that slides under the selected option. */}
            <span className="am-slider" aria-hidden="true" style={{
              transform: `translateX(${slide.x}px)`, width: slide.w,
              opacity: slide.w ? 1 : 0
            }} />
            {cats.map((c) =>
            <button key={c} role="tab" aria-selected={c === cat} data-cat={c}
            className={"am-chip" + (c === shown ? " is-on" : "")} onClick={() => {setCat(c);if (hint) dismissHint();}}>{c}</button>
            )}
          </div>
        </div>

        <div className="am-grid" key={cat}>
          {/* Balanced masonry: each item goes into whichever column is shortest
              so far, using the media's real shape, so the columns end evenly
              instead of leaving a big gap at the bottom of one. */}
          {(() => {
            // Card height in column-width units: media plus title and margin.
            const hOf = (it) => {
              const k = it.videoSrc || it.src;
              return 1 / ((k && ratios[k]) || 1.4) + 0.2;
            };
            const cols = Array.from({ length: colCount }, () => ({ h: 0, items: [] }));
            // 1) Greedy: each item to the currently shortest column.
            list.forEach((it) => {
              const target = cols.reduce((a, c) => c.h < a.h ? c : a, cols[0]);
              target.items.push(it);
              target.h += hOf(it);
            });
            // 2) Balance: greedy only bounds the gap by one card, so move or
            // swap trailing cards between the tallest and shortest columns
            // while that narrows the spread between column bottoms.
            if (colCount > 1) {
              const spread = () => Math.max(...cols.map((c) => c.h)) - Math.min(...cols.map((c) => c.h));
              const TAIL = 4;
              for (let pass = 0; pass < 40; pass++) {
                const before = spread();
                let best = null;
                cols.forEach((hi, i) => cols.forEach((lo, j) => {
                  if (i === j || hi.h <= lo.h) return;
                  const hiT = hi.items.slice(-TAIL), loT = lo.items.slice(-TAIL);
                  // Move one trailing card from hi to the end of lo.
                  hiT.forEach((x) => {
                    const hx = hOf(x);
                    const nh = cols.map((c, n) => n === i ? c.h - hx : n === j ? c.h + hx : c.h);
                    const sp = Math.max(...nh) - Math.min(...nh);
                    if (sp < before - 0.01 && (!best || sp < best.sp)) best = { sp, kind: "move", i, j, x };
                  });
                  // Swap a trailing card from each.
                  hiT.forEach((x) => loT.forEach((y) => {
                    const d = hOf(x) - hOf(y);
                    if (d <= 0) return;
                    const nh = cols.map((c, n) => n === i ? c.h - d : n === j ? c.h + d : c.h);
                    const sp = Math.max(...nh) - Math.min(...nh);
                    if (sp < before - 0.01 && (!best || sp < best.sp)) best = { sp, kind: "swap", i, j, x, y };
                  }));
                }));
                if (!best) break;
                const hi = cols[best.i], lo = cols[best.j];
                if (best.kind === "move") {
                  hi.items.splice(hi.items.indexOf(best.x), 1);
                  lo.items.push(best.x);
                  hi.h -= hOf(best.x);lo.h += hOf(best.x);
                } else {
                  const xi = hi.items.indexOf(best.x), yi = lo.items.indexOf(best.y);
                  hi.items[xi] = best.y;lo.items[yi] = best.x;
                  const d = hOf(best.x) - hOf(best.y);
                  hi.h -= d;lo.h += d;
                }
              }
            }
            // The first row or so loads right away; the rest as you scroll.
            const rank = (ci, ri) => ri * colCount + ci;
            return cols.map((c, ci) =>
            <div key={ci} className="am-col">
                {c.items.map((it, ri) => <MasonryCard key={it.key} item={it} onOpen={open} showTag={cat === FEATURED}
                ratio={ratios[it.videoSrc || it.src]} eager={rank(ci, ri) < 9} />)}
              </div>
            );
          })()}
        </div>
      </div>
      <Footer contentMaxWidth={1680} />
      <div className="am-bar-spacer" aria-hidden="true" />
      {zoomed !== null && (() => {
        const toLb = (x) => ({ title: x.title, caption: x.sub, src: x.src, videoSrc: x.videoSrc });
        // Featured and Design mix in project pages, so a gallery there would
        // only step through the few full-screen items. Show just the one.
        if (cat === FEATURED || cat === "Design") return <Lightbox item={toLb(zoomables[zoomed])} onClose={() => setZoomed(null)} />;
        return <Lightbox items={zoomables.map(toLb)} startIndex={zoomed} galleryTitle={cat} onClose={() => setZoomed(null)} />;
      })()}
    </div>);

}

window.Playground = ArchiveMasonry;
