// WorkCard + Lightbox components

const { useState: useStateW, useEffect: useEffectW } = React;

function WorkCard({ id, idx, total, tag, accent, onOpen }) {
  const [meta, setMeta] = useStateW(null);
  const [thumbErr, setThumbErr] = useStateW(false);
  const ref = window.useReveal();
  const cardRef = React.useRef(null);

  useEffectW(() => {
    let live = true;
    window.fetchYTMeta(id).then((m) => { if (live) setMeta(m); });
    return () => { live = false; };
  }, [id]);

  // magnetic-ish 3D tilt
  React.useEffect(() => {
    const el = cardRef.current;
    if (!el || matchMedia('(hover: none)').matches) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const px = (e.clientX - r.left) / r.width - 0.5;
      const py = (e.clientY - r.top) / r.height - 0.5;
      el.style.transform = `perspective(1000px) translateY(-3px) rotateX(${-py * 4}deg) rotateY(${px * 4}deg)`;
    };
    const onLeave = () => { el.style.transform = ''; };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
    };
  }, []);

  const setRefs = (node) => {
    cardRef.current = node;
    if (typeof ref === 'function') ref(node); else if (ref) ref.current = node;
  };

  return (
    <article
      ref={setRefs}
      className="work-card reveal"
      style={{ transitionDelay: `${(idx % 6) * 60}ms` }}
      onClick={() => onOpen(id, meta)}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(id, meta); } }}
    >
      <div className="work-thumb">
        {meta && !thumbErr ? (
          <img
            className="work-thumb-img"
            src={meta.thumb}
            alt={meta.title}
            loading="lazy"
            onError={(e) => {
              if (e.target.src !== meta.thumbFallback) e.target.src = meta.thumbFallback;
              else setThumbErr(true);
            }}
          />
        ) : (
          <div className="work-thumb-loading">
            {thumbErr ? '// thumbnail unavailable' : '// fetching frame…'}
          </div>
        )}
        <div className="work-thumb-overlay"></div>
        {tag && (
          <div className={`work-thumb-tag ${accent ? 'accent' : ''}`}>{tag}</div>
        )}
        <div className="play-btn" aria-label="Play"></div>
      </div>
      <div className="work-meta">
        <div className="work-id">
          <span>// {String(idx + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}</span>
          <span className="accent">YT ↗</span>
        </div>
        <h3 className="work-title">{meta ? meta.title : 'Loading title…'}</h3>
        <div className="work-channel">{meta && meta.author ? meta.author : 'YouTube'}</div>
      </div>
    </article>
  );
}

function FeatureCard({ id, title, desc, points, tag, onOpen }) {
  const [meta, setMeta] = useStateW(null);
  const [thumbErr, setThumbErr] = useStateW(false);
  const ref = window.useReveal();

  useEffectW(() => {
    let live = true;
    window.fetchYTMeta(id).then((m) => { if (live) setMeta(m); });
    return () => { live = false; };
  }, [id]);

  return (
    <article
      ref={ref}
      className="work-card reveal"
      onClick={() => onOpen(id, meta)}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(id, meta); } }}
    >
      <div className="work-thumb">
        {meta && !thumbErr ? (
          <img
            className="work-thumb-img"
            src={meta.thumb}
            alt={title}
            loading="lazy"
            onError={(e) => {
              if (e.target.src !== meta.thumbFallback) e.target.src = meta.thumbFallback;
              else setThumbErr(true);
            }}
          />
        ) : (
          <div className="work-thumb-loading">// fetching frame…</div>
        )}
        <div className="work-thumb-overlay"></div>
        {tag && <div className="work-thumb-tag accent">{tag}</div>}
        <div className="play-btn" aria-label="Play"></div>
      </div>
      <div className="work-meta">
        <div className="work-id">
          <span>// FEATURED CASE</span>
          <span className="accent">YT ↗</span>
        </div>
        <h3 className="work-title">{title}</h3>
        <p className="work-desc">{desc}</p>
        <ul className="feature-points">
          {points.map(([k, v], i) => (
            <li key={i}>
              <span>{k}</span>
              <span>{v}</span>
            </li>
          ))}
        </ul>
        <div className="work-channel">Live · Virtual Production</div>
      </div>
    </article>
  );
}

