// Founders.jsx — founders, team story, credential logos.
const FOUNDER_BACKGROUND_LOGOS = [
  { src: "assets/external-logos/university-logos/columbia-logo.png", alt: "Columbia University", mark: "columbia" },
  { src: "assets/external-logos/university-logos/yale-logo.png", alt: "Yale University", mark: "yale" },
  { src: "assets/external-logos/previous-employers/Intel-logo-2022.png", alt: "Intel", mark: "intel" },
  { src: "assets/external-logos/previous-employers/microsoft-logo.webp", alt: "Microsoft", mark: "microsoft" },
];

const FOUNDER_INVESTOR_LOGOS = [
  { src: "assets/external-logos/past-investors/lerer-hippeau.webp", alt: "Lerer Hippeau", mark: "lerer" },
  { src: "assets/external-logos/past-investors/related-logos.png", alt: "Related", mark: "related" },
  { src: "assets/external-logos/past-investors/warby-parker.png", alt: "Warby Parker", mark: "warby" },
];

function FounderCard({ src, name, role, bio }) {
  return (
    <article className="zg-founder-card">
      <div className="zg-founder-media">
        <img src={src} alt={name} loading="lazy" />
      </div>
      <div className="zg-founder-copy">
        <span className="zg-founder-meta">{role}</span>
        <h3 className="zg-founder-name">{name}</h3>
        <p className="zg-founder-bio">{bio}</p>
      </div>
    </article>
  );
}

function FounderCredRow({ label, labelId, logos }) {
  return (
    <div className="zg-founders-cred-row">
      <div className="zg-founders-cred-label">
        <span className="zg-cred-label" id={labelId}>
          {label}
        </span>
      </div>
      <ul className="zg-founders-cred-logos" aria-labelledby={labelId}>
        {logos.map((logo) => (
          <li
            key={logo.alt}
            className="zg-client-logo-item"
            style={logo.slot ? { gridColumn: logo.slot } : undefined}
          >
            <img
              className={`zg-client-logo zg-founders-mark zg-founders-mark--${logo.mark}`}
              src={logo.src}
              alt={logo.alt}
              loading="lazy"
              decoding="async"
            />
          </li>
        ))}
      </ul>
    </div>
  );
}

function FoundersCredStack() {
  return (
    <div className="zg-founders-cred-stack">
      <FounderCredRow
        label="Where we studied and worked"
        labelId="zg-founders-background-label"
        logos={FOUNDER_BACKGROUND_LOGOS}
      />
      <FounderCredRow
        label="Previously backed by investors who have built companies"
        labelId="zg-founders-investors-label"
        logos={FOUNDER_INVESTOR_LOGOS}
      />
    </div>
  );
}

function animateFounderCard(tl, card, position, photoScale = 1.08) {
  const media = card.querySelector(".zg-founder-media");
  const photo = card.querySelector(".zg-founder-media img");
  const meta = card.querySelector(".zg-founder-meta");
  const name = card.querySelector(".zg-founder-name");
  const bio = card.querySelector(".zg-founder-bio");

  tl.fromTo(
    card,
    { opacity: 0, y: 64, scale: 0.97, transformOrigin: "50% 100%" },
    { opacity: 1, y: 0, scale: 1, duration: 0.92, transformOrigin: "50% 100%" },
    position
  );

  if (media) {
    tl.fromTo(
      media,
      { opacity: 0, scale: 1.04 },
      { opacity: 1, scale: 1, duration: 0.95, ease: "power2.out" },
      "<0.08"
    );
  }

  if (photo) {
    tl.fromTo(
      photo,
      { scale: photoScale, opacity: 0.7 },
      { scale: 1, opacity: 1, duration: 1.15, ease: "power2.out" },
      "<"
    );
  }

  if (meta) {
    tl.fromTo(meta, { opacity: 0, y: 12 }, { opacity: 1, y: 0, duration: 0.5 }, "<0.22");
  }

  if (name) {
    tl.fromTo(name, { opacity: 0, y: 18 }, { opacity: 1, y: 0, duration: 0.58 }, "<0.08");
  }

  if (bio) {
    tl.fromTo(bio, { opacity: 0, y: 14 }, { opacity: 1, y: 0, duration: 0.52 }, "<0.06");
  }
}

