const { SectionHeading } = window.TheVisualsBrothersDesignSystem_fe64e0;

const items = [
  { image: "site/work-raastah.jpg", category: "AI Commercial", title: "RAASTAH", url: "https://www.instagram.com/reel/DUQmJkrDYp5/" },
  { image: "site/work-odyssey.jpg", category: "Physical Film", title: "The Life After Watching The Odyssey", url: "https://www.instagram.com/reel/DbYcDG4A8UM/" },
  { image: "site/work-football.jpg", category: "AI Commercial", title: "Football In Pakistan", url: "https://www.instagram.com/reel/DanhLsOAzZQ/" },
  { image: "site/work-oakley.jpg", category: "AI Commercial", title: "Oakley", url: "https://www.instagram.com/reel/DblNmRaNCcu/" },
  { image: "site/work-obsession.jpg", category: "Physical + VFX", title: "Obsession", url: "https://www.instagram.com/reel/Dax0Y0xgntP/" },
  { image: "site/work-gullylabs.jpg", category: "AI Commercial", title: "Gully Labs", url: "https://www.instagram.com/reel/DZ7lQOZAo1H/" },
  { image: "site/work-benzgadi.jpg", category: "AI Commercial", title: "Benz Gadi", url: "https://www.instagram.com/reel/DVeHfDtjfQn/" },
  { image: "site/work-strangerthings.jpg", category: "Physical + VFX", title: "Stranger Things", url: "https://www.instagram.com/reel/DTAo5AYDUaX/" },
  { image: "site/work-movement.jpg", category: "AI Fashion Commercial", title: "Movement", url: "https://www.instagram.com/reel/DUn6VqxDFdR/" },
];

const musicItems = [
  { image: "site/work-sawal.jpg", category: "Music Video", title: "Sawal", subtitle: "Muddabir Khan", url: "https://www.youtube.com/watch?v=Ne6zdvQVq1g" },
  { image: "site/work-tuhinahi.jpg", category: "Music Video", title: "Tu Hi Nahi", subtitle: "Khizer Hameed", url: "https://youtu.be/p1w9OdfueHM?si=1HTbYH0djF7KreAr" },
  { image: "site/work-nainadisharab.jpg", category: "Music Video", title: "Naina Di Sharab", subtitle: "Ramzan Jani", url: "https://youtu.be/ElrVekpB2EE?si=CbM-epzkAV-4aBMN" },
];

let vbActiveVideo = null;

