/* global React, window */
const { Reveal, GlassChip, GlassButton, Icon, LazyImage } = window;

const CODING = [
  {
    n: "赛博宠物",
    en: "CYBER PET",
    tag: "TAMAGOTCHI · 2026",
    desc: "养个自己的赛博宠物，它会每小时强制提醒你去喝水。",
    accents: ["#7aa2ff", "#b07aff"],
    icon: "cat",
    iconImg: "assets/xiaoxiaolin/icon.png",
    cover: "assets/xiaoxiaolin/cover.gif",
    video: "assets/xiaoxiaolin/xiaoxiaolin.mp4",
    href: "#"
  },
  {
    n: "塔罗占星",
    en: "TAROT",
    tag: "AI ORACLE · 2025",
    desc: "AI 解牌，每日一抽。78 张牌的语义嵌入 + 大模型解读。",
    accents: ["#b07aff", "#ff7ab0"],
    icon: "sparkle",
    previewText: "to be continued",
    href: "#"
  }
];

function CodingCard({ w, i, onPlay }) {
  const { motion } = window.Motion || {};
  const hasVideo = !!w.video;
  const Wrap = motion ? motion.a : "a";
  const openVideo = (e) => {
    if (!hasVideo) return;
    const opened = window.open(w.video, "_blank", "noopener,noreferrer");
    if (!opened && onPlay) {
      e.preventDefault();
      onPlay(w);
    }
  };
  const wrapProps = hasVideo
    ? { href: w.video, target: "_blank", rel: "noreferrer", onClick: openVideo }
    : { href: w.href };
  return (
    <Wrap
      {...wrapProps}
      className="liquid-glass rounded-2xl md:rounded-3xl p-5 md:p-8 block w-full text-left group relative overflow-hidden cursor-pointer"
      style={{ minHeight: 320 }}
      whileHover={motion ? { y: -4 } : undefined}
      transition={{ type: "spring", stiffness: 200, damping: 24 }}
    >
      {/* color halo */}
      <div className="absolute -top-24 -right-24 w-64 h-64 rounded-full blur-3xl opacity-30 pointer-events-none"
        style={{ background: `radial-gradient(circle, ${w.accents[0]}, transparent 70%)` }}></div>
      <div className="absolute -bottom-24 -left-24 w-64 h-64 rounded-full blur-3xl opacity-20 pointer-events-none"
        style={{ background: `radial-gradient(circle, ${w.accents[1]}, transparent 70%)` }}></div>

      {/* top row */}
      <div className="flex items-start justify-between relative z-10">
        <div>
          <div className="font-mono text-[10px] text-white/45 tracking-[0.25em]">0{i + 1} · {w.tag}</div>
          <h3 className="font-heading italic text-white text-4xl md:text-6xl mt-2 tracking-tight leading-none">{w.n}</h3>
          <div className="font-mono text-[11px] text-white/40 tracking-[0.3em] mt-2">{w.en}</div>
        </div>
        <div className="liquid-glass-strong rounded-2xl w-14 h-14 flex items-center justify-center overflow-hidden flex-none">
          {w.iconImg ? (
            <LazyImage src={w.iconImg} alt={w.n} className="w-full h-full object-cover" rootMargin="1200px" />
          ) : (
            <Icon name={w.icon} className="h-6 w-6 text-white" strokeWidth={1.2} />
          )}
        </div>
      </div>

      {/* preview */}
      <div className="mt-6 ph rounded-xl md:rounded-2xl relative overflow-hidden" style={{ aspectRatio: "99 / 64" }}>
        {w.cover ? (
          <>
            <LazyImage
              src={w.cover}
              alt={w.n}
              className="absolute inset-0 w-full h-full object-cover transition-transform duration-500 group-hover:scale-[1.03]"
            />
            {/* play button overlay */}
            <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
              <div className="relative">
                <div className="absolute inset-[-9px] rounded-full border border-white/40 scale-90 opacity-0 group-hover:scale-100 group-hover:opacity-100 transition-all duration-300"></div>
                <div className="relative w-14 h-14 rounded-full border border-white/70 bg-black/45 backdrop-blur-md flex items-center justify-center transition-all duration-300 group-hover:bg-white group-hover:border-white group-hover:scale-105 group-hover:shadow-[0_0_26px_rgba(255,255,255,0.45)]">
                  <svg width="16" height="16" viewBox="0 0 12 12" className="ml-[2px] fill-white transition-colors duration-300 group-hover:fill-black">
                    <path d="M2 1.5l8 4.5-8 4.5V1.5z" />
                  </svg>
                </div>
              </div>
            </div>
          </>
        ) : (
          <>
            <span className="ph-label absolute top-3 left-3">LIVE PREVIEW · 720×360</span>
            <div className="absolute inset-0 flex items-center justify-center">
              {w.previewText ? (
                <span className="font-heading italic text-white/40 text-3xl md:text-4xl tracking-wide">{w.previewText}</span>
              ) : (
                <div className="font-heading italic text-white/30 text-7xl">{w.en[0]}</div>
              )}
            </div>
          </>
        )}
      </div>

      <div className="mt-5 flex items-end justify-between gap-4 relative z-10">
        <p className="font-cn text-white/75 text-sm leading-relaxed max-w-md">{w.desc}</p>
        <span className="liquid-glass rounded-full px-3 py-1.5 text-[11px] font-mono tracking-[0.25em] flex items-center gap-1.5 flex-none">
          {hasVideo ? "PLAY" : "OPEN"} <Icon name={hasVideo ? "play" : "arrow-up-right"} className="h-3 w-3" />
        </span>
      </div>
    </Wrap>
  );
}

