// project-page.jsx — single project view + next-project transition
const { useState: usePState, useEffect: usePEffect, useRef: usePRef, useMemo: usePMemo } = React;

/* ============================================================
   DragScrollRow — horizontal scroll container with click-and-drag pan
   ============================================================ */
function DragScrollRow({ children, style }) {
  const ref = usePRef(null);
  usePEffect(() => {
    const el = ref.current;
    if (!el) return;
    let isDown = false;
    let startX = 0;
    let startScroll = 0;
    let lastX = 0;
    let lastT = 0;
    let velocity = 0;
    let moved = false;
    let momentumRaf = null;

    const cancelMomentum = () => {
      if (momentumRaf) { cancelAnimationFrame(momentumRaf); momentumRaf = null; }
    };
    const runMomentum = () => {
      const step = () => {
        velocity *= 0.94; // friction
        el.scrollLeft -= velocity;
        if (Math.abs(velocity) > 0.4) {
          momentumRaf = requestAnimationFrame(step);
        } else {
          momentumRaf = null;
          el.style.scrollSnapType = ""; // restore snap
        }
      };
      momentumRaf = requestAnimationFrame(step);
    };

    const onDown = (e) => {
      if (e.button !== 0) return;
      cancelMomentum();
      isDown = true;
      moved = false;
      startX = e.clientX;
      lastX = e.clientX;
      lastT = performance.now();
      startScroll = el.scrollLeft;
      velocity = 0;
      el.style.cursor = "grabbing";
      el.style.scrollSnapType = "none"; // disable snap during drag for smooth feel
      el.classList.add("is-dragging");
      try { el.setPointerCapture(e.pointerId); } catch (_) {}
    };
    const onMove = (e) => {
      if (!isDown) return;
      const dx = e.clientX - startX;
      if (Math.abs(dx) > 3) moved = true;
      el.scrollLeft = startScroll - dx;
      // update velocity (px / ms) based on recent movement
      const now = performance.now();
      const dt = Math.max(1, now - lastT);
      velocity = (e.clientX - lastX) / dt * 16; // normalized to ~60fps frame
      lastX = e.clientX;
      lastT = now;
      e.preventDefault();
    };
    const stop = (e) => {
      if (!isDown) return;
      isDown = false;
      el.style.cursor = "grab";
      el.classList.remove("is-dragging");
      if (e && e.pointerId !== undefined) {
        try { el.releasePointerCapture(e.pointerId); } catch (_) {}
      }
      if (moved) {
        const block = (ev) => { ev.stopPropagation(); ev.preventDefault(); };
        window.addEventListener("click", block, { capture: true, once: true });
        // momentum decay
        if (Math.abs(velocity) > 0.5) {
          runMomentum();
        } else {
          el.style.scrollSnapType = "";
        }
      } else {
        el.style.scrollSnapType = "";
      }
    };

    el.addEventListener("pointerdown", onDown);
    el.addEventListener("pointermove", onMove);
    el.addEventListener("pointerup", stop);
    el.addEventListener("pointercancel", stop);
    el.addEventListener("pointerleave", stop);

    return () => {
      cancelMomentum();
      el.removeEventListener("pointerdown", onDown);
      el.removeEventListener("pointermove", onMove);
      el.removeEventListener("pointerup", stop);
      el.removeEventListener("pointercancel", stop);
      el.removeEventListener("pointerleave", stop);
    };
  }, []);
  return (
    <div ref={ref}
      style={{
        display: "flex",
        gap: 24,
        overflowX: "auto",
        scrollSnapType: "x mandatory",
        scrollBehavior: "auto",
        WebkitOverflowScrolling: "touch",
        scrollbarWidth: "thin",
        cursor: "grab",
        userSelect: "none",
        touchAction: "pan-y",
        ...style,
      }}>
      {children}
    </div>
  );
}

/* ============================================================
   Lightbox — modal for zooming carousel images
   ============================================================ */
