
// Projects section — fetches from Sanity, full-width showcase with parallax

function ProjectCard({ project, index }) {
  const { t, lang } = useI18n();
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  const [parallax, setParallax] = React.useState(0);
  const [imgLoaded, setImgLoaded] = React.useState(false);
  const isEven = index % 2 === 0;

  const title = pickLocale(project.title, lang);
  const subtitle = pickLocale(project.subtitle, lang);
  const description = pickLocale(project.description, lang);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;

    const io = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) setVisible(true); },
      { threshold: 0.08 }
    );
    io.observe(el);

    const onScroll = () => {
      const rect = el.getBoundingClientRect();
      const center = rect.top + rect.height / 2 - window.innerHeight / 2;
      setParallax(center * 0.08);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();

    return () => { io.disconnect(); window.removeEventListener("scroll", onScroll); };
  }, []);

  const number = String(index + 1).padStart(2, "0");
  const stack = (project.technologies || []).join(" · ");
  const imageUrl = sanityImageUrl(project.mainImage, { width: 1600, quality: 85 });
  const subtitleLine = [subtitle, project.year].filter(Boolean).join(" · ");

  return (
    <article
      ref={ref}
      data-screen-label={`Project ${index + 1}`}
      style={{
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gridTemplateAreas: isEven ? '"visual content"' : '"content visual"',
        minHeight: "85vh",
        borderTop: "1px solid #161616",
        opacity: visible ? 1 : 0,
        transition: "opacity 0.9s cubic-bezier(0.16,1,0.3,1)",
      }}
      className="project-card"
    >
      {/* Visual */}
      <div
        style={{
          gridArea: "visual",
          position: "relative",
          overflow: "hidden",
          background: "#0c0c0e",
          minHeight: "clamp(300px, 50vh, 680px)",
        }}
      >
        <div style={{
          position: "absolute",
          inset: "-12%",
          transform: `translateY(${parallax}px)`,
          transition: "transform 0.05s linear",
        }}>
          {imageUrl ? (
            <img
              src={imageUrl}
              alt={title}
              loading="lazy"
              onLoad={() => setImgLoaded(true)}
              style={{
                width: "100%",
                height: "100%",
                objectFit: "cover",
                display: "block",
                filter: "grayscale(15%) brightness(0.92)",
                opacity: imgLoaded ? 1 : 0,
                transition: "opacity 0.6s ease",
              }}
            />
          ) : (
            <div style={{
              width: "100%",
              height: "100%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              background: "repeating-linear-gradient(135deg, #111 0px, #111 1px, #0d0d0d 1px, #0d0d0d 18px)",
              border: "1px solid #1e1e1e",
            }}>
              <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, color: "#2a2a2a", letterSpacing: "0.2em", textTransform: "uppercase" }}>
                {title}
              </span>
            </div>
          )}
        </div>

        <div style={{
          position: "absolute",
          bottom: "clamp(16px, 3vh, 28px)",
          left: "clamp(20px, 4vw, 48px)",
          fontFamily: "'Cormorant Garamond', serif",
          fontSize: "clamp(64px, 9vw, 120px)",
          fontWeight: 300,
          color: "#ededeb",
          mixBlendMode: "difference",
          lineHeight: 1,
          userSelect: "none",
          pointerEvents: "none",
        }}>
          {number}
        </div>
      </div>

      {/* Content */}
      <div style={{
        gridArea: "content",
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        padding: "clamp(40px, 6vw, 96px) clamp(32px, 5vw, 80px)",
      }}>
        {subtitleLine && (
          <p style={{
            fontFamily: "'DM Mono', monospace",
            fontSize: "clamp(9px, 0.9vw, 11px)",
            letterSpacing: "0.28em",
            color: "#888",
            textTransform: "uppercase",
            marginBottom: "clamp(16px, 2.5vh, 28px)",
            transform: visible ? "translateY(0)" : "translateY(20px)",
            opacity: visible ? 1 : 0,
            transition: "all 0.8s cubic-bezier(0.16,1,0.3,1) 0.1s",
          }}>
            {subtitleLine}
          </p>
        )}

        <h2 style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontWeight: 300,
          fontSize: "clamp(48px, 6.5vw, 96px)",
          letterSpacing: "-0.02em",
          lineHeight: 0.9,
          color: "#ededeb",
          margin: "0 0 clamp(20px, 3vh, 36px)",
          transform: visible ? "translateY(0)" : "translateY(30px)",
          opacity: visible ? 1 : 0,
          transition: "all 0.9s cubic-bezier(0.16,1,0.3,1) 0.18s",
        }}>
          {title}
        </h2>

        {description && (
          <p style={{
            fontFamily: "'DM Sans', sans-serif",
            fontWeight: 300,
            fontSize: "clamp(14px, 1.2vw, 17px)",
            lineHeight: 1.7,
            color: "#666",
            maxWidth: 440,
            marginBottom: "clamp(24px, 4vh, 44px)",
            transform: visible ? "translateY(0)" : "translateY(20px)",
            opacity: visible ? 1 : 0,
            transition: "all 0.9s cubic-bezier(0.16,1,0.3,1) 0.28s",
          }}>
            {description}
          </p>
        )}

        {stack && (
          <p style={{
            fontFamily: "'DM Mono', monospace",
            fontSize: "clamp(9px, 0.85vw, 11px)",
            letterSpacing: "0.14em",
            color: "#777",
            marginBottom: "clamp(28px, 4vh, 48px)",
            transform: visible ? "translateY(0)" : "translateY(20px)",
            opacity: visible ? 1 : 0,
            transition: "all 0.9s cubic-bezier(0.16,1,0.3,1) 0.36s",
          }}>
            {stack}
          </p>
        )}

        {(project.siteUrl || project.githubUrl) && (
          <div style={{
            display: "flex",
            gap: "clamp(16px, 2vw, 28px)",
            transform: visible ? "translateY(0)" : "translateY(20px)",
            opacity: visible ? 1 : 0,
            transition: "all 0.9s cubic-bezier(0.16,1,0.3,1) 0.44s",
          }}>
            {project.siteUrl && (
              <MagneticElement strength={0.4}>
                <a href={project.siteUrl} target="_blank" rel="noopener noreferrer" className="project-link cursor-link">
                  {t.projects.live}
                  <span className="project-link-arrow">↗</span>
                </a>
              </MagneticElement>
            )}
            {project.githubUrl && (
              <MagneticElement strength={0.4}>
                <a href={project.githubUrl} target="_blank" rel="noopener noreferrer" className="project-link project-link--ghost cursor-link">
                  {t.projects.repo}
                  <span className="project-link-arrow">↗</span>
                </a>
              </MagneticElement>
            )}
          </div>
        )}
      </div>
    </article>
  );
}

