/* archive.jsx — HUSTLY ARCHIV editorial index (real @hustlyarchiv.kr posts) */

const { useState: useStateAr, useEffect: useEffectAr, useRef: useRefAr, useMemo: useMemoAr } = React;

/* Real posts pulled from /instagram_exports/hustlyarchiv.kr/manifest.json
   Sorted newest → oldest. Folder name doubles as image filename stem.       */
const ARCHIVE_POSTS = [
  { date: "2026-01-06", title: "Talk with HUSTLY ARCHIV 7",          url: "https://www.instagram.com/p/DTKgX5zk-4V/", folder: "2026-01-06_Talk with HUSTLY ARCHIV 7", count: 12 },
  { date: "2025-12-06", title: "Talk with HUSTLY ARCHIV 6 — 공공구",  url: "https://www.instagram.com/p/DR61gyzk4WI/", folder: "2025-12-06_Talk with HUSTLY ARCHIV 6 공공구 님", count: 15 },
  { date: "2025-10-06", title: "Talk with HUSTLY ARCHIV 5",          url: "https://www.instagram.com/p/DPdYlOokwQa/", folder: "2025-10-06_Talk with HUSTLY ARCHIV 5", count: 8 },
  { date: "2025-10-03", title: "Talk with HUSTLY ARCHIV 4",          url: "https://www.instagram.com/p/DPWT0GvE11F/", folder: "2025-10-03_Talk with HUSTLY ARCHIV 4", count: 11 },
  { date: "2025-09-11", title: "Talk with HUSTLY ARCHIV 3",          url: "https://www.instagram.com/p/DOcl5AZE1GE/", folder: "2025-09-11_Talk with HUSTLY ARCHIV 3", count: 10 },
  { date: "2025-08-09", title: "NOCHANG — 행",                       url: "https://www.instagram.com/p/DNIQlsSyw6p/", folder: "2025-08-09_NOCHANG, 행", count: 13 },
  { date: "2025-07-19", title: "HUSTLY ARCHIV D+200",                url: "https://www.instagram.com/p/DMRqXPhSCKp/", folder: "2025-07-19_HUSTLY ARCHIV D+200", count: 6 },
  { date: "2025-07-16", title: "Talk with HUSTLY ARCHIV 2",          url: "https://www.instagram.com/p/DMKE6_0S-kO/", folder: "2025-07-16_Talk with HUSTLY ARCHIV 2", count: 10 },
  { date: "2025-07-13", title: "JUSTHIS — 2 MANY HOMES 4 1 KID",     url: "https://www.instagram.com/p/DMCzPZmy1EU/", folder: "2025-07-13_JUSTHIS, 2 MANY HOMES 4 1 KID", count: 13 },
  { date: "2025-06-30", title: "GIRIBOY — 영화같게 등",               url: "https://www.instagram.com/p/DLhApZOyTLA/", folder: "2025-06-30_GIRIBOY, 영화같게 등", count: 9 },
  { date: "2025-06-19", title: "최성 — 환상 사이코시스 뮤 127",       url: "https://www.instagram.com/p/DLFH4gTyBnh/", folder: "2025-06-19_최성, 환상 사이코시스 뮤 127 등", count: 11 },
  { date: "2025-06-11", title: "Tablo — 열꽃",                        url: "https://www.instagram.com/p/DKwITlwSpbj/", folder: "2025-06-11_Tablo - 열꽃", count: 9 },
  { date: "2025-06-06", title: "Talk with HUSTLY ARCHIV 1",          url: "https://www.instagram.com/p/DKi1Tmkyaxy/", folder: "2025-06-06_Talk with HUSTLY ARCHIV 1", count: 9 },
  { date: "2025-05-31", title: "B-FREE — Korean Dream",              url: "https://www.instagram.com/p/DKUCBQ_y43C/", folder: "2025-05-31_B-FREE, Korean Dream", count: 13 },
  { date: "2025-04-06", title: "ZENE THE ZILLA — 94-24",             url: "https://www.instagram.com/p/DIGW6H1ygWQ/", folder: "2025-04-06_ZENE THE ZILLA - 94-24", count: 9 },
  { date: "2025-03-24", title: "Paloalto — Dirt",                    url: "https://www.instagram.com/p/DHlGibiSYYh/", folder: "2025-03-24_Paloalto, Dirt", count: 8 },
  { date: "2025-03-10", title: "GongGongGoo009 — 9+9",               url: "https://www.instagram.com/p/DHBHAXTy2BF/", folder: "2025-03-10_GongGongGoo009, 9+9", count: 7 },
  { date: "2025-03-07", title: "Q&A",                                 url: "https://www.instagram.com/p/DG40zc2yHur/", folder: "2025-03-07_Q&A", count: 12 },
  { date: "2025-03-03", title: "Dok2 — Reborn",                      url: "https://www.instagram.com/p/DGuuFDqy9TE/", folder: "2025-03-03_Dok2 - Reborn", count: 8 },
  { date: "2025-02-27", title: "BewhY — The Movie Star",             url: "https://www.instagram.com/p/DGkwxzvyCv_/", folder: "2025-02-27_BewhY - The Movie Star", count: 9 },
  { date: "2025-02-22", title: "호미들 — 하루가 달리",                 url: "https://www.instagram.com/p/DGXaApzSQPc/", folder: "2025-02-22_호미들 - '하루가 달리'", count: 8 },
  { date: "2025-02-16", title: "KHUNDI PANDA — 가로사옥",             url: "https://www.instagram.com/p/DGIUSq7yeY5/", folder: "2025-02-16_KHUNDI PANDA - 가로사옥", count: 9 },
  { date: "2025-02-10", title: "이찬혁 — 부재중전화",                  url: "https://www.instagram.com/p/DF7gdAbS9lk/", folder: "2025-02-10_이찬혁 - 부재중전화", count: 7 },
  { date: "2025-02-09", title: "HUSTLY ARCHIV — 허슬리 아카이브",     url: "https://www.instagram.com/p/DF1wcYayMpm/", folder: "2025-02-09_HUSTLY ARCHIV 허슬리 아카이브", count: 7 },
  { date: "2025-02-02", title: "이센스 — The Anecdote",              url: "https://www.instagram.com/p/DFkNHCayyUe/", folder: "2025-02-02_이센스 - The Anecdote", count: 9 },
  { date: "2025-01-30", title: "창모 — UNDERGROUND ROCKSTAR",        url: "https://www.instagram.com/p/DFcN8HqSpRQ/", folder: "2025-01-30_창모 UNDERGROUND ROCKSTAR", count: 10 },
  { date: "2025-01-26", title: "REDDY — 500000",                     url: "https://www.instagram.com/p/DFSMYQASsbB/", folder: "2025-01-26_REDDY - 500000", count: 15 },
  { date: "2025-01-22", title: "CHOILB — 독립음악 (下)",              url: "https://www.instagram.com/p/DFIBupjS5AF/", folder: "2025-01-22_CHOILB - 독립음악 (下)", count: 7 },
  { date: "2025-01-18", title: "Beenzino — Like A Fool",             url: "https://www.instagram.com/p/DE9QmoYSUmL/", folder: "2025-01-18_Beenzino - Like A Fool (feat.Y2K92)", count: 9 },
  { date: "2025-01-15", title: "SIK-K의 성공은 예정되어 있었다",       url: "https://www.instagram.com/p/DE1g3R7y_UJ/", folder: "2025-01-15_SIK-K의 성공은 예정되어 있었다", count: 8 },
  { date: "2025-01-08", title: "CHOILB — 독립음악 (上)",              url: "https://www.instagram.com/p/DEjyTH5yw_g/", folder: "2025-01-08_CHOILB - 독립음악 (上)", count: 9 },
  { date: "2025-01-06", title: "오직 한국이기에 나올 수 있었던 앨범들", url: "https://www.instagram.com/p/DEess6tSWsw/", folder: "2025-01-06_오직 한국이기에 세상에 나올 수 있었던 앨범들✅", count: 1 },
  { date: "2025-01-06", title: "원슈타인 — Apocalypse",              url: "https://www.instagram.com/p/DEeqZwIyzYt/", folder: "2025-01-06_원슈타인 - Apocalypse", count: 7 },
  { date: "2025-01-04", title: "스카이민혁 — 내방에서 나가",           url: "https://www.instagram.com/p/DEZJW18SZFv/", folder: "2025-01-04_스카이민혁 - 내방에서 나가", count: 7 },
  { date: "2025-01-02", title: "JUSTHIS & Paloalto — Seoul Romance", url: "https://www.instagram.com/p/DEUoN3QS7vD/", folder: "2025-01-02_JUSTHIS&Paloalto - Seoul Romance", count: 9 },
  { date: "2025-01-01", title: "Dabin — TILL I LIVE",                url: "https://www.instagram.com/p/DERbeHESOfe/", folder: "2025-01-01_Dabin - TILL I LIVE", count: 7 },
  { date: "2025-01-01", title: "허슬리아카이브를 시작합니다",            url: "https://www.instagram.com/p/DERBCe4y9fK/", folder: "2025-01-01_허슬리아카이브를 시작합니다", count: 1 },
];