function Founders() {
  const sectionRef = React.useRef(null);
  const playedRef = React.useRef(false);

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return undefined;

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const gsap = window.gsap;

    const clearMotion = (cards) => {
      if (!gsap) return;
      cards.forEach((card) => {
        gsap.set(card, { clearProps: "transform,opacity" });
        card
          .querySelectorAll(
            ".zg-founder-media, .zg-founder-media img, .zg-founder-meta, .zg-founder-name, .zg-founder-bio"
          )
          .forEach((el) => {
            gsap.set(el, { clearProps: "all" });
          });
      });
    };

    const play = () => {
      if (playedRef.current) return;
      playedRef.current = true;

      const opener = section.querySelector(".zg-founders-opener");
      const label = section.querySelector(".zg-founders-opener .label");
      const title = section.querySelector(".zg-founders-opener h2");
      const lede = section.querySelector(".zg-founders-lede");
      const credStack = section.querySelector(".zg-founders-cred-stack");
      const cards = section.querySelectorAll(".zg-founder-card");

      if (reduced || !gsap) {
        section.classList.add("zg-founders-section--revealed");
        return;
      }

      const tl = gsap.timeline({ defaults: { ease: "power3.out" } });

      tl.from(opener, { opacity: 0, y: 28, duration: 0.7 })
        .from(label, { opacity: 0, y: 14, duration: 0.55 }, "-=0.55")
        .from(title, { opacity: 0, y: 24, duration: 0.78 }, "-=0.45")
        .from(lede, { opacity: 0, x: 28, duration: 0.72 }, "-=0.45");

      if (credStack) {
        tl.fromTo(
          credStack,
          { y: 16, opacity: 1 },
          { y: 0, opacity: 1, duration: 0.68 },
          "-=0.2"
        );
      }

      cards.forEach((card, index) => {
        animateFounderCard(tl, card, index === 0 ? "-=0.08" : "-=0.46", 1.1);
      });

      tl.add(() => {
        section.classList.add("zg-founders-section--revealed");
        clearMotion(cards);
      });
    };

    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          play();
          io.disconnect();
        }
      },
      { threshold: 0.18 }
    );

    io.observe(section);

    let cleanupTilts = () => {};
    if (!reduced && window.matchMedia("(hover: hover)").matches) {
      const cards = section.querySelectorAll(".zg-founder-card");
      const cleanups = [];

      cards.forEach((card) => {
        let raf = 0;
        let targetX = 0;
        let targetY = 0;
        let currentX = 0;
        let currentY = 0;
        let active = false;

        const paint = () => {
          raf = 0;
          currentX += (targetX - currentX) * 0.14;
          currentY += (targetY - currentY) * 0.14;
          card.style.setProperty("--tilt-x", `${currentX.toFixed(2)}deg`);
          card.style.setProperty("--tilt-y", `${currentY.toFixed(2)}deg`);
          if (
            active ||
            Math.abs(currentX - targetX) > 0.05 ||
            Math.abs(currentY - targetY) > 0.05
          ) {
            raf = requestAnimationFrame(paint);
          }
        };

        const queue = () => {
          if (!raf) raf = requestAnimationFrame(paint);
        };

        const onMove = (event) => {
          const rect = card.getBoundingClientRect();
          const nx = (event.clientX - rect.left) / rect.width;
          const ny = (event.clientY - rect.top) / rect.height;
          const tiltMax = 4;
          targetY = (nx - 0.5) * tiltMax * 2;
          targetX = (0.5 - ny) * tiltMax * 2;
          active = true;
          queue();
        };

        const onLeave = () => {
          targetX = 0;
          targetY = 0;
          active = false;
          queue();
        };

        card.addEventListener("pointermove", onMove);
        card.addEventListener("pointerleave", onLeave);

        cleanups.push(() => {
          card.removeEventListener("pointermove", onMove);
          card.removeEventListener("pointerleave", onLeave);
          if (raf) cancelAnimationFrame(raf);
        });
      });

      cleanupTilts = () => cleanups.forEach((fn) => fn());
    }

    return () => {
      io.disconnect();
      cleanupTilts();
    };
  }, []);

  return (
    <section
      id="about"
      ref={sectionRef}
      className="zg-founders-section"
      aria-labelledby="zg-founders-title"
    >
      <div className="zg-container">
        <header className="zg-founders-header">
          <div className="zg-founders-opener">
            <span className="label">The team</span>
            <h2 id="zg-founders-title">
              Experienced <span className="zg-highlight">founders</span>.
              <span className="muted">
                An AI-native team of engineers and technical product managers.
              </span>
            </h2>
          </div>
          <p className="zg-founders-lede">
            Pete and Kyle lead Zaigo and stay close to every project. Behind them
            is a team that builds with AI every day: senior engineers and technical
            PMs with at least 15 years of experience.
          </p>
        </header>

        <FoundersCredStack />

        <div className="zg-founders-grid">
          <FounderCard
            src="assets/team-shots/Kyle.png"
            name="Kyle Richless"
            role="Co-Founder & Managing Partner"
            bio="Previously Global Head of Business Development and Growth at Axiom, then Venture Capitalist before starting Zaigo."
          />
          <FounderCard
            src="assets/team-shots/pete-photo.png"
            name="Pete Enestrom"
            role="Co-Founder & CTO"
            bio="Repeat exited founder who most recently sold Learnexus to Cognota. Ex-Microsoft, with degrees from Yale and Columbia."
          />
        </div>
      </div>
    </section>
  );
}

window.Founders = Founders;
