// work.jsx — Featured work section: big editorial cards + scroll-linked list.
//
// To add a real video to any project: open components/data.jsx and paste
// the URL into the project's `video` field. Supported:
//   • YouTube  →  https://youtu.be/XXXX  or  https://youtube.com/watch?v=XXXX
//   • Vimeo    →  https://vimeo.com/XXXXXXXX
//   • Direct file → "assets/yourfile.mp4" (drop file into assets/ folder first)
// Optional: set `cover` to "assets/yourimage.jpg" for the still that shows
// before the video plays.

function parseVideoSrc(url) {
  if (!url) return null;
  // Direct file
  if (/\.(mp4|webm|mov)(\?|$)/i.test(url) || url.startsWith("assets/")) {
    return { kind: "file", src: url, thumb: null };
  }
  // YouTube
  let m = url.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([\w-]{11})/);
  if (m) {
    const id = m[1];
    return {
      kind: "youtube",
      src: `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&mute=1&controls=1&rel=0&modestbranding=1&playsinline=1`,
      thumb: `https://img.youtube.com/vi/${id}/maxresdefault.jpg`,
    };
  }
  // Vimeo
  m = url.match(/vimeo\.com\/(?:video\/)?(\d+)/);
  if (m) {
    return {
      kind: "vimeo",
      src: `https://player.vimeo.com/video/${m[1]}?autoplay=1&muted=1&loop=1&background=0&dnt=1`,
      thumb: null,
    };
  }
  return null;
}

function WorkSection({ onOpen }) {
  const [hovered, setHovered] = React.useState(null);

  return (
    <section className="work" id="work">
      <div className="sec-head">
        <span className="sec-label">
          <span className="sec-label-num">§ 01</span>
          <span>Selected work</span>
        </span>
        <h2 className="sec-h">
          Six projects<br />worth sharing.
        </h2>
        <p className="sec-sub">
          A slice of what we've made for founders, operators, and institutions since 2016. Film, identity, campaign, and everything between.
        </p>
      </div>

      <div className="work-grid">
        {WORK.slice(0, 2).map((w, i) => (
          <WorkCard key={w.id} w={w} size="lg" index={i} onOpen={onOpen} />
        ))}
      </div>

      <div className="work-list">
        {WORK.slice(2).map((w, i) => (
          <WorkRow
            key={w.id}
            w={w}
            index={i + 2}
            active={hovered === w.id}
            onHover={() => setHovered(w.id)}
            onLeave={() => setHovered(null)}
            onOpen={onOpen}
          />
        ))}
      </div>

      <div className="work-all">
        <a href="work.html" className="pill-link">
          <span>All work, archived</span>
          <span className="pill-arrow" aria-hidden="true">→</span>
        </a>
      </div>
    </section>
  );
}

function WorkCard({ w, size, index, onOpen }) {
  const [playing, setPlaying] = React.useState(false);
  const video = parseVideoSrc(w.video);
  const ratio = size === "lg" ? "16/9" : "4/3";

  const handleClick = (e) => {
    // While playing, never re-trigger case-study or replay from a card click —
    // let clicks fall through to the iframe (YouTube controls).
    if (playing) return;
    if (video) {
      e.stopPropagation();
      setPlaying(true);
      return;
    }
    onOpen && onOpen(w);
  };

  const stop = (e) => e.stopPropagation();

  return (
    <article
      className={`wc wc-${size}`}
      data-playing={playing ? "1" : "0"}
      style={{ "--tint": w.tint, "--bg": w.bg }}
      onClick={handleClick}
    >
      <div className="wc-media">
        {video && playing ? (
          video.kind === "file" ? (
            <video
              className="wc-vid"
              style={{ aspectRatio: ratio }}
              src={video.src}
              poster={w.cover}
              autoPlay
              muted
              loop
              playsInline
              controls
            />
          ) : (
            <iframe
              className="wc-vid"
              style={{ aspectRatio: ratio }}
              src={video.src}
              title={w.title}
              frameBorder="0"
              allow="autoplay; fullscreen; picture-in-picture"
              allowFullScreen
            />
          )
        ) : (w.cover || (video && video.thumb)) ? (
          <img className="wc-cover" style={{ aspectRatio: ratio }} src={w.cover || video.thumb} alt={w.title} />
        ) : (
          <Placeholder
            label={`${w.client.toLowerCase()} · ${w.kind.toLowerCase()}`}
            tint={w.tint}
            bg={w.bg}
            ratio={ratio}
          />
        )}
        {!playing && <span className="wc-tag">{w.tag}</span>}
        {!playing && size !== "lg" && (
          <span className="wc-play">
            <span className="wc-play-ring" />
            <span className="wc-play-tri">▶</span>
          </span>
        )}
        {!playing && size === "lg" && (
          <div className="wc-overlay">
            <span className="wc-overlay-play">
              <span className="wc-overlay-ring" />
              <span className="wc-overlay-tri">▶</span>
            </span>
            <h3 className="wc-overlay-title">{w.title}</h3>
          </div>
        )}
        {playing && (
          <div className="wc-vid-actions" onClick={stop}>
            {w.feature ? (
              <a className="wc-vid-btn" href={w.feature}>Learn more →</a>
            ) : (
              <button className="wc-vid-btn" onClick={(e) => { stop(e); onOpen && onOpen(w); }}>Case study →</button>
            )}
            <button className="wc-vid-btn wc-vid-close" aria-label="Stop video" onClick={(e) => { stop(e); setPlaying(false); }}>✕</button>
          </div>
        )}
      </div>
      <div className="wc-meta">
        <span className="wc-num">{String(index + 1).padStart(2, "0")}</span>
        <div className="wc-text">
          <h3 className="wc-title">{w.title}</h3>
          <div className="wc-sub">
            <span>{w.client}</span>
            <span className="wc-dot" />
            <span>{w.kind}</span>
            <span className="wc-dot" />
            <span>{w.year}</span>
          </div>
        </div>
      </div>
    </article>
  );
}

function WorkRow({ w, index, active, onHover, onLeave, onOpen }) {
  const go = () => {
    // Opening a suit from this list auto-plays that suit's featured film.
    if (w.suit) { window.location.href = `suit-${w.suit}.html?play=1`; return; }
    onOpen && onOpen(w);
  };
  return (
    <div
      className="wr"
      data-active={active ? "1" : "0"}
      style={{ "--tint": w.tint, "--bg": w.bg }}
      onMouseEnter={onHover}
      onMouseLeave={onLeave}
      onClick={go}
    >
      <span className="wr-num">{String(index + 1).padStart(2, "0")}</span>
      <span className="wr-client">{w.client}</span>
      <span className="wr-title">{w.title}</span>
      <span className="wr-kind">{w.kind}</span>
      <span className="wr-year">{w.year}</span>
      <span className="wr-open" aria-hidden="true">↗</span>
    </div>
  );
}

window.WorkSection = WorkSection;