function WorkCard({ image, video, category, title, subtitle, url }) {
  const [hover, setHover] = React.useState(false);
  const [videoReady, setVideoReady] = React.useState(false);
  const videoRef = React.useRef(null);
  const stopTimerRef = React.useRef(null);
  const canHoverPreview = video && typeof window !== "undefined" && window.matchMedia && window.matchMedia("(hover: hover) and (pointer: fine)").matches;

  function startPreview() {
    setHover(true);
    if (!canHoverPreview) return;
    const v = videoRef.current;
    if (!v) return;
    if (vbActiveVideo && vbActiveVideo !== v) { vbActiveVideo.pause(); }
    vbActiveVideo = v;
    v.currentTime = 0;
    v.muted = true;
    const playPromise = v.play();
    if (playPromise) playPromise.then(() => setVideoReady(true)).catch(() => {});
    clearTimeout(stopTimerRef.current);
    stopTimerRef.current = setTimeout(() => { if (v) v.pause(); }, 2800);
  }
  function stopPreview() {
    setHover(false);
    setVideoReady(false);
    clearTimeout(stopTimerRef.current);
    const v = videoRef.current;
    if (v) { v.pause(); v.currentTime = 0; }
    if (vbActiveVideo === v) vbActiveVideo = null;
  }

  return (
    <a href={url} target="_blank" rel="noopener noreferrer" onMouseEnter={startPreview} onMouseLeave={stopPreview} style={{
      position: "relative", display: "block", aspectRatio: "16/9", borderRadius: "var(--radius-default)", overflow: "hidden",
      border: `1px solid ${hover ? "var(--border-hover)" : "var(--border-default)"}`,
      boxShadow: hover ? "var(--shadow-portfolio-hover)" : "none",
      transform: hover ? "translateY(-8px)" : "translateY(0)",
      transition: "all var(--duration-standard) var(--ease-portfolio)", cursor: "pointer", textDecoration: "none",
    }}>
      <div style={{
        position: "absolute", inset: 0, backgroundImage: `url('${image}')`, backgroundSize: "cover", backgroundPosition: "center",
        transform: hover ? "scale(1.04)" : "scale(1)",
        opacity: videoReady ? 0 : 1,
        transition: "transform var(--duration-standard) ease, opacity 300ms ease",
      }} />
      {canHoverPreview && hover ? (
        <video ref={videoRef} src={video} muted playsInline preload="none" style={{
          position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover",
          opacity: videoReady ? 1 : 0, transition: "opacity 300ms ease",
        }} />
      ) : null}
      <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{
          width: "56px", height: "56px", borderRadius: "50%",
          border: `2px solid ${hover ? "var(--accent-primary)" : "var(--text-primary)"}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          transform: hover ? "scale(1)" : "scale(0)", transition: "transform var(--duration-fast) ease, border-color 0.3s ease",
          background: "rgba(15,23,42,0.4)", boxShadow: hover ? "0 0 16px rgba(217,119,6,0.5)" : "none",
        }}>
          <i data-lucide="play" style={{ width: "22px", height: "22px", color: "var(--text-primary)", marginLeft: "2px" }}></i>
        </div>
      </div>
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0, padding: "20px",
        background: "linear-gradient(180deg, transparent, rgba(15,23,42,0.9))",
        opacity: hover ? 1 : 0, transform: hover ? "translateY(0)" : "translateY(10px)",
        transition: "all var(--duration-standard) ease",
      }}>
        <span style={{
          display: "inline-block", fontSize: "12px", textTransform: "uppercase", letterSpacing: "1px",
          color: hover ? "var(--golden)" : "var(--accent-primary)", fontFamily: "var(--font-body)", fontWeight: 600,
          transition: "color 0.3s ease",
        }}>{category}</span>
        <div style={{
          color: "var(--text-primary)", fontSize: "18px", marginTop: "4px", fontFamily: "var(--font-body)",
          textShadow: hover ? "0 0 14px rgba(255,255,255,0.5)" : "none", transition: "text-shadow 0.3s ease",
        }}>{title}{subtitle ? <span style={{ color: "var(--text-secondary)", fontSize: "14px" }}> — {subtitle}</span> : null}</div>
      </div>
    </a>
  );
}

function Portfolio() {
  const canvasRef = React.useRef(null);
  React.useEffect(() => {
    const canvas = canvasRef.current, section = canvas.parentElement;
    const ctx = canvas.getContext("2d");
    let w, h, particles, mouse = { x: -9999, y: -9999 };
    function resize() {
      w = canvas.width = section.offsetWidth;
      h = canvas.height = section.offsetHeight;
    }
    function makeParticles() {
      const count = Math.round((w * h) / 18000);
      particles = Array.from({ length: count }, () => ({
        x: Math.random() * w, y: Math.random() * h,
        vx: (Math.random() - 0.5) * 0.25, vy: (Math.random() - 0.5) * 0.25,
        r: Math.random() * 2 + 1, hue: Math.random() < 0.5 ? "217,119,6" : "245,158,11",
        a: Math.random() * 0.5 + 0.3,
      }));
    }
    const spriteSize = 48, spriteR = spriteSize / 2;
    const hues = ["217,119,6", "245,158,11"];
    const sprites = {};
    hues.forEach((hue) => {
      const s = document.createElement("canvas");
      s.width = spriteSize; s.height = spriteSize;
      const sctx = s.getContext("2d");
      const grad = sctx.createRadialGradient(spriteR, spriteR, 0, spriteR, spriteR, spriteR);
      grad.addColorStop(0, `rgba(${hue},1)`);
      grad.addColorStop(1, `rgba(${hue},0)`);
      sctx.fillStyle = grad;
      sctx.beginPath(); sctx.arc(spriteR, spriteR, spriteR, 0, Math.PI * 2); sctx.fill();
      sprites[hue] = s;
    });
    resize(); makeParticles();
    window.addEventListener("resize", () => { resize(); makeParticles(); });
    section.addEventListener("mousemove", (e) => {
      const r = section.getBoundingClientRect();
      mouse.x = e.clientX - r.left; mouse.y = e.clientY - r.top;
    });
    section.addEventListener("mouseleave", () => { mouse.x = -9999; mouse.y = -9999; });
    let raf = null, frameCount = 0, cachedLines = [];
    function tick() {
      ctx.clearRect(0, 0, w, h);
      particles.forEach((p) => {
        const dx = p.x - mouse.x, dy = p.y - mouse.y, dist = Math.sqrt(dx * dx + dy * dy);
        if (dist < 120) {
          const f = (120 - dist) / 120;
          p.x += (dx / dist) * f * 2.2; p.y += (dy / dist) * f * 2.2;
        }
        p.x += p.vx; p.y += p.vy;
        if (p.x < 0) p.x = w; if (p.x > w) p.x = 0;
        if (p.y < 0) p.y = h; if (p.y > h) p.y = 0;
        const d = p.r * 4 * 2;
        ctx.globalAlpha = p.a;
        ctx.drawImage(sprites[p.hue], p.x - d / 2, p.y - d / 2, d, d);
      });
      ctx.globalAlpha = 1;
      if (frameCount % 3 === 0) {
        cachedLines = [];
        for (let i = 0; i < particles.length; i++) {
          for (let j = i + 1; j < particles.length; j++) {
            const a = particles[i], b = particles[j];
            const d = Math.hypot(a.x - b.x, a.y - b.y);
            if (d < 90) cachedLines.push([a.x, a.y, b.x, b.y, 0.12 * (1 - d / 90)]);
          }
        }
      }
      frameCount++;
      cachedLines.forEach(([ax, ay, bx, by, alpha]) => {
        ctx.strokeStyle = `rgba(217,119,6,${alpha})`;
        ctx.lineWidth = 1;
        ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by); ctx.stroke();
      });
      raf = requestAnimationFrame(tick);
    }
    const io = new IntersectionObserver((entries) => {
      const visible = entries[0].isIntersecting;
      if (visible && raf === null) { raf = requestAnimationFrame(tick); }
      else if (!visible && raf !== null) { cancelAnimationFrame(raf); raf = null; }
    }, { threshold: 0 });
    io.observe(section);
    return () => { cancelAnimationFrame(raf); io.disconnect(); };
  }, []);
  return (
    <section id="work" style={{
      padding: "var(--space-section-v) var(--space-section-h)",
      background: "var(--slate-900)",
      position: "relative", overflow: "hidden",
    }}>
      <div style={{ position: "absolute", inset: 0, zIndex: 0, pointerEvents: "none", color: "rgba(255,255,255,0.95)", mixBlendMode: "soft-light" }}>
        <svg width="0" height="0" style={{ position: "absolute" }}>
          <defs>
            <pattern id="vb-hatch" width="6" height="6" patternTransform="rotate(45)" patternUnits="userSpaceOnUse">
              <line x1="0" y1="0" x2="0" y2="6" stroke="currentColor" strokeWidth="1" opacity="0.5" />
            </pattern>
          </defs>
        </svg>
        {/* SLR camera, top-left */}
        <svg viewBox="0 0 120 90" style={{ position: "absolute", top: "16px", left: "16px", width: "120px", opacity: 0.2, transform: "rotate(-7deg)" }}>
          <g fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <rect x="10" y="25" width="80" height="55" rx="6" fill="url(#vb-hatch)" />
            <rect x="11" y="26" width="80" height="55" rx="6" />
            <rect x="35" y="10" width="30" height="18" rx="3" />
            <circle cx="50" cy="52" r="20" />
            <circle cx="51" cy="51" r="20" />
            <circle cx="50" cy="52" r="9" fill="url(#vb-hatch)" />
            <rect x="76" y="33" width="10" height="8" rx="2" />
            <line x1="20" y1="35" x2="30" y2="35" />
          </g>
        </svg>
        {/* twin-lens camera, bottom-left */}
        <svg viewBox="0 0 100 120" style={{ position: "absolute", bottom: "10px", left: "40px", width: "90px", opacity: 0.2, transform: "rotate(5deg)" }}>
          <g fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <rect x="15" y="15" width="70" height="90" rx="4" fill="url(#vb-hatch)" />
            <rect x="16" y="16" width="70" height="90" rx="4" />
            <rect x="25" y="5" width="20" height="14" rx="2" />
            <circle cx="50" cy="50" r="18" />
            <circle cx="51" cy="49" r="18" />
            <circle cx="50" cy="85" r="14" />
            <circle cx="51" cy="84" r="14" fill="url(#vb-hatch)" />
          </g>
        </svg>
        {/* film reel, bottom-right */}
        <svg viewBox="0 0 120 120" style={{ position: "absolute", bottom: "20px", right: "20px", width: "130px", opacity: 0.2, transform: "rotate(8deg)" }}>
          <g fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="60" cy="60" r="45" />
            <circle cx="61" cy="59" r="45" />
            <circle cx="60" cy="60" r="10" fill="url(#vb-hatch)" />
            <circle cx="60" cy="27" r="10" />
            <circle cx="88" cy="45" r="10" />
            <circle cx="88" cy="75" r="10" />
            <circle cx="60" cy="93" r="10" />
            <circle cx="32" cy="75" r="10" />
            <circle cx="32" cy="45" r="10" />
            <path d="M18 100 Q -10 130 -30 150" />
          </g>
        </svg>
      </div>
      <img src="site/doodle-crown.png" alt="" aria-hidden="true" style={{ position: "absolute", top: "-24px", right: "64px", width: "64px", opacity: 0.18, transform: "rotate(6deg)", zIndex: 0, pointerEvents: "none" }} />
      <img src="site/doodle-sparkle.png" alt="" aria-hidden="true" style={{ position: "absolute", top: "46%", left: "-20px", width: "46px", opacity: 0.15, transform: "rotate(-8deg)", zIndex: 0, pointerEvents: "none" }} />
      <img src="site/doodle-photoframe.png" alt="" aria-hidden="true" style={{ position: "absolute", bottom: "-30px", right: "12%", width: "70px", opacity: 0.14, transform: "rotate(-5deg)", zIndex: 0, pointerEvents: "none" }} />
      <canvas ref={canvasRef} style={{ position: "absolute", inset: 0, zIndex: 0, pointerEvents: "auto" }} />
      <div style={{ position: "relative", zIndex: 1, marginBottom: "var(--gap-lg)" }}>
        <SectionHeading text="SELECTED" accent="WORK" />
      </div>
      <div className="vb-portfolio-grid" style={{ position: "relative", zIndex: 1, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "var(--gap-md)" }}>
        {items.map((it, i) => (
          <div className="vb-reveal" style={{ transitionDelay: `${i * 100}ms` }} key={it.title}>
            <WorkCard {...it} />
          </div>
        ))}
      </div>
      <div style={{ position: "relative", zIndex: 1, margin: "var(--gap-lg) 0 var(--gap-md)" }}>
        <SectionHeading text="MUSIC" accent="VIDEOS" />
      </div>
      <div className="vb-portfolio-grid" style={{ position: "relative", zIndex: 1, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "var(--gap-md)" }}>
        {musicItems.map((it, i) => (
          <div className="vb-reveal" style={{ transitionDelay: `${i * 100}ms` }} key={it.title}>
            <WorkCard {...it} />
          </div>
        ))}
      </div>
    </section>
  );
}

window.Portfolio = Portfolio;