/* Path is relative to the http root (personal-webpage/), via symlink to instagram_exports/hustlyarchiv.kr */
const ARCHIVE_BASE = "archive-media";
const thumbSrc = (p) => `${ARCHIVE_BASE}/${encodeURIComponent(p.folder)}/${encodeURIComponent(p.folder)}_01.jpg`;

/* Editorial taxonomy — derived from real titles, not invented */
function archiveClassify(p) {
  if (p.title.startsWith("Talk with HUSTLY ARCHIV")) return "Talks";
  if (/D\+|허슬리아카이브를|HUSTLY ARCHIV — 허슬리|Q&A|오직 한국이기에/.test(p.title)) return "Editorial";
  return "Reviews";
}

const ARCHIVE_FILTERS = ["All", "Reviews", "Talks", "Editorial"];

function ArchiveThumb({ post, idx, big }) {
  const [hover, setHover] = useStateAr(false);
  const [errored, setErrored] = useStateAr(false);
  const cat = archiveClassify(post);
  return (
    <a
      href={post.url}
      target="_blank"
      rel="noopener"
      data-cursor="link"
      data-cursor-label={t("Open")}
      onMouseEnter={() => window.__hasHover && setHover(true)}
      onMouseLeave={() => window.__hasHover && setHover(false)}
      style={{
        position: "relative",
        display: "block",
        aspectRatio: big ? "4 / 5" : "1 / 1",
        border: "1px solid var(--line)",
        background: "var(--bg)",
        overflow: "hidden",
      }}
    >
      {!errored ? (
        <img
          src={thumbSrc(post)}
          alt={post.title}
          loading="lazy"
          onError={() => setErrored(true)}
          style={{
            position: "absolute", inset: 0,
            width: "100%", height: "100%",
            objectFit: "cover",
            filter: hover ? "grayscale(0%) contrast(1)" : "grayscale(100%) contrast(0.95)",
            transform: hover ? "scale(1.04)" : "scale(1)",
            transition: "filter 600ms var(--easing-default), transform 900ms var(--easing-default)",
          }}
        />
      ) : (
        <div style={{
          position: "absolute", inset: 0,
          background: "repeating-linear-gradient(135deg, var(--line-soft) 0 1px, transparent 1px 8px), var(--bg)",
        }} />
      )}

      {/* register marks: top-left index, top-right category */}
      <div className="micro" style={{
        position: "absolute", top: 10, left: 12, color: "#fff",
        textShadow: "0 0 4px rgba(0,0,0,0.6)",
      }}>{String(idx + 1).padStart(3, "0")}</div>
      <div className="micro" style={{
        position: "absolute", top: 10, right: 12, color: "#fff",
        textShadow: "0 0 4px rgba(0,0,0,0.6)",
      }}>{t(cat)}</div>

      {/* hover caption */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0,
        padding: "16px 14px 12px",
        background: "linear-gradient(to top, rgba(0,0,0,0.78), rgba(0,0,0,0))",
        color: "#fff",
        opacity: hover ? 1 : 0,
        transform: `translateY(${hover ? 0 : 8}px)`,
        transition: "opacity 240ms var(--easing-default), transform 240ms var(--easing-default)",
      }}>
        <div className="micro" style={{ color: "rgba(255,255,255,0.7)", marginBottom: 4 }}>{post.date}</div>
        <div style={{
          fontFamily: "var(--font-display)", fontSize: big ? 22 : 17, lineHeight: 1.2,
          fontStyle: "italic",
        }}>{post.title}</div>
      </div>
    </a>
  );
}

