// Showreel works grid
// Fonte dos dados: Supabase (portfolio_cases, publicado=true) com fallback estático.

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

const PROJECTS = [
  { name: 'NOITE INFINITA', client: 'CLUB ZERO', kind: 'CAMPAIGN', tall: true, hue: 18 },
  { name: 'PRIMEIRA LUZ', client: 'CASA AMARELA', kind: 'BRANDING', tall: false, hue: 32 },
  { name: 'AVENIDA', client: 'AURA STUDIO', kind: 'FILM', tall: false, hue: 12 },
  { name: 'TROPICAL FUTURO', client: 'ÉTER REC.', kind: 'MUSIC VIDEO', tall: true, hue: 280 },
  { name: 'CONTRA-LUZ', client: 'PRADO MODA', kind: 'EDITORIAL', tall: false, hue: 24 },
  { name: 'MADRUGADA', client: 'BLUMA EVENTS', kind: 'COVERAGE', tall: false, hue: 200 },
];

// Espera o window._sb nascer (retry defensivo p/ CDN lento/ausente). Resolve null se não vier.
function waitForSbW(tries = 20) {
  return new Promise((resolve) => {
    let n = 0;
    (function check() {
      if (window._sb) return resolve(window._sb);
      if (n++ >= tries) return resolve(null);
      setTimeout(check, 100);
    })();
  });
}

// formato do banco → orientação no grid (span de linha + aspect ratio).
function formatToLayout(formato) {
  switch (formato) {
    case '9:16': return { span: 2, ratio: '9 / 16' };
    case '16:9': return { span: 1, ratio: '16 / 9' };
    case '1:1':  return { span: 1, ratio: '1 / 1' };
    case 'foto': return { span: 1, ratio: '4 / 3' };
    default:     return { span: 1, ratio: '4 / 3' };
  }
}

// Ano derivado do created_at no fuso de São Paulo (fallback '2026').
function yearSP(iso) {
  if (!iso) return '2026';
  try {
    return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', year: 'numeric' }).format(new Date(iso));
  } catch (e) { return '2026'; }
}

// Estáticos normalizados na MESMA shape dos itens do banco (preserva 4/5 e 4/3 atuais).
const STATIC_PROJECTS = PROJECTS.map((p) => ({
  name: p.name,
  client: p.client,
  badge: p.kind,
  formato: null,
  span: p.tall ? 2 : 1,
  ratio: p.tall ? '4 / 5' : '4 / 3',
  hue: p.hue,
  year: '2026',
  midia_url: null,
}));

// Camada de mídia real do case (banco). foto → <img>; demais → <video> play no hover.
function WorkMedia({ item, hov }) {
  const videoRef = useRefW(null);
  useEffectW(() => {
    const v = videoRef.current;
    if (!v) return;
    if (hov) { const p = v.play(); if (p && p.catch) p.catch(() => {}); }
    else { try { v.pause(); v.currentTime = 0; } catch (e) {} }
  }, [hov]);

  if (!item.midia_url) return null;
  const fill = { position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' };
  if (item.formato === 'foto') {
    return <img src={item.midia_url} alt={item.name || ''} loading="lazy" style={fill} />;
  }
  return <video ref={videoRef} src={item.midia_url} muted loop playsInline preload="metadata" style={fill} />;
}

function ProjectCard({ p, idx }) {
  const [hov, setHov] = useStateW(false);
  return (
    <div
      className="proj-slot"
      style={{
        position: 'relative',
        gridRow: `span ${p.span}`,
        aspectRatio: p.ratio,
      }}>
      {/* Drawer slot — visible when card lifts */}
      <div style={{
        position: 'absolute', inset: 0,
        border: '1px solid var(--accent)',
        borderColor: hov ? 'var(--accent)' : 'transparent',
        background: hov ? 'rgba(240,85,3,0.04)' : 'transparent',
        transition: 'border-color 0.5s, background 0.5s',
        pointerEvents: 'none',
      }} />
    <div
      data-cursor="link"
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        position: 'absolute', inset: 0,
        background: '#0a0a0a',
        border: '1px solid var(--line)',
        overflow: 'hidden',
        transform: hov ? 'translateY(-14px)' : 'translateY(0)',
        boxShadow: hov ? '0 28px 60px -10px rgba(0,0,0,0.7), 0 0 0 1px var(--accent)' : '0 0 0 0 rgba(0,0,0,0)',
        transition: 'transform 0.55s cubic-bezier(.2,.8,.2,1), box-shadow 0.55s cubic-bezier(.2,.8,.2,1), border-color 0.4s',
        borderColor: hov ? 'var(--accent)' : 'var(--line)',
        willChange: 'transform',
      }}>
      {/* Visual */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(${135 + idx * 20}deg, oklch(0.18 0.08 ${p.hue}) 0%, #0a0a0a 50%, oklch(0.12 0.04 ${p.hue}) 100%)`,
      }} />
      <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0 }}>
        <defs>
          <pattern id={`pp-${idx}`} patternUnits="userSpaceOnUse" width="80" height="80" patternTransform={`rotate(${idx * 18})`}>
            <line x1="0" y1="40" x2="80" y2="40" stroke="rgba(255,255,255,0.04)" strokeWidth="1"/>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#pp-${idx})`}/>
      </svg>

      {/* Mídia real (banco) sobre o gradiente — gradiente fica de fallback se não houver */}
      <WorkMedia item={p} hov={hov} />

      <div style={{
        position: 'absolute', inset: 0,
        background: hov
          ? `radial-gradient(circle at 50% 50%, rgba(240,85,3,0.18) 0%, transparent 70%)`
          : 'transparent',
        transition: 'background 0.5s',
      }} />

      {/* Hover "play" indicator — escondido quando é foto (imagem estática) */}
      {p.formato !== 'foto' && (
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: `translate(-50%,-50%) scale(${hov ? 1 : 0.6})`,
        opacity: hov ? 1 : 0,
        transition: 'all 0.5s cubic-bezier(.2,.8,.2,1)',
        width: 80, height: 80, borderRadius: '50%',
        border: '1px solid var(--accent)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'rgba(5,5,5,0.5)',
        backdropFilter: 'blur(4px)',
      }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.15em' }}>
          ▶ PLAY
        </span>
      </div>
      )}

      {/* Top label */}
      <div style={{
        position: 'absolute', top: 20, left: 20, right: 20,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <span className="mono uppercase tracked" style={{
          fontSize: 10, color: 'var(--accent)',
          padding: '4px 8px', border: '1px solid var(--accent)',
        }}>
          {p.badge}
        </span>
        <span className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)' }}>
          0{idx + 1}
        </span>
      </div>

      {/* Bottom info */}
      <div style={{
        position: 'absolute', bottom: 20, left: 20, right: 20,
      }}>
        <div className="display" style={{
          fontSize: p.span === 2 ? 'clamp(28px, 2.4vw, 36px)' : 'clamp(22px, 1.9vw, 28px)',
          fontWeight: 500, letterSpacing: '-0.03em',
          color: 'var(--fg)', lineHeight: 1,
        }}>
          {p.name}
        </div>
        <div className="mono uppercase tracked" style={{
          fontSize: 10, color: 'var(--fg-dim)', marginTop: 6,
        }}>
          {[p.client, p.year].filter(Boolean).join(' · ')}
        </div>
      </div>
    </div>
    </div>
  );
}