function WebWorks() {
  const { useState, useEffect } = React;
  const [active, setActive] = useState(null);

  useEffect(() => {
    if (!active) return;
    const onKey = (e) => { if (e.key === "Escape") setActive(null); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [active]);

  return (
    <section id="works" className="relative bg-black">
      <div className="max-w-7xl mx-auto px-6 md:px-12 pt-32 pb-24">
        <div className="flex items-end justify-between flex-wrap gap-6 mb-12">
          <div>
            <div className="font-mono text-[10px] text-white/45 tracking-[0.3em] mb-4">// 03 — WEB CODING</div>
                  <h2 className="hero-heading font-heading italic text-4xl sm:text-5xl md:text-7xl lg:text-[5.5rem] leading-[0.9] tracking-tight">
              AI <span className="not-italic font-cn font-light">作品</span>.
            </h2>
            <p className="font-cn text-white/60 text-sm md:text-base mt-4 max-w-lg leading-relaxed">
              业余时间用 AI 写代码的小东西。每一个都是周末的某个晚上想出来的。
            </p>
          </div>
          <GlassChip strong className="text-sm py-1.5 px-4">
            <span className="h-1.5 w-1.5 rounded-full bg-emerald-300 pulse-dot"></span>
            <span className="font-cn">点击即可在新标签页打开</span>
          </GlassChip>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          {CODING.map((w, i) => (
            <Reveal key={w.n} delay={i * 0.08}>
              <CodingCard w={w} i={i} onPlay={setActive} />
            </Reveal>
          ))}
        </div>
      </div>

      <div className="hairline max-w-7xl mx-auto"></div>

      {/* Video lightbox — portaled to body so it escapes any transformed ancestor */}
      {active && ReactDOM.createPortal(
        <div
          className="fixed inset-0 z-[100] bg-black/90 backdrop-blur-md flex items-center justify-center p-6 md:p-12"
          onClick={() => setActive(null)}
        >
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); setActive(null); }}
            className="absolute top-6 right-6 w-11 h-11 rounded-full bg-white/10 hover:bg-white/20 border border-white/20 flex items-center justify-center text-white text-2xl leading-none transition-colors z-10"
            aria-label="Close"
          >×</button>
          <div className="relative w-full max-w-[960px]" onClick={(e) => e.stopPropagation()}>
            <video
              key={active.video}
              src={active.video}
              ref={(el) => { if (el) el.play().catch(() => {}); }}
              controls
              autoPlay
              playsInline
              className="w-full h-auto rounded-2xl shadow-2xl bg-black max-h-[82vh] object-contain"
            />
            <div className="mt-3 text-center font-cn text-sm text-white/85">{active.n}</div>
          </div>
        </div>,
        document.body
      )}
    </section>
  );
}

