// Tools — two-row infinite logo marquee, opposite directions, GSAP-driven.
const { useRef: useRefTools, useEffect: useEffectTools, useState: useStateTools } = React;

// Logos live in /logos at the project root. Sub-pages (/about/, /work/) need to
// climb one level so the same component works everywhere.
const TOOLS_BASE = /\/(about|work)\//.test(location.pathname) ? "../" : "";

// name = label; file = logo PNG in /logos. Each tool's duplicates across the
// marquee share the same image.
const TOOLS_ROW_1 = [
  { name: "Figma", file: "logos/figma.png" },
  { name: "Adobe", file: "logos/adobe.png" },
  { name: "Claude", file: "logos/claude.png" },
  { name: "Midjourney", file: "logos/midjourney.png" },
  { name: "Perplexity", file: "logos/perplexity.png" },
  { name: "Lovable", file: "logos/lovable.png" },
  { name: "Antigravity", file: "logos/antigravity.png" },
];

const TOOLS_ROW_2 = [
  { name: "Cursor", file: "logos/cursor.png" },
  { name: "Blender", file: "logos/blender.png" },
  { name: "Rhino", file: "logos/rhino.png" },
  { name: "Autodesk", file: "logos/autodesk.png" },
  { name: "SolidWorks", file: "logos/solidworks.png" },
  { name: "Shapr3D", file: "logos/shapr3d.png" },
  { name: "KeyShot", file: "logos/keyshot.png" },
];

function ToolTile({ tool }) {
  return (
    <div className="tool-tile group/tile relative shrink-0 w-16 h-16 md:w-20 md:h-20 transition-transform duration-300 ease-out hover:-translate-y-1">
      {/* Accent gradient ring (revealed on hover) — same pattern as project cards */}
      <span
        className="pointer-events-none absolute rounded-2xl accent-gradient-anim opacity-0 group-hover/tile:opacity-100 transition-opacity duration-300"
        style={{ inset: "-1px" }}
      ></span>

      <div className="relative w-full h-full rounded-2xl overflow-hidden bg-surface border border-stroke group-hover/tile:border-transparent">
        <img
          src={TOOLS_BASE + tool.file}
          alt={`${tool.name} logo`}
          draggable="false"
          className="tool-logo absolute inset-0 w-full h-full object-contain"
        />
      </div>
    </div>
  );
}

function MarqueeRow({ items, direction }) {
  const trackRef = useRefTools(null);
  const tweenRef = useRefTools(null);
  // One "copy" of the row must be at least as wide as the viewport, otherwise
  // the -50% loop reveals a gap on wide screens. Repeat the list enough to fill.
  const [reps, setReps] = useStateTools(2);

  useEffectTools(() => {
    const compute = () => {
      const tileW = window.matchMedia("(min-width: 768px)").matches ? 104 : 88; // tile + gap
      const need = Math.max(1, Math.ceil((window.innerWidth + 240) / (items.length * tileW)));
      setReps(need);
    };
    compute();
    window.addEventListener("resize", compute);
    return () => window.removeEventListener("resize", compute);
  }, [items.length]);

  useEffectTools(() => {
    if (!window.gsap || !trackRef.current) return;
    // Track = two identical halves; translating by -50% loops seamlessly.
    const from = direction === "rtl" ? -50 : 0;
    const to = direction === "rtl" ? 0 : -50;
    const tween = window.gsap.fromTo(
      trackRef.current,
      { xPercent: from },
      { xPercent: to, duration: 50, ease: "none", repeat: -1 }
    );
    tweenRef.current = tween;
    return () => tween.kill();
  }, [direction, reps]);

  // One copy (list repeated `reps` times), then doubled for the seamless loop.
  const oneCopy = Array.from({ length: reps }, () => items).flat();
  const all = [...oneCopy, ...oneCopy];

  return (
    <div className="tools-marquee overflow-hidden">
      <div ref={trackRef} className="flex w-max gap-6 will-change-transform">
        {all.map((tool, i) => (
          <ToolTile key={tool.name + "-" + i} tool={tool} />
        ))}
      </div>
    </div>
  );
}

function Tools() {
  const ref = useRefTools(null);

  // Reveal-on-scroll for the header (matches Works / Journal).
  useEffectTools(() => {
    if (!window.gsap || !window.ScrollTrigger) return;
    const els = ref.current.querySelectorAll(".reveal-up");
    const anims = [];
    els.forEach((el) => {
      anims.push(
        window.gsap.to(el, {
          opacity: 1, y: 0, duration: 1, ease: "power2.out",
          scrollTrigger: { trigger: el, start: "top 90%", once: true },
        })
      );
    });
    return () => anims.forEach((a) => a.scrollTrigger && a.scrollTrigger.kill());
  }, []);

  return (
    <section id="Tools" ref={ref} className="bg-bg py-16 md:py-24 overflow-hidden">
      <div className="max-w-content mx-auto px-6 md:px-10 lg:px-16">
        <SectionHeader
          eyebrow="Toolkit"
          pre="Works seamlessly with the tools "
          italic="I already use"
          post="."
          subtext="The set I reach for across product design, prototyping, research, and 3D, kept tight on purpose." />
      </div>

      {/* Full-bleed marquee */}
      <div className="mt-12 md:mt-16 flex flex-col gap-10 md:gap-12 w-screen relative left-1/2 right-1/2 -ml-[50vw] -mr-[50vw]">
        <MarqueeRow items={TOOLS_ROW_1} direction="ltr" />
        <MarqueeRow items={TOOLS_ROW_2} direction="rtl" />
      </div>
    </section>
  );
}

Object.assign(window, { Tools });