function ArchiveIndexRow({ post, idx }) {
  const [hover, setHover] = useStateAr(false);
  return (
    <a
      href={post.url}
      target="_blank"
      rel="noopener"
      data-cursor="link"
      data-cursor-label={t("Open")}
      onMouseEnter={() => window.__hasHover && setHover(true)}
      onMouseLeave={() => window.__hasHover && setHover(false)}
      className="row-list"
      style={{
        display: "grid",
        gridTemplateColumns: "60px 110px 1fr 110px 60px",
        alignItems: "center",
        gap: 24,
        padding: "18px 0",
        borderTop: "1px solid var(--line-soft)",
        position: "relative",
        color: "var(--fg)",
      }}
    >
      <span className="micro row-n">{String(idx + 1).padStart(3, "0")}</span>
      <span className="micro row-date" style={{ color: "var(--fg-muted)" }}>{post.date}</span>
      <span className="row-title" style={{
        fontFamily: "var(--font-display)",
        fontSize: hover ? 28 : 24,
        fontStyle: hover ? "italic" : "normal",
        lineHeight: 1.1,
        transition: "all 280ms var(--easing-default)",
      }}>{post.title}</span>
      <span className="micro row-tag" style={{ color: "var(--fg-muted)", textAlign: "right" }}>{t(archiveClassify(post))}</span>
      <span className="micro row-arrow" style={{ textAlign: "right" }}>↗</span>

      {/* hover image preview */}
      {hover && (
        <div style={{
          position: "absolute", right: 180, top: "50%",
          transform: "translateY(-50%)",
          width: 180, height: 220,
          pointerEvents: "none",
          border: "1px solid var(--line)",
          overflow: "hidden",
          background: "var(--bg)",
          animation: "reveal 360ms var(--easing-default) forwards",
          clipPath: "inset(100% 0 0 0)",
          zIndex: 2,
        }}>
          <img src={thumbSrc(post)} alt="" loading="lazy"
            style={{ width: "100%", height: "100%", objectFit: "cover", filter: "grayscale(100%)" }} />
        </div>
      )}
    </a>
  );
}

