// SectionHeader (shared) + SelectedWorks 2-column grid of rich project cards.
const { useRef: useRefWorks, useEffect: useEffectWorks } = React;

// Shared reveal-on-scroll header used by Works, Journal, Explorations.
function SectionHeader({ eyebrow, pre, italic, post, subtext, viewAll, onViewAll }) {
  return (
    <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-12 md:mb-16">
      <div className="reveal-up max-w-xl">
        <div className="flex items-center gap-3 mb-5">
          <span className="w-8 h-px bg-stroke"></span>
          <span className="text-xs text-muted uppercase tracking-[0.3em] whitespace-nowrap">{eyebrow}</span>
        </div>
        <h2 className="text-4xl md:text-5xl lg:text-6xl tracking-tight text-text-primary leading-[1.05]" style={{ fontSize: "clamp(30px, 7.5vw, 48px)" }}>
          {pre}
          <span className="font-display italic" style={{ color: "rgb(80, 134, 191)" }}>{italic}</span>
          {post}
        </h2>
        {subtext && <p className="mt-5 text-sm md:text-base text-muted max-w-md text-balance">{subtext}</p>}
      </div>
      {viewAll &&
      <button
        onClick={onViewAll}
        className="reveal-up group relative hidden md:inline-flex items-center gap-2 self-start md:self-end rounded-full text-sm px-5 py-3">
        
          <span className="absolute rounded-full accent-gradient-anim opacity-0 group-hover:opacity-100 transition-opacity duration-300" style={{ inset: "-2px" }}></span>
          <span className="relative flex items-center gap-2 rounded-full bg-surface border border-stroke group-hover:border-transparent px-5 py-3 text-text-primary transition-colors duration-300 -mx-5 -my-3">
            {viewAll}
            <span className="transition-transform duration-300 group-hover:translate-x-1">→</span>
          </span>
        </button>
      }
    </div>);

}

// Each card: subtle accent tint, logo slot, tag pills, screenshot slot, then
// title / subtitle / status underneath. tint is an accent hue used very subtly.
const WORK_PROJECTS = [
{
  id: "work-1",
  logo: "work-1-logo",
  shot: "work-1",
  tint: "#4E85BF",
  tags: ["Product & Service Design", "Led End-to-End", "Renewable Energy"],
  status: "Shipped 2025",
  statusUnder: "Capstone 2025",
  title: "SolarSync",
  subtitle: "A Design System for Smarter Solar Maintenance",
  href: "work/solarsync.html"
},
{
  id: "work-2",
  logo: "work-2-logo",
  shot: "work-2",
  tint: "#4E9E84",
  tags: ["Product Design", "Led End-to-End", "Events & Discovery"],
  status: "Shipped 2023",
  title: "AllEvents: An Event Discovery Platform",
  subtitle: "From Zero to 20+ Million Users",
  href: "work/allevents.html"
},
{
  id: "work-3",
  logo: "work-3-logo",
  shot: "work-3",
  tint: "#8B7CC0",
  tags: ["AI Product Design", "Founding Designer", "Productivity & AI"],
  status: "In Progress",
  statusUnder: "In Process",
  statusEmoji: "🟡",
  title: "Corisius AI",
  subtitle: "The Invisible Assistant Behind Every Meeting"
},
{
  id: "work-4",
  logo: "work-4-logo",
  shot: "work-4",
  tint: "#C09766",
  tags: ["UX Research + Dev", "Team of 5 · 7 weeks", "Assistive Tech & Care"],
  status: "Concept",
  title: "Daily Living Lab",
  subtitle: "All in One Place for Michael's Daily Care",
  href: "work/daily-living-lab.html"
}];


function StatusChip({ label, emoji }) {
  return (
    <span className="inline-flex items-center gap-2 text-base text-muted">
      <span className="emoji text-[15px] leading-none">{emoji || "✅"}</span>
      {label}
    </span>);

}

