// Ricardo Vargas — Portfolio

const TALLY = '#E30613';

const useIsMobile = () => {
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const handler = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  return isMobile;
};

const Hamburger = ({ open }) => (
  <div style={{ width: 22, height: 16, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
    <span style={{ display: 'block', height: 1.5, background: '#fff', transition: 'transform 300ms', transformOrigin: 'center', transform: open ? 'translateY(7.25px) rotate(45deg)' : 'none' }}></span>
    <span style={{ display: 'block', height: 1.5, background: '#fff', transition: 'opacity 300ms', opacity: open ? 0 : 1 }}></span>
    <span style={{ display: 'block', height: 1.5, background: '#fff', transition: 'transform 300ms', transformOrigin: 'center', transform: open ? 'translateY(-7.25px) rotate(-45deg)' : 'none' }}></span>
  </div>
);

const Portfolio = () => {
  const [lang, setLang] = React.useState('en');
  const [tab, setTab] = React.useState('live');
  const [openProject, setOpenProject] = React.useState(null);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const isMobile = useIsMobile();
  const t = window.COPY[lang];
  const projects = window.PROJECTS[tab];
  const sectionLabel = tab === 'commercial' ? t.nav.commercial : t.nav.live;

  React.useEffect(() => {
    if (openProject) window.scrollTo({ top: 0, behavior: 'instant' });
  }, [openProject]);

  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  const handleTab = (newTab) => {
    setOpenProject(null);
    setTab(newTab);
    setMenuOpen(false);
  };

  return (
    <div style={{ background: '#0A0A0B', color: '#fff', minHeight: '100vh', fontFamily: '"Inter", sans-serif' }}>
      {/* Sticky header */}
      <header style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: isMobile ? '18px 20px' : '36px 56px 32px',
        position: 'sticky', top: 0, zIndex: 10,
        background: 'rgba(10,10,11,0.92)',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ width: 9, height: 9, borderRadius: '50%', background: TALLY, boxShadow: `0 0 12px ${TALLY}`, flexShrink: 0 }}></span>
          <a href="#top" onClick={(e) => { e.preventDefault(); setOpenProject(null); setTab('live'); setMenuOpen(false); window.scrollTo({ top: 0, behavior: 'smooth' }); }} style={{ color: '#fff', textDecoration: 'none', fontSize: isMobile ? 14 : 22, letterSpacing: '0.3em', fontWeight: 700 }}>RICARDO VARGAS</a>
          {!isMobile && <>
            <span style={{ width: 1, height: 18, background: 'rgba(255,255,255,0.22)', margin: '0 10px' }}></span>
            <div style={{ fontSize: 14, letterSpacing: '0.34em', color: 'rgba(255,255,255,0.6)', fontWeight: 500 }}>{t.role.toUpperCase()}</div>
          </>}
        </div>
        {isMobile ? (
          <button onClick={() => setMenuOpen(!menuOpen)} style={{ background: 'none', border: 0, color: '#fff', cursor: 'pointer', padding: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Hamburger open={menuOpen} />
          </button>
        ) : (
          <nav style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
            <NavSeg active={tab === 'live' && !openProject} onClick={() => handleTab('live')}>{t.nav.live.toUpperCase()}</NavSeg>
            <NavSeg active={tab === 'commercial' && !openProject} onClick={() => handleTab('commercial')}>{t.nav.commercial.toUpperCase()}</NavSeg>
            <a href="#contact" onClick={() => setOpenProject(null)} style={{ background: 'transparent', border: 0, padding: '4px 0', color: 'rgba(255,255,255,0.55)', fontSize: 13, letterSpacing: '0.22em', fontWeight: 500, textDecoration: 'none' }}>{t.nav.contact.toUpperCase()}</a>
            <span style={{ width: 1, height: 14, background: 'rgba(255,255,255,0.15)' }}></span>
            <LangToggle lang={lang} setLang={setLang} />
          </nav>
        )}
      </header>

      {/* Mobile menu overlay */}
      {isMobile && menuOpen && (
        <div onClick={() => setMenuOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(10,10,11,0.97)', backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)', zIndex: 9, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 40 }}>
          <NavSeg active={tab === 'live' && !openProject} onClick={() => handleTab('live')}>{t.nav.live.toUpperCase()}</NavSeg>
          <NavSeg active={tab === 'commercial' && !openProject} onClick={() => handleTab('commercial')}>{t.nav.commercial.toUpperCase()}</NavSeg>
          <a href="#contact" onClick={() => { setOpenProject(null); setMenuOpen(false); }} style={{ color: 'rgba(255,255,255,0.55)', fontSize: 13, letterSpacing: '0.22em', fontWeight: 500, textDecoration: 'none' }}>{t.nav.contact.toUpperCase()}</a>
          <LangToggle lang={lang} setLang={setLang} />
        </div>
      )}

      {openProject ?
        <ProjectDetail project={openProject} t={t} lang={lang} onBack={() => setOpenProject(null)} /> :
        <>
          {/* Meta row */}
          <div id="top" style={{ padding: isMobile ? '14px 20px 20px' : '20px 56px 32px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 11, letterSpacing: '0.36em', color: 'rgba(255,255,255,0.45)', fontWeight: 500 }}>
              {t.workLabel} — {sectionLabel.toUpperCase()}
            </div>
            <div style={{ fontSize: 11, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.35)' }}>
              {String(projects.length).padStart(2, '0')} {lang === 'en' ? 'PROJECTS' : 'PROYECTOS'}
            </div>
          </div>

          {projects.length === 0 ? <ComingSoon t={t} /> : <ProjectGrid projects={projects} t={t} onOpen={setOpenProject} />}

          <Contact lang={lang} t={t} />
        </>
      }
    </div>
  );
};

// ─── Project grid ────────────────────────────────────────────
const ProjectGrid = ({ projects, t, onOpen }) => {
  const isMobile = useIsMobile();
  const hero = projects.slice(0, 2);
  const rest = projects.slice(2);
  return (
    <div style={{ maxWidth: 1400, margin: '0 auto', padding: isMobile ? '0 12px' : '0 8px' }}>
      {hero.length > 0 &&
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : (hero.length === 1 ? '1fr' : 'repeat(2, 1fr)'),
          gap: isMobile ? 6 : 8
        }}>
          {hero.map((p) => <Tile key={p.id} p={p} t={t} large onClick={() => onOpen(p)} />)}
        </div>
      }
      {rest.length > 0 &&
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 6 : 8, marginTop: isMobile ? 6 : 8 }}>
          {rest.map((p) => <Tile key={p.id} p={p} t={t} onClick={() => onOpen(p)} />)}
        </div>
      }
    </div>
  );
};