function Trabalhos() {
  // Estático = estado inicial (render instantâneo + rede de segurança). Troca p/ banco se houver publicados.
  const [projects, setProjects] = useStateW(STATIC_PROJECTS);
  const [fromDb, setFromDb] = useStateW(false);

  useEffectW(() => {
    let alive = true;
    (async () => {
      const sb = await waitForSbW();
      if (!sb || !alive) return;
      try {
        const { data, error } = await sb
          .from('portfolio_cases')
          .select('titulo, cliente_nome, descricao, midia_url, formato, created_at, ordem')
          .eq('publicado', true)
          .order('ordem', { ascending: true });
        if (error) throw error;
        if (alive && data && data.length) {
          setProjects(data.map((r, i) => ({
            name: r.titulo,
            client: r.cliente_nome || '',
            badge: r.formato || '',
            formato: r.formato || '',
            ...formatToLayout(r.formato),
            hue: (i * 40) % 360,
            year: yearSP(r.created_at),
            midia_url: r.midia_url || null,
          })));
          setFromDb(true);
        }
      } catch (e) {
        console.warn('[vitrine] portfolio_cases — mantendo fallback estático:', (e && e.message) || e);
      }
    })();
    return () => { alive = false; };
  }, []);

  return (
    <section id="trabalhos" className="section" style={{
      padding: '180px 6vw', position: 'relative', background: '#050505',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
        marginBottom: 80, flexWrap: 'wrap', gap: 24,
      }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 16 }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.1em' }}>
              02 / SELECIONADOS
            </span>
            <span style={{ width: 60, height: 1, background: 'var(--accent)' }} />
          </div>
          <div className="display" style={{
            fontSize: 'clamp(40px, 6vw, 88px)',
            fontWeight: 500, letterSpacing: '-0.04em', lineHeight: 0.95,
          }}>
            Trabalhos &amp; <br />
            <em style={{ color: 'var(--accent)', fontStyle: 'normal' }}>cases recentes.</em>
          </div>
        </div>
        <div style={{ maxWidth: 320 }}>
          <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--fg-dim)' }}>
            {fromDb ? (
              <>Seleção de <span style={{ color: 'var(--fg)' }}>cases recentes.</span> Direção, produção e finalização — do conceito à entrega.</>
            ) : (
              <>Em produção. <span style={{ color: 'var(--fg)' }}>Próximos cases em breve.</span> Esses são placeholders do que está em pipeline para 2026.</>
            )}
          </p>
        </div>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(3, 1fr)',
        gridAutoRows: '220px',
        gap: 16,
      }} className="works-grid">
        {projects.map((p, i) => <ProjectCard key={i} p={p} idx={i} />)}
      </div>

      <style>{`
        @media (max-width: 900px) {
          .works-grid { grid-template-columns: repeat(2, 1fr) !important; }
        }
        @media (max-width: 600px) {
          /* Coluna única: deixa cada card dimensionar pela própria proporção
             (o grid-row span + auto-rows fixos forçavam largura > viewport). */
          .works-grid { grid-template-columns: 1fr !important; grid-auto-rows: auto !important; }
          .works-grid .proj-slot { grid-row: auto !important; }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { Trabalhos });