function Lightbox({ src, onClose }) {
  const [zoom, setZoom] = usePState(1);
  const [pan, setPan] = usePState({ x: 0, y: 0 });
  const dragState = usePRef({ down: false, startX: 0, startY: 0, sx: 0, sy: 0 });

  usePEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  const onWheel = (e) => {
    e.preventDefault();
    const delta = -e.deltaY * 0.0025;
    setZoom((z) => Math.max(1, Math.min(5, z * (1 + delta))));
  };
  const onDoubleClick = () => {
    setZoom((z) => (z > 1 ? 1 : 2.2));
    if (zoom > 1) setPan({ x: 0, y: 0 });
  };
  const onDown = (e) => {
    if (zoom <= 1) return;
    dragState.current = { down: true, startX: e.clientX, startY: e.clientY, sx: pan.x, sy: pan.y };
  };
  const onMove = (e) => {
    if (!dragState.current.down) return;
    setPan({
      x: dragState.current.sx + (e.clientX - dragState.current.startX),
      y: dragState.current.sy + (e.clientY - dragState.current.startY),
    });
  };
  const onUp = () => { dragState.current.down = false; };

  return ReactDOM.createPortal(
    <div onClick={onClose}
         onPointerMove={onMove}
         onPointerUp={onUp}
         onPointerLeave={onUp}
         style={{
           position: "fixed", inset: 0, zIndex: 9998,
           background: "rgba(8,8,10,0.94)",
           backdropFilter: "blur(8px)",
           display: "flex", alignItems: "center", justifyContent: "center",
           cursor: zoom > 1 ? "grab" : "zoom-out",
           animation: "lightboxIn 0.3s var(--ease)",
         }}>
      <button onClick={(e) => { e.stopPropagation(); onClose(); }}
              aria-label="Close"
              style={{
                position: "absolute", top: 24, right: 24, zIndex: 2,
                width: 52, height: 52, borderRadius: "50%",
                border: "1px solid rgba(255,255,255,0.2)",
                background: "rgba(255,255,255,0.08)",
                color: "#fff", fontSize: 22, lineHeight: 1,
                cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "center",
                transition: "background 0.2s, transform 0.2s",
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.18)"; e.currentTarget.style.transform = "scale(1.05)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.08)"; e.currentTarget.style.transform = "scale(1)"; }}>
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
          <path d="M3 3 L15 15 M15 3 L3 15" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      </button>

      <div className="mono" style={{ position: "absolute", top: 32, left: 32, color: "rgba(255,255,255,0.55)", fontSize: 11, letterSpacing: "0.1em" }}>
        {zoom > 1 ? `${zoom.toFixed(1)}× · drag to pan · scroll to zoom` : "scroll to zoom · double-click for 2×"}
      </div>

      <div onClick={(e) => e.stopPropagation()}
           onWheel={onWheel}
           onDoubleClick={onDoubleClick}
           onPointerDown={onDown}
           style={{
             maxWidth: "92vw",
             maxHeight: "88vh",
             display: "flex", alignItems: "center", justifyContent: "center",
             transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
             transition: dragState.current.down ? "none" : "transform 0.18s var(--ease)",
             cursor: zoom > 1 ? (dragState.current.down ? "grabbing" : "grab") : "zoom-in",
             willChange: "transform",
           }}>
        <img src={src} alt="" draggable={false}
             style={{
               maxWidth: "92vw", maxHeight: "88vh",
               display: "block",
               objectFit: "contain",
               pointerEvents: "none",
               WebkitUserDrag: "none",
               boxShadow: "0 30px 80px rgba(0,0,0,0.6)",
               borderRadius: 4,
             }}/>
      </div>
    </div>,
    document.body
  );
}

/* ============================================================
   ProjectArt — placeholder visual using grain + circles + type
   ============================================================ */