function ProjectsSection() {
  const { t } = useI18n();
  const p = t.projects;
  const { items, status } = useSanityProjects();

  return (
    <section id="projects" data-screen-label="04 Projects" style={{ paddingTop: "clamp(80px, 10vh, 120px)" }}>
      <div style={{ padding: "0 clamp(24px, 8vw, 120px)", marginBottom: "clamp(40px, 6vh, 72px)" }}>
        <RevealText delay={0} className="section-label">
          <span>{p.label}</span>
        </RevealText>
      </div>

      <div>
        {items.map((project, i) => (
          <ProjectCard key={project._id} project={project} index={i} />
        ))}

        {status === "loading" && (
          <div style={{ padding: "clamp(80px, 14vh, 160px) clamp(24px, 8vw, 120px)", borderTop: "1px solid #161616", textAlign: "center" }}>
            <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, letterSpacing: "0.28em", color: "#2a2a2a", textTransform: "uppercase" }}>
              {p.loading}
            </span>
          </div>
        )}

        {status === "ready" && items.length === 0 && (
          <div style={{ padding: "clamp(80px, 14vh, 160px) clamp(24px, 8vw, 120px)", borderTop: "1px solid #161616", textAlign: "center" }}>
            <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 10, letterSpacing: "0.28em", color: "#2a2a2a", textTransform: "uppercase" }}>
              {p.empty}
            </span>
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { ProjectsSection });