// ─── Coming soon ─────────────────────────────────────────────
const ComingSoon = ({ t }) =>
  <div style={{
    margin: '0 8px', padding: '120px 40px',
    border: '1px solid rgba(255,255,255,0.08)',
    background: 'linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0))',
    textAlign: 'center'
  }}>
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 28, padding: '6px 14px', border: `1px solid ${TALLY}`, color: TALLY, fontSize: 10, letterSpacing: '0.36em', fontWeight: 600 }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: TALLY, animation: 'pulse 1.6s ease-in-out infinite' }}></span>
      {t.recLabel}
    </div>
    <h2 style={{ margin: 0, fontSize: 38, lineHeight: 1.1, letterSpacing: '0.02em', fontWeight: 600, maxWidth: 720, marginLeft: 'auto', marginRight: 'auto' }}>
      {t.comingSoon}
    </h2>
    <p style={{ marginTop: 18, fontSize: 14, letterSpacing: '0.04em', color: 'rgba(255,255,255,0.55)', maxWidth: 520, marginLeft: 'auto', marginRight: 'auto' }}>
      {t.comingSoonSub}
    </p>
    <style>{`@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }`}</style>
  </div>;


// ─── Tile ────────────────────────────────────────────────────
const Tile = ({ p, t, large, onClick }) => {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick}
      style={{
        position: 'relative', aspectRatio: '16/9',
        overflow: 'hidden', cursor: 'pointer', background: '#000'
      }}>
      <img src={p.img} alt={p.title} style={{
        width: '100%', height: '100%', objectFit: 'cover',
        transition: 'all 700ms cubic-bezier(0.2, 0.8, 0.2, 1)',
        filter: hover ? 'brightness(0.25) saturate(0.75)' : 'brightness(0.95)',
        transform: hover ? 'scale(1.04)' : 'scale(1)'
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        opacity: hover ? 1 : 0,
        transition: 'opacity 450ms ease',
        padding: 24
      }}>
        <div style={{ position: 'relative', padding: '24px 32px', textAlign: 'center', maxWidth: '90%' }}>
          <span style={bracket('tl')}></span>
          <span style={bracket('tr')}></span>
          <span style={bracket('bl')}></span>
          <span style={bracket('br')}></span>
          <div style={{ fontSize: 10, letterSpacing: '0.4em', color: 'rgba(255,255,255,0.7)', marginBottom: 12, fontWeight: 500 }}>
            {p.client.toUpperCase()} — {p.year}
          </div>
          <div style={{ fontSize: large ? 22 : 18, letterSpacing: '0.08em', fontWeight: 600, lineHeight: 1.3 }}>
            {p.title}
          </div>
        </div>
      </div>
      <div style={{
        position: 'absolute', bottom: 12, right: 14,
        fontSize: 10, letterSpacing: '0.3em', color: 'rgba(255,255,255,0.5)',
        opacity: hover ? 0 : 1, transition: 'opacity 250ms',
        textShadow: '0 1px 4px rgba(0,0,0,0.6)',
        fontWeight: 500
      }}>{p.year}</div>
    </div>
  );
};