/* ─────────── LIFE · 照片墙 (scattered masonry) ─────────── */
const LIFE_PICS = [
  "039d390373f5ad6c5a1b718f4b041f.JPG","0d84820c4371fbcbfebf48e50ffdca.JPG","12042f96176a377912219e1341b1ce.JPG",
  "14ef08404ce5fcf5cc4f4959807d40.JPG","18aac418e648cd07d8882ffe1e1c81.JPG","1e274c1b86e2668540a77aed2a4d0a.JPG",
  "25b7cff13363be9180ef87eeca80e6.JPG","2957c9afea7be3de1786db6cccac2e.JPG","34900e3f1603018fb3b231b44f52e5.JPG",
  "387c0ccd8b5cb3d414259f5973bde6.JPG","39aa13638690c4c390babe481d8e0b.JPG","40e13505d80f58af3c92ca8eee591a.JPG",
  "445be682ebff5e27fb906105c2990b.JPG","4cdf88bc2ccaf485929fc33105f1cd.JPG","4e64bdfd789740a86253be60b416fa.JPG",
  "6801e51b54eda738a1a6d93ef7d546.JPG","6d1b7069b27cb84a51d978551969cc.JPG","6d9a75f774519698096feb08204395.JPG",
  "78e4cfd48e83722d49ac77f0ac450f.JPG","83c244bb5a95f4fb59bfc3fe52aeb0.JPG","83e1c94edcfe28692470f61dab276b.JPG",
  "85d57caebb168ed997f2b775e21d48.JPG","888a8482f6df68ab4a6231ba53cc31.JPG","894af1cb57bb4274bc728d40748c12.JPG",
  "8f4938949379f3275c6334deb4419e.JPG","90899cef431b2022aa1cae72c566a2.JPG","96bb18012c8b3d2f65057ccdb8a9a7.JPG",
  "9748dfff33b3e27e60c247671e7914.JPG","a9391c3c7d998e9595751ad6742621.JPG","ac37df22f1eb979a4f2ad90add9bb6.JPG",
  "ad87375760becffd5116b2b207f7cd.JPG","b73b9dadcac4dec9912c6648b0613d.JPG","de7fbd66510a527edc789e27c9746a.JPG",
  "e21123449cbd43ce092ef6319327d1.JPG","ef81e3bd1a8b8eba9936e0d86ad409.JPG","f1b7a9b0178c4c870ec548737a575a.JPG",
  "f3af2e10b08d2af198992d6b0f699e.JPG","f7632420c0e35783b3f91fe9833e38.JPG","f95b91ac0e4a33ce06b7878e7fa74c.JPG"
];

// Deterministic pseudo-random from index — keeps layout stable across renders.
function seedRand(seed) {
  let x = Math.sin(seed * 9301 + 49297) * 233280;
  return x - Math.floor(x);
}