function ProjectArt({ p, compact, full, stylized }) {
  // Use real image when available — UNLESS stylized is requested
  if (p.cover && !stylized) {
    return (
      <div style={{ position: "relative", width: "100%", height: "100%", aspectRatio: compact ? undefined : "16/10", overflow: "hidden", background: "#0a0a0a" }}>
        <img src={p.cover} alt={p.name} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2'/><feColorMatrix values='0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>\")",
          mixBlendMode: "multiply", opacity: 0.25, pointerEvents: "none",
        }}/>
        <div style={{
          position: "absolute", bottom: compact ? 14 : 28, left: compact ? 14 : 28, right: compact ? 14 : 28,
          display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 12, color: "#fff",
          textShadow: "0 2px 12px rgba(0,0,0,0.4)",
        }}>
          <div>
            <div style={{ fontFamily: "JetBrains Mono", fontSize: 10, opacity: 0.85, letterSpacing: "0.1em" }}>{p.n} / {p.year}</div>
            <div style={{ fontSize: compact ? 20 : "clamp(26px, 3vw, 48px)", fontWeight: 500, letterSpacing: "-0.02em", marginTop: 4, lineHeight: 1 }}>
              {p.name}
            </div>
          </div>
        </div>
      </div>
    );
  }
  // unique 'art direction' per project, all in B&W
  const variants = {
    psicoai:    { bg: "#0a0a0a", fg: "#f6f5f2", motif: "circle-stack" },
    photonow:   { bg: "#1c1c1c", fg: "#ecebe7", motif: "stacked-rect" },
    atem:       { bg: "#f6f5f2", fg: "#0a0a0a", motif: "editorial" },
    madeireira: { bg: "#0a0a0a", fg: "#f6f5f2", motif: "vertical-bars" },
    projeti:    { bg: "#ecebe7", fg: "#0a0a0a", motif: "grid-dots" },
    karbono0:   { bg: "#0a0a0a", fg: "#ecebe7", motif: "circle-stack" },
  };
  const v = variants[p.id] || variants.psicoai;
  const Motif = ({ id }) => {
    if (id === "circle-stack") {
      return (<>
        <div style={{ position: "absolute", top: "10%", left: "50%", transform: "translateX(-50%)", width: "120%", aspectRatio: "1", borderRadius: "50%", border: `1px solid ${v.fg}`, opacity: 0.35 }} />
        <div style={{ position: "absolute", top: "20%", left: "50%", transform: "translateX(-50%)", width: "85%", aspectRatio: "1", borderRadius: "50%", border: `1px solid ${v.fg}`, opacity: 0.6 }} />
        <div style={{ position: "absolute", top: "30%", left: "50%", transform: "translateX(-50%)", width: "55%", aspectRatio: "1", borderRadius: "50%", border: `1px solid ${v.fg}`, opacity: 0.9 }} />
        <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: "1px", background: v.fg, opacity: 0.4 }} />
        <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: "1px", background: v.fg, opacity: 0.4 }} />
      </>);
    }
    if (id === "stacked-rect") {
      return (<>
        {[0, 1, 2, 3].map(i => (
          <div key={i} style={{
            position: "absolute",
            top: `${15 + i * 8}%`,
            left: `${15 + i * 4}%`,
            width: "55%",
            height: "55%",
            border: `1px solid ${v.fg}`,
            opacity: 0.25 + i * 0.18,
            background: i === 3 ? v.fg : "transparent",
          }} />
        ))}
      </>);
    }
    if (id === "editorial") {
      return (<>
        <div style={{ position: "absolute", top: "20%", left: "8%", right: "8%", display: "flex", flexDirection: "column", gap: 10 }}>
          {[100, 80, 92, 60, 75, 50].map((w, i) => (
            <div key={i} style={{ height: 1, width: `${w}%`, background: v.fg, opacity: 0.6 }} />
          ))}
        </div>
        <div style={{ position: "absolute", top: "8%", left: "8%", width: 18, height: 18, borderRadius: "50%", border: `1px solid ${v.fg}` }} />
        <div style={{ position: "absolute", bottom: "10%", right: "8%", fontFamily: "JetBrains Mono", fontSize: 10, color: v.fg, opacity: 0.7, letterSpacing: "0.1em" }}>EDITORIAL</div>
      </>);
    }
    if (id === "vertical-bars") {
      return (<>
        {Array.from({ length: 18 }).map((_, i) => (
          <div key={i} style={{
            position: "absolute",
            left: `${(i / 18) * 100}%`,
            top: "20%", bottom: "20%",
            width: 1,
            background: v.fg,
            opacity: 0.15 + (i % 4) * 0.18,
          }} />
        ))}
        <div style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", width: 50, height: 50, borderRadius: "50%", border: `1px solid ${v.fg}` }} />
      </>);
    }
    if (id === "grid-dots") {
      return (<>
        <div style={{
          position: "absolute", inset: "12%",
          backgroundImage: `radial-gradient(${v.fg} 1px, transparent 1px)`,
          backgroundSize: "16px 16px",
          opacity: 0.3,
        }} />
        <div style={{ position: "absolute", top: "30%", left: "30%", width: "40%", height: "40%", border: `1px solid ${v.fg}`, opacity: 0.7 }} />
      </>);
    }
    return null;
  };

  return (
    <div style={{
      position: "relative",
      width: "100%",
      height: full ? "100%" : (compact ? "100%" : "100%"),
      aspectRatio: compact ? undefined : "16/10",
      background: v.bg,
      color: v.fg,
      overflow: "hidden",
    }}>
      <Motif id={v.motif} />
      {/* grain layer */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2'/><feColorMatrix values='0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.7 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>\")",
        mixBlendMode: v.bg === "#f6f5f2" || v.bg === "#ecebe7" ? "multiply" : "screen",
        opacity: 0.35,
        pointerEvents: "none",
      }}/>
      <div style={{
        position: "absolute",
        bottom: compact ? 16 : 32,
        left: compact ? 16 : 32,
        right: compact ? 16 : 32,
        display: "flex",
        justifyContent: "space-between",
        alignItems: "flex-end",
        gap: 12,
      }}>
        <div>
          <div style={{ fontFamily: "JetBrains Mono", fontSize: 10, opacity: 0.6, letterSpacing: "0.1em" }}>{p.n} / {p.year}</div>
          <div style={{ fontSize: compact ? 22 : "clamp(28px, 3.5vw, 56px)", fontWeight: 500, letterSpacing: "-0.02em", marginTop: 4, lineHeight: 1 }}>
            {p.name}
          </div>
        </div>
        {!compact && (
          <div style={{ fontFamily: "JetBrains Mono", fontSize: 10, opacity: 0.6, letterSpacing: "0.1em", textAlign: "right" }}>
            {p.services && p.services.slice(0, 2).join(" / ")}
          </div>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   Project page
   ============================================================ */
function Project({ id, t, navigate, lang }) {
  const idx = PROJECTS.findIndex(x => x.id === id);
  const p = PROJECTS[idx];
  const next = PROJECTS[(idx + 1) % PROJECTS.length];
  const containerRef = usePRef(null);
  const [transitioning, setTransitioning] = usePState(false);
  const previewRef = usePRef(null);
  const [zoomSrc, setZoomSrc] = usePState(null);

  usePEffect(() => {
    window.scrollTo(0, 0);
    const el = containerRef.current;
    if (!el) return;
    gsap.fromTo(el.querySelectorAll("[data-fade-in]"),
      { y: 50, opacity: 0 },
      { y: 0, opacity: 1, duration: 1, ease: "expo.out", stagger: 0.08, delay: 0.1 }
    );
  }, [id]);

  const handleNext = () => {
    if (transitioning || !previewRef.current) return;
    setTransitioning(true);
    const el = previewRef.current;
    // Animate the preview to fullscreen
    const rect = el.getBoundingClientRect();
    const vh = window.innerHeight;
    const vw = window.innerWidth;

    // Place a clone fixed
    const clone = el.cloneNode(true);
    clone.style.position = "fixed";
    clone.style.left = rect.left + "px";
    clone.style.top = rect.top + "px";
    clone.style.width = rect.width + "px";
    clone.style.height = rect.height + "px";
    clone.style.margin = "0";
    clone.style.zIndex = "999";
    clone.style.borderRadius = "0";
    document.body.appendChild(clone);
    el.style.visibility = "hidden";

    gsap.to(clone, {
      left: 0, top: 0, width: vw, height: vh,
      duration: 1.1, ease: "expo.inOut",
      onComplete: () => {
        navigate("project", { id: next.id });
        // fade clone out after navigation
        setTimeout(() => {
          gsap.to(clone, { opacity: 0, duration: 0.5, onComplete: () => {
            clone.remove();
            setTransitioning(false);
          }});
        }, 50);
      }
    });
  };

  if (!p) return null;

  return (
    <section data-screen-label={`project-${p.id}`} ref={containerRef}>
      {/* Header */}
      <div style={{ padding: "60px var(--gutter) 40px" }}>
        <div data-fade-in style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 60 }}>
          <button onClick={() => navigate("work")} className="mono" style={{ display: "inline-flex", alignItems: "center", gap: 10, color: "var(--muted)" }}>
            <span style={{ display: "inline-block", transform: "rotate(180deg)" }}><Arrow size={12}/></span>
            {t.project.back}
          </button>
          <div className="mono" style={{ color: "var(--muted)" }}>{p.n} / {String(PROJECTS.length).padStart(2,"0")}</div>
        </div>

        <div data-fade-in style={{ marginBottom: 24 }}>
          <span className="mono" style={{ color: "var(--muted)", marginRight: 16 }}>{p.year}</span>
          <span className="mono" style={{ color: "var(--muted)" }}>{p.type[lang]}</span>
        </div>

        <h1 data-fade-in style={{
          fontSize: "clamp(56px, 10vw, 160px)",
          fontWeight: 500,
          letterSpacing: "-0.04em",
          lineHeight: 0.9,
          marginBottom: 40,
        }}>
          {p.name.includes(" ") ? <>
            {p.name.split(" ")[0]} <span className="italic-serif">{p.name.split(" ").slice(1).join(" ")}</span>
          </> : p.name}
        </h1>

        <div data-fade-in style={{ maxWidth: 760, fontSize: "var(--t-h3)", lineHeight: 1.4, marginBottom: 80 }}>
          {p.summary[lang]}
        </div>
      </div>

      {/* Cover */}
      <div data-fade-in style={{ padding: "0 var(--gutter)" }}>
        <div style={{ height: "min(78vh, 820px)", overflow: "hidden" }}>
          <ProjectArt p={p} full stylized/>
        </div>
      </div>

      {/* Context + banner image side-by-side (when cover exists) */}
      {p.cover && (
        <div data-fade-in style={{ padding: "100px var(--gutter) 60px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 60, alignItems: "center" }}>
            <div style={{ overflow: "hidden" }}>
              <img src={p.cover} alt={p.name} style={{ width: "100%", height: "auto", display: "block" }}/>
            </div>
            <div>
              <div className="mono" style={{ color: "var(--muted)", marginBottom: 16 }}>{t.project.context}</div>
              <p style={{ fontSize: "clamp(18px, 1.4vw, 22px)", lineHeight: 1.5, color: "var(--ink-soft)" }}>
                {p.context[lang]}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Meta grid */}
      <div style={{
        padding: p.cover ? "20px var(--gutter) 100px" : "100px var(--gutter)",
        display: "grid",
        gridTemplateColumns: p.cover ? "1fr" : "1fr 1fr",
        gap: 80,
      }}>
        {!p.cover && (
          <div data-fade-in>
            <div className="mono" style={{ color: "var(--muted)", marginBottom: 16 }}>{t.project.context}</div>
            <p style={{ fontSize: "clamp(18px, 1.4vw, 22px)", lineHeight: 1.5, color: "var(--ink-soft)" }}>
              {p.context[lang]}
            </p>
          </div>
        )}
        <div data-fade-in style={p.cover ? { maxWidth: 880, marginLeft: "auto" } : undefined}>
          <HairlineRow><span className="mono muted" style={{ flexBasis: 120 }}>{t.project.role}</span><span>{p.role[lang]}</span></HairlineRow>
          <HairlineRow><span className="mono muted" style={{ flexBasis: 120 }}>{t.project.year}</span><span>{p.year}</span></HairlineRow>
          <HairlineRow><span className="mono muted" style={{ flexBasis: 120 }}>{t.project.type}</span><span>{p.type[lang]}</span></HairlineRow>
          <HairlineRow><span className="mono muted" style={{ flexBasis: 120 }}>{t.project.services}</span>
            <span style={{ display: "inline-flex", flexWrap: "wrap", gap: 8 }}>
              {p.services.map((s, i) => (
                <span key={i} className="mono" style={{ padding: "5px 10px", border: "1px solid var(--hairline-strong)", borderRadius: 999 }}>{s}</span>
              ))}
            </span>
          </HairlineRow>
          {p.tools && (
            <HairlineRow><span className="mono muted" style={{ flexBasis: 120 }}>{lang === "pt" ? "Ferramentas" : "Tools"}</span>
              <span style={{ display: "inline-flex", flexWrap: "wrap", gap: 8 }}>
                {p.tools.map((s, i) => (
                  <span key={i} className="mono" style={{ padding: "5px 10px", border: "1px solid var(--hairline-strong)", borderRadius: 999 }}>{s}</span>
                ))}
              </span>
            </HairlineRow>
          )}
          <HairlineRow style={{ borderBottom: "1px solid var(--hairline)" }}><span className="mono muted" style={{ flexBasis: 120 }}>Palette</span>
            <span style={{ display: "inline-flex", gap: 6 }}>
              {p.palette.map((c, i) => <span key={i} style={{ width: 22, height: 22, borderRadius: "50%", background: c, border: "1px solid var(--hairline-strong)" }}/>)}
            </span>
          </HairlineRow>
        </div>
      </div>

      {/* Secondary visuals — varied compositions */}
      {p.gallery && p.gallery.length > 0 ? (
        <div style={{ padding: "0 var(--gutter) 120px" }}>
          {p.gallery.map((src, i) => (
            <div key={i} data-fade-in style={{
              marginBottom: 24,
              overflow: "hidden",
              maxWidth: i % 2 === 0 ? "100%" : "70%",
              marginLeft: i % 2 === 0 ? 0 : "auto",
            }}>
              <img src={src} alt={`${p.name} ${i+1}`} style={{ width: "100%", height: "auto", display: "block" }}/>
            </div>
          ))}
        </div>
      ) : (!p.cover && !p.carousels && (
        <div style={{ padding: "0 var(--gutter) 120px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24 }}>
          {[0, 1, 2].map(i => (
            <div key={i} data-fade-in style={{ aspectRatio: i === 1 ? "3/4" : "4/5", overflow: "hidden", marginTop: i === 1 ? 60 : 0 }}>
              <ProjectArt p={p} full stylized/>
            </div>
          ))}
        </div>
      ))}

      {/* Multi-carousels (app + extension + etc) */}
      {p.carousels && p.carousels.map((c, ci) => (
        <div key={ci} data-fade-in style={{ padding: "0 0 80px" }}>
          <div style={{ padding: "0 var(--gutter)", marginBottom: 28 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: c.description ? 14 : 0, flexWrap: "wrap", gap: 16 }}>
              <h3 style={{ fontSize: "clamp(26px, 3.2vw, 44px)", fontWeight: 500, letterSpacing: "-0.02em", lineHeight: 1.1 }}>
                {(c.title && c.title[lang]) || ""}
              </h3>
              <span className="mono" style={{ color: "var(--muted)" }}>
                {String(c.images.length).padStart(2, "0")} · {lang === "pt" ? "arraste lateralmente" : "drag horizontally"}
              </span>
            </div>
            {c.description && (
              <p style={{ maxWidth: 720, fontSize: "clamp(15px, 1.1vw, 18px)", lineHeight: 1.5, color: "var(--ink-soft)" }}>
                {c.description[lang]}
              </p>
            )}
          </div>
          <DragScrollRow style={{ padding: "0 var(--gutter) 24px" }}>
            {c.images.map((src, i) => (
              <div key={i}
                data-zoom-cursor
                onClick={() => setZoomSrc(src)}
                style={{
                  flex: "0 0 auto",
                  width: c.cardWidth || "clamp(280px, 30vw, 420px)",
                  aspectRatio: c.aspect || "16/9",
                  scrollSnapAlign: "start",
                  borderRadius: 16,
                  overflow: "hidden",
                  background: "#0a0a0a",
                  boxShadow: "0 24px 48px rgba(0,0,0,0.08)",
                }}>
                <img src={src} alt={`${p.name} ${i+1}`} draggable={false} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", pointerEvents: "none", WebkitUserDrag: "none" }}/>
              </div>
            ))}
          </DragScrollRow>
        </div>
      ))}

      {/* Screens carousel — horizontal scroll of mobile screens */}
      {p.screens && p.screens.length > 0 && (
        <div data-fade-in style={{ padding: "0 0 100px" }}>
          <div style={{ padding: "0 var(--gutter)", display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 28 }}>
            <span className="mono" style={{ color: "var(--muted)" }}>{lang === "pt" ? "Telas · arraste lateralmente" : "Screens · drag horizontally"}</span>
            <span className="mono" style={{ color: "var(--muted)" }}>{String(p.screens.length).padStart(2, "0")}</span>
          </div>
          <DragScrollRow style={{ padding: "0 var(--gutter) 24px" }}>
            {p.screens.map((src, i) => (
              <div key={i}
                data-zoom-cursor
                onClick={() => setZoomSrc(src)}
                style={{
                  flex: "0 0 auto",
                  width: "clamp(220px, 22vw, 320px)",
                  aspectRatio: "9/19.5",
                  scrollSnapAlign: "start",
                  borderRadius: 20,
                  overflow: "hidden",
                  background: "#0a0a0a",
                }}>
                <img src={src} alt={`${p.name} screen ${i+1}`} draggable={false} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", pointerEvents: "none", WebkitUserDrag: "none" }}/>
              </div>
            ))}
          </DragScrollRow>
        </div>
      )}

      {/* Prototype CTA */}
      {p.prototypeUrl && (
        <div data-fade-in style={{ padding: "0 var(--gutter) 120px" }}>
          <a href={p.prototypeUrl} target="_blank" rel="noopener noreferrer"
             style={{
               display: "flex",
               justifyContent: "space-between",
               alignItems: "center",
               gap: 32,
               padding: "40px 48px",
               border: "1px solid var(--hairline-strong)",
               borderRadius: 999,
               textDecoration: "none",
               color: "var(--ink)",
               transition: "background 0.4s var(--ease), color 0.4s var(--ease), transform 0.4s var(--ease)",
               flexWrap: "wrap",
             }}
             onMouseEnter={e => { e.currentTarget.style.background = "var(--ink)"; e.currentTarget.style.color = "var(--inv)"; }}
             onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink)"; }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <span className="mono" style={{ opacity: 0.6 }}>{lang === "pt" ? "Protótipo interativo · Figma" : "Interactive prototype · Figma"}</span>
              <span style={{ fontSize: "clamp(22px, 2.4vw, 34px)", fontWeight: 500, letterSpacing: "-0.01em", lineHeight: 1.2 }}>
                {(p.prototypeCta && p.prototypeCta[lang]) || (lang === "pt" ? "Abrir protótipo" : "Open prototype")}
              </span>
            </div>
            <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 72, height: 72, borderRadius: "50%", border: "1px solid currentColor" }}>
              <Arrow size={22}/>
            </span>
          </a>
        </div>
      )}

      {/* Live site CTA */}
      {p.liveSiteUrl && (
        <div data-fade-in style={{ padding: "0 var(--gutter) 120px" }}>
          <a href={p.liveSiteUrl} target="_blank" rel="noopener noreferrer"
             style={{
               display: "flex",
               justifyContent: "space-between",
               alignItems: "center",
               gap: 32,
               padding: "40px 48px",
               border: "1px solid var(--hairline-strong)",
               borderRadius: 999,
               textDecoration: "none",
               color: "var(--ink)",
               transition: "background 0.4s var(--ease), color 0.4s var(--ease), transform 0.4s var(--ease)",
               flexWrap: "wrap",
             }}
             onMouseEnter={e => { e.currentTarget.style.background = "var(--ink)"; e.currentTarget.style.color = "var(--inv)"; }}
             onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink)"; }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <span className="mono" style={{ opacity: 0.6 }}>
                {lang === "pt" ? "Site no ar · " : "Live site · "}{p.liveSiteUrl.replace(/^https?:\/\//, "").replace(/\/$/, "")}
              </span>
              <span style={{ fontSize: "clamp(22px, 2.4vw, 34px)", fontWeight: 500, letterSpacing: "-0.01em", lineHeight: 1.2 }}>
                {lang === "pt" ? "Ver site ao vivo" : "Visit live site"}
              </span>
            </div>
            <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 72, height: 72, borderRadius: "50%", border: "1px solid currentColor" }}>
              <Arrow size={22}/>
            </span>
          </a>
        </div>
      )}

      {/* Next project preview */}
      <NextProjectPreview ref={previewRef} next={next} t={t} lang={lang} onClick={handleNext}/>

      {/* Lightbox modal */}
      {zoomSrc && <Lightbox src={zoomSrc} onClose={() => setZoomSrc(null)}/>}
    </section>
  );
}

const NextProjectPreview = React.forwardRef(({ next, t, lang, onClick }, ref) => {
  const [hover, setHover] = usePState(false);
  return (
    <div style={{ padding: "0 var(--gutter) 60px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24 }}>
        <span className="mono" style={{ color: "var(--muted)" }}>{t.project.next}</span>
        <span className="mono" style={{ color: "var(--muted)" }}>{t.project.clickToOpen}</span>
      </div>

      <div ref={ref}
        onClick={onClick}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          position: "relative",
          height: "min(56vh, 600px)",
          overflow: "hidden",
          cursor: "pointer",
          transform: hover ? "translateY(-8px)" : "translateY(0)",
          transition: "transform 0.6s var(--ease)",
        }}>
        <ProjectArt p={next} full stylized/>
        <div style={{
          position: "absolute",
          inset: 0,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          pointerEvents: "none",
        }}>
          <div style={{
            width: 96, height: 96,
            borderRadius: "50%",
            background: "rgba(255,255,255,0.95)",
            color: "#0a0a0a",
            display: "flex", alignItems: "center", justifyContent: "center",
            transform: hover ? "scale(1)" : "scale(0.85)",
            opacity: hover ? 1 : 0.85,
            transition: "transform 0.5s var(--ease), opacity 0.4s",
          }}>
            <Arrow size={28} dir="n"/>
          </div>
        </div>
      </div>
    </div>
  );
});

Object.assign(window, { ProjectArt, Project, NextProjectPreview });