const bracket = (corner) => {
  const size = 14, color = 'rgba(255,255,255,0.85)', w = 1;
  const base = { position: 'absolute', width: size, height: size };
  if (corner === 'tl') return { ...base, top: 0, left: 0, borderTop: `${w}px solid ${color}`, borderLeft: `${w}px solid ${color}` };
  if (corner === 'tr') return { ...base, top: 0, right: 0, borderTop: `${w}px solid ${color}`, borderRight: `${w}px solid ${color}` };
  if (corner === 'bl') return { ...base, bottom: 0, left: 0, borderBottom: `${w}px solid ${color}`, borderLeft: `${w}px solid ${color}` };
  if (corner === 'br') return { ...base, bottom: 0, right: 0, borderBottom: `${w}px solid ${color}`, borderRight: `${w}px solid ${color}` };
};

// ─── Project Detail ──────────────────────────────────────────
const ProjectDetail = ({ project, t, lang, onBack }) => {
  const isMobile = useIsMobile();
  const sidePad = isMobile ? '0 20px' : '0 56px';
  return (
    <div style={{ paddingBottom: 80 }}>
      {/* Back link */}
      <div style={{ padding: isMobile ? '16px 20px 20px' : '20px 56px 24px' }}>
        <button onClick={onBack} style={{
          background: 'transparent', border: 0, padding: 0,
          color: 'rgba(255,255,255,0.55)', fontSize: 11, letterSpacing: '0.3em',
          fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', gap: 10
        }}>
          <span style={{ display: 'inline-block', width: 18, height: 1, background: 'currentColor' }}></span>
          {t.backToWork.toUpperCase()}
        </button>
      </div>

      {/* Title block */}
      <div style={{ textAlign: 'center', padding: isMobile ? '16px 20px 24px' : '24px 56px 32px' }}>
        <div style={{ fontSize: 11, letterSpacing: '0.4em', color: TALLY, fontWeight: 600, marginBottom: 16 }}>
          {project.client.toUpperCase()} · {project.year}
        </div>
        <h1 style={{ margin: 0, fontSize: isMobile ? 28 : 64, lineHeight: 1.1, letterSpacing: '0.04em', fontWeight: 700 }}>
          {project.title}
        </h1>
        <div style={{ marginTop: 16, fontSize: 13, letterSpacing: '0.04em', color: 'rgba(255,255,255,0.6)', fontWeight: 500 }}>
          {project.credits[0]?.role[lang]}: <span style={{ color: 'rgba(255,255,255,0.9)' }}>{project.credits[0]?.name}</span>
          <span style={{ margin: '0 12px', color: 'rgba(255,255,255,0.3)' }}>|</span>
          {project.credits[1]?.role[lang]}: <span style={{ color: 'rgba(255,255,255,0.9)' }}>{project.credits[1]?.name}</span>
        </div>
      </div>

      {/* Hero video player */}
      <div style={{ padding: sidePad, maxWidth: 1512, margin: '0 auto' }}>
        <VideoPlayer src={project.hero} title={project.title} vimeoId={project.vimeoId} vimeoHash={project.vimeoHash} />
      </div>

      {/* Credits + Gear */}
      <div style={{ padding: isMobile ? '40px 20px 0' : '64px 56px 0', textAlign: 'center' }}>
        <div style={{ fontSize: 13, letterSpacing: '0.18em', color: 'rgba(255,255,255,0.85)', lineHeight: 2, fontWeight: 500, maxWidth: 640, margin: '0 auto' }}>
          <div style={{ fontSize: 12, letterSpacing: '0.4em', color: TALLY, fontWeight: 700, marginBottom: 16 }}>
            {project.title}
          </div>
          <div style={{ color: 'rgba(255,255,255,0.7)' }}>
            {lang === 'en' ? 'Shot on' : 'Filmado en'} <span style={{ color: '#fff' }}>{project.gear.cameras[0]}</span> {lang === 'en' ? 'using' : 'usando'} <span style={{ color: '#fff' }}>{project.gear.lenses[0]}</span> {lang === 'en' ? 'and' : 'y'} <span style={{ color: '#fff' }}>{project.gear.lenses[1]}</span>.
          </div>
          {project.credits.map((c, i) =>
            <div key={i} style={{ color: 'rgba(255,255,255,0.7)' }}>
              {c.role[lang]}: <span style={{ color: '#fff' }}>{c.name}</span>
            </div>
          )}
        </div>
      </div>

      {/* Camera + lens detail blocks */}
      <div style={{ padding: isMobile ? '40px 20px 0' : '72px 56px 0', display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 28 : 32 }}>
        <GearBlock label={t.cameras} items={project.gear.cameras} />
        <GearBlock label={t.lenses} items={project.gear.lenses} />
        <GearBlock label={t.format} items={[project.gear.format]} />
      </div>

      {/* More frames carousel */}
      <div style={{ marginTop: isMobile ? 56 : 96 }}>
        <div style={{ padding: isMobile ? '0 20px 20px' : '0 56px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div style={{ fontSize: 11, letterSpacing: '0.36em', color: 'rgba(255,255,255,0.45)', fontWeight: 500 }}>
            {t.moreFrames.toUpperCase()}
          </div>
        </div>
        <Carousel images={project.gallery} />
      </div>
    </div>
  );
};

const GearBlock = ({ label, items }) =>
  <div>
    <div style={{ fontSize: 10, letterSpacing: '0.36em', color: 'rgba(255,255,255,0.4)', fontWeight: 500, marginBottom: 14, paddingBottom: 12, borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
      {label.toUpperCase()}
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {items.map((it, i) =>
        <div key={i} style={{ fontSize: 14, letterSpacing: '0.02em', color: 'rgba(255,255,255,0.85)', fontWeight: 500 }}>{it}</div>
      )}
    </div>
  </div>;


// ─── Video player ─────────────────────────────────────────────
const VideoPlayer = ({ src, title, vimeoId, vimeoHash }) => {
  if (vimeoId) {
    const url = `https://player.vimeo.com/video/${vimeoId}?h=${vimeoHash}&autoplay=0&title=0&byline=0&portrait=0`;
    return (
      <div style={{ position: 'relative', aspectRatio: '16/9', background: '#000' }}>
        <iframe
          src={url}
          title={title}
          width="100%" height="100%"
          style={{ position: 'absolute', inset: 0, border: 0 }}
          allow="autoplay; fullscreen; picture-in-picture; clipboard-write; encrypted-media"
          allowFullScreen
        />
      </div>
    );
  }

  const [playing, setPlaying] = React.useState(false);
  return (
    <div style={{ position: 'relative', aspectRatio: '16/9', overflow: 'hidden', background: '#000', cursor: 'pointer' }}
      onClick={() => setPlaying(!playing)}>
      <img src={src} alt={title} style={{
        width: '100%', height: '100%', objectFit: 'cover',
        filter: playing ? 'brightness(1)' : 'brightness(0.85)',
        transition: 'filter 300ms'
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        opacity: playing ? 0 : 1, transition: 'opacity 300ms'
      }}>
        <div style={{
          width: 88, height: 88, borderRadius: '50%',
          background: 'rgba(255,255,255,0.12)',
          backdropFilter: 'blur(8px)',
          border: '1.5px solid rgba(255,255,255,0.6)',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <div style={{
            width: 0, height: 0,
            borderTop: '14px solid transparent',
            borderBottom: '14px solid transparent',
            borderLeft: '22px solid #fff',
            marginLeft: 6
          }}></div>
        </div>
      </div>
    </div>
  );
};

// ─── Carousel ─────────────────────────────────────────────────
const Carousel = ({ images }) => {
  const isMobile = useIsMobile();
  const [idx, setIdx] = React.useState(0);
  const next = () => setIdx((idx + 1) % images.length);
  const prev = () => setIdx((idx - 1 + images.length) % images.length);
  return (
    <div style={{ padding: isMobile ? '0 12px' : '0 56px', maxWidth: 1512, margin: '0 auto' }}>
      <div style={{ position: 'relative', aspectRatio: '16/9', overflow: 'hidden', background: '#000' }}>
        {images.map((src, i) =>
          <img
            key={i}
            src={src}
            alt={`Frame ${i + 1}`}
            style={{
              position: 'absolute', inset: 0,
              width: '100%', height: '100%', objectFit: 'cover',
              opacity: i === idx ? 1 : 0,
              transition: 'opacity 600ms ease'
            }} />
        )}
        {/* Arrows */}
        <button onClick={prev} style={arrowStyle('left')} aria-label="Previous">
          <ArrowSvg dir="left" />
        </button>
        <button onClick={next} style={arrowStyle('right')} aria-label="Next">
          <ArrowSvg dir="right" />
        </button>
        {/* Counter */}
        <div style={{
          position: 'absolute', bottom: 16, left: '50%', transform: 'translateX(-50%)',
          fontSize: 10, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.85)',
          background: 'rgba(0,0,0,0.5)', padding: '6px 14px',
          fontWeight: 500
        }}>
          {String(idx + 1).padStart(2, '0')} / {String(images.length).padStart(2, '0')}
        </div>
      </div>
      {/* Thumbs */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(3, 1fr)' : `repeat(${images.length}, 1fr)`, gap: 6, marginTop: 8 }}>
        {images.map((src, i) =>
          <button key={i} onClick={() => setIdx(i)} style={{
            border: 0, padding: 0, cursor: 'pointer', background: '#000',
            aspectRatio: '16/9', overflow: 'hidden',
            opacity: i === idx ? 1 : 0.4,
            outline: i === idx ? `1px solid ${TALLY}` : 'none',
            outlineOffset: -1,
            transition: 'opacity 200ms'
          }}>
            <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          </button>
        )}
      </div>
    </div>
  );
};

const arrowStyle = (side) => ({
  position: 'absolute', top: '50%', transform: 'translateY(-50%)',
  [side]: 12,
  width: 40, height: 40, borderRadius: '50%',
  background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(6px)',
  border: '1px solid rgba(255,255,255,0.3)',
  color: '#fff', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  transition: 'background 200ms'
});

const ArrowSvg = ({ dir }) =>
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ transform: dir === 'left' ? 'rotate(180deg)' : 'none' }}>
    <path d="M3 7H11M11 7L7 3M11 7L7 11" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
  </svg>;


// ─── Nav button + lang ───────────────────────────────────────
const NavSeg = ({ active, onClick, children }) =>
  <button
    onClick={onClick}
    style={{
      background: 'transparent', border: 0, padding: '4px 0',
      color: active ? '#fff' : 'rgba(255,255,255,0.55)',
      fontSize: 13, letterSpacing: '0.22em', fontWeight: 500, cursor: 'pointer',
      fontFamily: 'inherit',
      borderBottom: active ? `1px solid ${TALLY}` : '1px solid transparent',
      transition: 'all 200ms'
    }}>
    {children}
  </button>;


const LangToggle = ({ lang, setLang }) =>
  <div style={{ display: 'flex', gap: 10, fontSize: 11, letterSpacing: '0.22em', fontWeight: 500 }}>
    <button onClick={() => setLang('en')} style={{ background: 'none', border: 0, color: lang === 'en' ? '#fff' : 'rgba(255,255,255,0.4)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'inherit', letterSpacing: 'inherit', fontWeight: 'inherit', padding: 0 }}>EN</button>
    <span style={{ color: 'rgba(255,255,255,0.22)' }}>·</span>
    <button onClick={() => setLang('es')} style={{ background: 'none', border: 0, color: lang === 'es' ? '#fff' : 'rgba(255,255,255,0.4)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'inherit', letterSpacing: 'inherit', fontWeight: 'inherit', padding: 0 }}>ES</button>
  </div>;


// ─── Contact ─────────────────────────────────────────────────
const Contact = ({ lang, t }) => {
  const isMobile = useIsMobile();
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [msg, setMsg] = React.useState('');
  const [status, setStatus] = React.useState('idle');
  const [honey, setHoney] = React.useState('');
  const [lastSubmit, setLastSubmit] = React.useState(null);
  const [turnstileToken, setTurnstileToken] = React.useState('');
  const turnstileRef = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  React.useEffect(() => {
    const tryRender = () => {
      if (window.turnstile && turnstileRef.current && widgetIdRef.current === null) {
        widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
          sitekey: '0x4AAAAAADJD0zDbWlNCGMBv',
          theme: 'dark',
          callback: (token) => setTurnstileToken(token),
          'expired-callback': () => setTurnstileToken(''),
          'error-callback': () => setTurnstileToken(''),
        });
      }
    };
    tryRender();
    if (!window.turnstile) {
      const id = setInterval(() => { if (window.turnstile) { clearInterval(id); tryRender(); } }, 100);
      return () => clearInterval(id);
    }
  }, []);

  const labels = lang === 'en' ?
    { name: 'Name', email: 'Email', project: 'Tell me about your project', send: 'Send inquiry', sent: 'Thanks — I\'ll be in touch.', error: 'Something went wrong. Try again.', or: 'Or email directly', based: 'Based', social: 'Social', mty: 'Cartago, CR', work: 'Working nationwide' } :
    { name: 'Nombre', email: 'Correo', project: 'Cuéntame sobre tu proyecto', send: 'Enviar mensaje', sent: 'Gracias — pronto te contacto.', error: 'Algo salió mal. Intenta de nuevo.', or: 'O escribe directamente', based: 'Sede', social: 'Redes', mty: 'Cartago, CR', work: 'Trabajando nacionalmente' };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (honey) { setStatus('sent'); return; }
    if (!turnstileToken) return;
    if (lastSubmit && Date.now() - lastSubmit < 60_000) { setStatus('ratelimit'); return; }
    if (!name.trim() || !email.trim() || !msg.trim()) return;
    if (name.length > 200 || email.length > 320 || msg.length > 5000) { setStatus('error'); return; }
    setStatus('sending');
    try {
      const res = await fetch('https://formspree.io/f/xjglwkrw', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ name, email, message: msg, 'cf-turnstile-response': turnstileToken }),
      });
      if (res.ok) { setStatus('sent'); setLastSubmit(Date.now()); } else { setStatus('error'); }
    } catch { setStatus('error'); }
  };

  const sent = status === 'sent';
  const sending = status === 'sending';
  const ratelimited = status === 'ratelimit';

  return (
    <section id="contact" style={{ marginTop: isMobile ? 60 : 120, padding: isMobile ? '56px 20px 40px' : '80px 56px 56px', borderTop: '1px solid rgba(255,255,255,0.08)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: isMobile ? 36 : 56 }}>
        <div style={{ fontSize: 11, letterSpacing: '0.36em', color: 'rgba(255,255,255,0.45)', fontWeight: 500 }}>
          {t.nav.contact.toUpperCase()}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.45)' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: TALLY, boxShadow: `0 0 8px ${TALLY}` }}></span>
          {lang === 'en' ? 'AVAILABLE' : 'DISPONIBLE'} · 2026
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.2fr 1fr', gap: isMobile ? 48 : 80, alignItems: 'flex-start' }}>
        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          {/* Honeypot — invisible to users, filled only by bots */}
          <input type="text" name="_gotcha" value={honey} onChange={(e) => setHoney(e.target.value)} style={{ display: 'none' }} tabIndex="-1" autoComplete="off" aria-hidden="true" />
          <h2 style={{ margin: 0, fontSize: isMobile ? 32 : 44, lineHeight: 1.05, letterSpacing: '-0.01em', fontWeight: 600, marginBottom: 40, maxWidth: 560 }}>
            {t.contactHeading}
          </h2>
          <FormField label={labels.name} value={name} onChange={setName} disabled={sent} />
          <FormField label={labels.email} value={email} onChange={setEmail} disabled={sent} type="email" />
          <FormField label={labels.project} value={msg} onChange={setMsg} disabled={sent} multiline />
          <div ref={turnstileRef} style={{ marginTop: 28 }}></div>
          <button
            type="submit"
            disabled={sent || sending || ratelimited || !turnstileToken}
            style={{
              marginTop: 28, alignSelf: 'flex-start',
              background: sent ? 'transparent' : TALLY,
              color: '#fff',
              border: sent ? '1px solid rgba(255,255,255,0.3)' : `1px solid ${TALLY}`,
              padding: '16px 32px',
              fontSize: 12, letterSpacing: '0.28em', fontWeight: 600,
              cursor: (sent || sending) ? 'default' : 'pointer',
              fontFamily: 'inherit',
              transition: 'all 200ms',
              opacity: sending ? 0.6 : 1,
            }}
            onMouseEnter={(e) => { if (!sent && !sending && !ratelimited) e.currentTarget.style.background = '#B8050F'; }}
            onMouseLeave={(e) => { if (!sent && !sending && !ratelimited) e.currentTarget.style.background = TALLY; }}>
            {sent ? `✓  ${labels.sent.toUpperCase()}` : sending ? '...' : `${labels.send.toUpperCase()}  →`}
          </button>
          {status === 'error' && (
            <div style={{ marginTop: 12, fontSize: 12, color: TALLY, letterSpacing: '0.1em' }}>
              {labels.error}
            </div>
          )}
          {status === 'ratelimit' && (
            <div style={{ marginTop: 12, fontSize: 12, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.1em' }}>
              {lang === 'en' ? 'Please wait a moment before sending again.' : 'Por favor espera un momento antes de enviar de nuevo.'}
            </div>
          )}
        </form>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 40, paddingTop: isMobile ? 0 : 8 }}>
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.4)', marginBottom: 12, fontWeight: 500 }}>
              {labels.or.toUpperCase()}
            </div>
            <a href={`mailto:${t.contactEmail}`} style={{ color: '#fff', fontSize: isMobile ? 16 : 22, letterSpacing: '0.02em', textDecoration: 'none', fontWeight: 500, borderBottom: '1px solid rgba(255,255,255,0.25)', paddingBottom: 4 }}>
              {t.contactEmail}
            </a>
          </div>
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.4)', marginBottom: 12, fontWeight: 500 }}>
              {labels.based.toUpperCase()}
            </div>
            <div style={{ fontSize: 15, letterSpacing: '0.04em', color: 'rgba(255,255,255,0.85)', lineHeight: 1.6 }}>
              {labels.mty}<br />
              <span style={{ color: 'rgba(255,255,255,0.45)' }}>{labels.work}</span>
            </div>
          </div>
          <div>
            <div style={{ fontSize: 10, letterSpacing: '0.32em', color: 'rgba(255,255,255,0.4)', marginBottom: 12, fontWeight: 500 }}>
              {labels.social.toUpperCase()}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13, letterSpacing: '0.16em' }}>
              <a href="https://www.instagram.com/rvargas1606/" target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(255,255,255,0.85)', textDecoration: 'none' }}>INSTAGRAM ↗</a>
              <a href="https://vimeo.com/ricardovargas?fl=pp&fe=sh" target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(255,255,255,0.85)', textDecoration: 'none' }}>VIMEO ↗</a>
            </div>
          </div>
        </div>
      </div>

      <div style={{ marginTop: isMobile ? 56 : 96, paddingTop: 28, borderTop: '1px solid rgba(255,255,255,0.06)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 10, letterSpacing: '0.3em', color: 'rgba(255,255,255,0.35)' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: TALLY }}></span>
          © 2026 RICARDO VARGAS
        </div>
        <div style={{ fontSize: 10, letterSpacing: '0.3em', color: 'rgba(255,255,255,0.3)' }}>
          {lang === 'en' ? 'CRAFTED IN CR' : 'HECHO EN CR'}
        </div>
      </div>
    </section>
  );
};

const FormField = ({ label, value, onChange, disabled, type = 'text', multiline }) => {
  const [focus, setFocus] = React.useState(false);
  const Tag = multiline ? 'textarea' : 'input';
  return (
    <label style={{ display: 'block', borderBottom: `1px solid ${focus ? TALLY : 'rgba(255,255,255,0.18)'}`, paddingTop: 22, paddingBottom: 12, transition: 'border 200ms' }}>
      <div style={{ fontSize: 10, letterSpacing: '0.3em', color: focus ? TALLY : 'rgba(255,255,255,0.45)', fontWeight: 500, marginBottom: 8, textTransform: 'uppercase', transition: 'color 200ms' }}>
        {label}
      </div>
      <Tag
        type={type}
        value={value}
        disabled={disabled}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocus(true)}
        onBlur={() => setFocus(false)}
        rows={multiline ? 3 : undefined}
        style={{
          width: '100%', background: 'transparent', border: 0, outline: 'none',
          color: '#fff', fontSize: 17, fontFamily: 'inherit',
          padding: 0, resize: 'none',
          letterSpacing: '0.01em'
        }} />
    </label>
  );
};

window.Portfolio = Portfolio;