function Life() {
  const { useState, useMemo } = React;
  const [active, setActive] = useState(null);

  // Shuffle pics deterministically once
  const pics = useMemo(() => {
    const arr = LIFE_PICS.map((src, i) => ({ src, i }));
    // Fisher-Yates with seeded rand
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(seedRand(i + 17) * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr.map((p, idx) => ({
      ...p,
      rot: (seedRand(idx + 3) - 0.5) * 5, // -2.5° ~ 2.5°
      xOffset: (seedRand(idx + 7) - 0.5) * 16, // -8px ~ 8px
      delay: idx * 0.04 % 1.2
    }));
  }, []);

  React.useEffect(() => {
    if (!active) return;
    const onKey = (e) => { if (e.key === "Escape") setActive(null); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [active]);

  return (
    <section id="life" className="relative bg-black">
      <div className="max-w-7xl mx-auto px-6 md:px-12 pt-32 pb-32">
        <div className="flex items-end justify-between flex-wrap gap-6 mb-12">
          <div>
            <div className="font-mono text-[10px] text-white/45 tracking-[0.3em] mb-4">// 04 — OFF WORK</div>
            <h2 className="hero-heading font-heading italic text-4xl sm:text-5xl md:text-7xl lg:text-[5.5rem] leading-[0.9] tracking-tight">
              <span className="not-italic font-cn font-light">个人</span>兴趣.
            </h2>
            <p className="font-cn text-white/60 text-sm md:text-base mt-4 max-w-lg leading-relaxed">
              旅行、拍照、做饭、看建筑。屏幕之外那些让我变得更有想法的事。
            </p>
          </div>
          <div className="flex gap-2 items-center">
            <GlassChip><Icon name="camera" className="h-3 w-3" /> {LIFE_PICS.length} 张片段</GlassChip>
          </div>
        </div>

        {/* Scattered masonry — CSS columns (responsive) */}
        <div className="life-masonry">
          {pics.map((p, idx) => (
            <button
              key={p.src}
              type="button"
              onClick={() => setActive(p)}
              className="life-pic group block w-full mb-3.5 rounded-2xl overflow-hidden relative cursor-pointer"
              style={{
                transform: `translateX(${p.xOffset}px) rotate(${p.rot}deg)`,
                boxShadow: "0 18px 40px -16px rgba(0,0,0,.6), 0 0 0 1px rgba(255,255,255,.06)",
                breakInside: "avoid",
                animation: `lifeDrop 0.9s cubic-bezier(.2,.7,.2,1) ${p.delay}s both`
              }}
            >
              <LazyImage
                src={`assets/pics/${p.src}`}
                alt=""
                className="w-full h-auto block transition-transform duration-500 group-hover:scale-[1.03]"
              />
              <div className="absolute inset-0 ring-0 group-hover:ring-1 ring-white/30 transition-all rounded-2xl pointer-events-none"></div>
            </button>
          ))}
        </div>
      </div>

      {/* Photo lightbox */}
      {active && (
        <div
          className="fixed inset-0 z-[100] bg-black/90 backdrop-blur-md flex items-center justify-center p-6 md:p-12"
          onClick={() => setActive(null)}
        >
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); setActive(null); }}
            className="absolute top-6 right-6 w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 border border-white/20 flex items-center justify-center text-white text-xl transition-colors z-10"
            aria-label="Close"
          >×</button>
          <img
            src={`assets/pics/${active.src}`}
            alt=""
            className="max-w-full max-h-[88vh] object-contain rounded-2xl shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      )}
    </section>
  );
}

/* ─────────── Footer / contact ─────────── */
function Footer() {
  return (
    <footer id="contact" className="relative bg-black overflow-hidden">
      <div className="absolute inset-0 stars opacity-30 pointer-events-none"></div>
      <div className="max-w-7xl mx-auto px-6 md:px-12 py-32 relative z-10 text-center">
        <div className="font-mono text-[10px] text-white/45 tracking-[0.3em] mb-6">// LET'S TALK</div>
        <h2 className="hero-heading font-heading italic text-4xl sm:text-5xl md:text-7xl lg:text-[6.5rem] leading-[0.9] tracking-tight">
          See you on the other side.
        </h2>
        <p className="font-cn text-white/70 text-base md:text-lg mt-6 max-w-2xl mx-auto leading-relaxed">
          找我聊聊？关于 AI 产品、视频创作、Agent，或者只是想问问那本红色封皮的笔记本里写了什么。
        </p>

        <div className="mt-20 flex items-center justify-between border-t border-white/10 pt-6 flex-wrap gap-4">
          <div className="font-mono text-[10px] text-white/40 tracking-[0.25em]">© 2026 · YIJING LIN · 深圳</div>
          <div className="font-mono text-[10px] text-white/40 tracking-[0.25em]">DESIGNED · CODED · LIVED</div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { WebWorks, Life, Footer });