function Archive() {
  useLang();
  const [filter, setFilter] = useStateAr("All");
  const [view, setView] = useStateAr("grid"); // "grid" | "index"

  const filtered = useMemoAr(() => (
    filter === "All" ? ARCHIVE_POSTS : ARCHIVE_POSTS.filter(p => archiveClassify(p) === filter)
  ), [filter]);

  const counts = useMemoAr(() => ({
    All: ARCHIVE_POSTS.length,
    Reviews: ARCHIVE_POSTS.filter(p => archiveClassify(p) === "Reviews").length,
    Talks: ARCHIVE_POSTS.filter(p => archiveClassify(p) === "Talks").length,
    Editorial: ARCHIVE_POSTS.filter(p => archiveClassify(p) === "Editorial").length,
  }), []);

  return (
    <div className="page" style={{ paddingTop: 140 }}>
      <style>{`@keyframes reveal { to { clip-path: inset(0 0 0 0); } }`}</style>

      <div className="page-eyebrow">
        <span className="micro">{t("Index")} 05</span>
        <span style={{ width: 24, height: 1, background: "var(--fg)" }} />
        <span className="micro micro-fg">{t("Archive · HUSTLY ARCHIV")}</span>
      </div>

      {/* Editorial cover */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 64, marginBottom: 64, alignItems: "end" }} className="responsive-stack">
        <h1 className="display-xxl" style={{ fontStyle: "italic" }}>
          Hustly<br/>
          <span style={{ fontStyle: "normal" }}>Archiv</span>
          <span className="micro" style={{ verticalAlign: "super", marginLeft: 8 }}>™</span>
        </h1>
        <div>
          <div className="micro" style={{ marginBottom: 12 }}>{t("Editor's note")}</div>
          <p className="body-lg" style={{ marginBottom: 16 }}>
            {t("Started in January 2025, mid-military-service, from a single phone — long-text editorial inside a Korean hip-hop scene that runs on shorts. Album readings, conversations, and editorial notes. Each entry below is a real post; click through for the full essay on Instagram.")}
          </p>
          <p className="body-sm" style={{ marginBottom: 16, color: "var(--fg-muted)" }}>
            {t("Now collaborating under one vision with Beean (Dejavu producer), GongGongGoo009 (KHA 2023 Newcomer of the Year), Pohranos (indie distributor under Mound Media), and HD BL4CK (producer for The Quiett, nafla).")}
          </p>
          <a className="micro" href="https://www.instagram.com/hustlyarchiv.kr/" target="_blank" rel="noopener" data-cursor="link" data-cursor-label={t("Open")}
            style={{ color: "var(--fg)", borderBottom: "1px solid var(--fg)", paddingBottom: 2 }}>
            {t("@hustlyarchiv.kr · since Jan 2025 · 3K+ followers · 1M+ views")}
          </a>
        </div>
      </div>

      {/* Stats strip */}
      <div className="four-col" style={{
        display: "grid", gridTemplateColumns: "repeat(4, 1fr)",
        borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)",
        marginBottom: 56,
      }}>
        {[
          ["Entries", String(counts.All).padStart(3, "0")],
          ["Reviews", String(counts.Reviews).padStart(3, "0")],
          ["Talks", String(counts.Talks).padStart(3, "0")],
          ["Since", "2025·01"],
        ].map(([k, v], i, arr) => (
          <div key={k} style={{
            padding: "26px 20px",
            borderRight: i < arr.length - 1 ? "1px solid var(--line-soft)" : "none",
          }}>
            <div className="micro" style={{ marginBottom: 10, color: "var(--fg-muted)" }}>{t(k)}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 40, lineHeight: 1 }}>{v}</div>
          </div>
        ))}
      </div>

      {/* Filter + view toggle */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        marginBottom: 28, gap: 24, flexWrap: "wrap",
      }}>
        <div style={{ display: "flex", gap: 4 }}>
          {ARCHIVE_FILTERS.map(f => (
            <button key={f} onClick={() => setFilter(f)} data-cursor="link" data-cursor-label={t("Filter")}
              style={{
                fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em",
                textTransform: "uppercase",
                padding: "10px 16px",
                border: "1px solid " + (filter === f ? "var(--fg)" : "var(--line-soft)"),
                background: filter === f ? "var(--fg)" : "var(--bg)",
                color: filter === f ? "var(--bg)" : "var(--fg)",
                marginRight: 4,
              }}>
              {t(f)} <span style={{ opacity: 0.55, marginLeft: 6 }}>{counts[f]}</span>
            </button>
          ))}
        </div>
        <div style={{ display: "flex", gap: 4 }}>
          {["grid", "index"].map(v => (
            <button key={v} onClick={() => setView(v)} data-cursor="link" data-cursor-label={t("View")}
              style={{
                fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em",
                textTransform: "uppercase",
                padding: "10px 16px",
                border: "1px solid " + (view === v ? "var(--fg)" : "var(--line-soft)"),
                background: view === v ? "var(--fg)" : "var(--bg)",
                color: view === v ? "var(--bg)" : "var(--fg)",
              }}>{t(v)}</button>
          ))}
        </div>
      </div>

      {/* Grid view — uniform editorial grid */}
      {view === "grid" && (
        <div className="archive-grid" style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 12,
          marginBottom: 80,
        }}>
          {filtered.map((p, i) => (
            <ArchiveThumb key={p.url} post={p} idx={ARCHIVE_POSTS.indexOf(p)} />
          ))}
        </div>
      )}

      {/* Index view — text-forward, hover-reveals image */}
      {view === "index" && (
        <div style={{ marginBottom: 80 }}>
          {filtered.map((p) => (
            <ArchiveIndexRow key={p.url} post={p} idx={ARCHIVE_POSTS.indexOf(p)} />
          ))}
          <div style={{ borderTop: "1px solid var(--line-soft)" }} />
        </div>
      )}

      {/* Footer band */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64, padding: "48px 0", borderTop: "1px solid var(--line)" }} className="responsive-stack">
        <div className="display-md">
          {t("The archive lives natively on Instagram. The grid above is a static mirror.")}
        </div>
        <div style={{ display: "flex", alignItems: "end" }}>
          <a className="link-arrow" href="https://www.instagram.com/hustlyarchiv.kr/" target="_blank" rel="noopener" data-cursor="link" data-cursor-label={t("Open")}>{t("@hustlyarchiv.kr on Instagram →")}</a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Archive });