function Lightbox({ activeId, activeMeta, onClose }) {
  if (!activeId) {
    return <div className="lightbox" aria-hidden="true"></div>;
  }
  return (
    <>
      <div className="lightbox open" onClick={onClose}>
        <div className="lightbox-frame" onClick={(e) => e.stopPropagation()}>
          <iframe
            src={`https://www.youtube.com/embed/${activeId}?autoplay=1&rel=0&modestbranding=1`}
            title={activeMeta ? activeMeta.title : 'Video'}
            allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
            allowFullScreen
          ></iframe>
        </div>
        <div className="lightbox-meta">
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-mute)', marginBottom: 4 }}>
              // now playing
            </div>
            <div style={{ color: 'var(--fg)', fontSize: 14 }}>
              {activeMeta ? activeMeta.title : 'Loading…'}
            </div>
          </div>
          <a
            href={`https://www.youtube.com/watch?v=${activeId}`}
            target="_blank" rel="noopener"
            className="accent"
            style={{ fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase' }}
          >Open on YouTube ↗</a>
        </div>
      </div>
      <button className="lightbox-close" onClick={onClose} aria-label="Close">✕</button>
    </>
  );
}

function CampaignCard({ campaign, onOpenCampaign }) {
  const [thumbErr, setThumbErr] = useStateW(false);
  const ref = window.useReveal();
  const cardRef = React.useRef(null);
  const thumb = `https://i.ytimg.com/vi/${campaign.featured}/maxresdefault.jpg`;
  const thumbFallback = `https://i.ytimg.com/vi/${campaign.featured}/hqdefault.jpg`;

  React.useEffect(() => {
    const el = cardRef.current;
    if (!el || matchMedia('(hover: none)').matches) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const px = (e.clientX - r.left) / r.width - 0.5;
      const py = (e.clientY - r.top) / r.height - 0.5;
      el.style.transform = `perspective(1000px) translateY(-3px) rotateX(${-py * 4}deg) rotateY(${px * 4}deg)`;
    };
    const onLeave = () => { el.style.transform = ''; };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
    };
  }, []);

  const setRefs = (node) => {
    cardRef.current = node;
    if (typeof ref === 'function') ref(node); else if (ref) ref.current = node;
  };

  return (
    <article
      ref={setRefs}
      className={`work-card campaign-card reveal ${campaign.vertical ? 'vertical' : ''}`}
      onClick={() => onOpenCampaign(campaign)}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpenCampaign(campaign); } }}
    >
      <div className="work-thumb">
        {!thumbErr ? (
          <img
            className="work-thumb-img"
            src={thumb}
            alt={`${campaign.brand} — ${campaign.title}`}
            loading="lazy"
            onError={(e) => {
              if (e.target.src !== thumbFallback) e.target.src = thumbFallback;
              else setThumbErr(true);
            }}
          />
        ) : (
          <div className="work-thumb-loading">// thumbnail unavailable</div>
        )}
        <div className="work-thumb-overlay"></div>
        <div className="work-thumb-tag accent">{campaign.brand}</div>
        <div className="campaign-count-badge">{campaign.videos.length} FILMS</div>
        <div className="play-btn" aria-label="View campaign"></div>
      </div>
      <div className="work-meta">
        <div className="work-id">
          <span className="accent">{campaign.brand}</span>
          <span className="accent">VIEW ALL ↗</span>
        </div>
        <h3 className="work-title">{campaign.title}</h3>
        <div className="work-channel">{campaign.videos.length} films · Director</div>
      </div>
    </article>
  );
}

function CampaignPanel({ campaign, onClose, onPlayVideo }) {
  useEffectW(() => {
    if (!campaign) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [campaign]);

  return (
    <>
      <div className={`campaign-panel ${campaign ? 'open' : ''}`} onClick={onClose}>
        <div className="campaign-panel-inner" onClick={(e) => e.stopPropagation()}>
          {campaign && (
            <>
              <div className="campaign-panel-header">
                <div className="campaign-panel-brand">{campaign.brand}</div>
                <h2 className="campaign-panel-title">{campaign.title}</h2>
                <div className="campaign-panel-meta">{campaign.videos.length} films · Director</div>
              </div>
              <div className={`campaign-panel-grid ${campaign.vertical ? 'vertical' : ''}`}>
                {campaign.videos.map((v, i) => (
                  <window.WorkCard
                    key={v.id}
                    id={v.id}
                    idx={i}
                    total={campaign.videos.length}
                    tag="Director"
                    onOpen={onPlayVideo}
                  />
                ))}
              </div>
            </>
          )}
        </div>
      </div>
      {campaign && (
        <button className="lightbox-close" onClick={onClose} aria-label="Close campaign">✕</button>
      )}
    </>
  );
}

Object.assign(window, { WorkCard, FeatureCard, Lightbox, CampaignCard, CampaignPanel });