function WorkCard({ project }) {
  const Wrapper = project.href ? "a" : "div";
  const wrapperProps = project.href ? { href: project.href } : {};
  const cardRef = useRefWorks(null);

  // For linked cards: clicking anywhere on the card navigates to the case
  // study. We capture the click before the image-slot's click-to-upload
  // handler fires. Drag-and-drop to fill images still works (drag events).
  useEffectWorks(() => {
    if (!project.href || !cardRef.current) return;
    const el = cardRef.current;
    const onClick = (e) => {
      e.stopPropagation();
      e.preventDefault();
      window.location.href = project.href;
    };
    el.addEventListener("click", onClick, true);
    return () => el.removeEventListener("click", onClick, true);
  }, []);

  return (
    <Wrapper ref={cardRef} {...wrapperProps} className="work-card group relative flex flex-col h-full reveal-up">
      {/* Tinted panel */}
      <div
        className="card-media relative flex-1 rounded-3xl overflow-hidden border border-stroke bg-surface px-7 pt-9 flex flex-col items-center grayscale-0 group-hover:grayscale transition-[filter] duration-500"
        style={{
          background: `linear-gradient(180deg, ${project.tint}1f 0%, ${project.tint}0a 38%, hsl(var(--surface)) 100%)`
        }}>

        {/* Brand logo */}
        <div className={"relative w-full max-w-[260px] mb-6 flex items-center justify-center " + (project.logoH || "h-[104px]")}>
          <image-slot
            id={project.logo}
            shape="rect"
            fit="contain"
            placeholder={`logo — ${project.title}`}
            class="absolute inset-0">
          </image-slot>
        </div>

        {/* Tag pills */}
        <div className="flex flex-wrap justify-center gap-2.5 mb-8">
          {project.tags.map((t, i) =>
          <span key={i} className="px-3.5 py-1.5 rounded-full text-xs bg-bg/55 border border-white/10 text-text-primary/90 whitespace-nowrap">
              {t}
            </span>
          )}
          <span className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs bg-bg/55 border border-white/10 text-text-primary/90 whitespace-nowrap">
            <span className="emoji text-[12px] leading-none">{project.statusEmoji || "✅"}</span>
            {project.status}
          </span>
        </div>

        {/* Product screenshot (fills lower part, bleeds to bottom edge) */}
        <div className="relative w-full flex-1 min-h-[220px] rounded-t-2xl overflow-hidden border-t border-x border-white/10 bg-bg/40">
          <image-slot
            id={project.shot}
            shape="rect"
            fit="cover"
            placeholder={`screenshot — ${project.title}`}
            class="absolute inset-0 transition-transform duration-700 group-hover:scale-[1.03]">
          </image-slot>
          <div className="halftone pointer-events-none absolute inset-0 opacity-10 mix-blend-multiply"></div>
        </div>
      </div>

      {/* Title / subtitle / status under the card */}
      <div className="mt-6">
        <h3 className="text-2xl md:text-3xl font-display leading-snug" style={{ color: "#4E85BF", fontSize: "24px" }}>{project.title}</h3>
        <p className="mt-2 text-lg text-text-primary/85" style={{ fontSize: "16px" }}>{project.subtitle}</p>
        <div className="mt-3">
          <StatusChip label={project.statusUnder || project.status} emoji={project.statusEmoji} />
        </div>
      </div>
    </Wrapper>);

}

function SelectedWorks({ onViewAll }) {
  const sectionRef = useRefWorks(null);
  const gridRef = useRefWorks(null);
  const cursorRef = useRefWorks(null);

  // Custom "View Case Study" cursor that follows the mouse over the cards.
  useEffectWorks(() => {
    if (!window.gsap) return;
    const cursor = cursorRef.current;
    const scope = gridRef.current;
    if (!cursor || !scope) return;
    if (!window.matchMedia("(pointer: fine)").matches) return;

    window.gsap.set(cursor, { xPercent: -50, yPercent: -50, scale: 0.6 });
    const xTo = window.gsap.quickTo(cursor, "left", { duration: 0.35, ease: "power3" });
    const yTo = window.gsap.quickTo(cursor, "top", { duration: 0.35, ease: "power3" });
    let visible = false;

    const show = () => {
      if (visible) return;
      visible = true;
      window.gsap.to(cursor, { opacity: 1, scale: 1, duration: 0.25, ease: "power2.out" });
    };
    const hide = () => {
      if (!visible) return;
      visible = false;
      window.gsap.to(cursor, { opacity: 0, scale: 0.6, duration: 0.2, ease: "power2.out" });
    };
    const onMove = (e) => {
      xTo(e.clientX);
      yTo(e.clientY);
      if (e.target.closest("a.work-card")) show();else
      hide();
    };

    scope.addEventListener("mousemove", onMove);
    scope.addEventListener("mouseleave", hide);
    return () => {
      scope.removeEventListener("mousemove", onMove);
      scope.removeEventListener("mouseleave", hide);
    };
  }, []);

  // Reveal-on-scroll for header + cards.
  useEffectWorks(() => {
    if (!window.gsap || !window.ScrollTrigger) return;
    const els = sectionRef.current.querySelectorAll(".reveal-up");
    const anims = [];
    els.forEach((el) => {
      const idx = Array.prototype.indexOf.call(el.parentElement.children, el);
      anims.push(
        window.gsap.to(el, {
          opacity: 1, y: 0, duration: 1, ease: "power2.out",
          delay: Math.min(idx, 2) * 0.1,
          scrollTrigger: { trigger: el, start: "top 88%", once: true }
        })
      );
    });
    return () => anims.forEach((a) => a.scrollTrigger && a.scrollTrigger.kill());
  }, []);

  return (
    <section id="Work" ref={sectionRef} className="bg-bg py-20 md:py-28">
      {/* Custom cursor follower */}
      <div
        ref={cursorRef}
        className="work-cursor pointer-events-none fixed z-[60] accent-gradient text-bg text-sm font-medium px-5 py-3 rounded-full whitespace-nowrap shadow-lg shadow-black/30"
        style={{ left: 0, top: 0, opacity: 0 }}>
        View Case Study
      </div>

      <div className="max-w-content mx-auto w-full px-6 md:px-10 lg:px-16">
        <SectionHeader
          eyebrow="Selected Work"
          pre="Featured "
          italic="projects"
          subtext="A selection of projects I've worked on, from concept to launch." />

        <div ref={gridRef} className="grid grid-cols-1 md:grid-cols-2 gap-8 md:gap-10 items-stretch">
          {WORK_PROJECTS.map((p) =>
          <WorkCard key={p.id} project={p} />
          )}
        </div>
      </div>
    </section>);

}

Object.assign(window, { SectionHeader, SelectedWorks });