// home.jsx — Portfolio hub

const THEMES = {
  dark: {
    bg:         '#000000',
    fg:         '#FFFFFF',
    muted:      'rgba(255,255,255,0.48)',
    dim:        'rgba(255,255,255,0.24)',
    rule:       'rgba(255,255,255,0.10)',
    toggleBg:   'rgba(255,255,255,0.12)',
    toggleFg:   '#FFFFFF',
    toggleHover:'rgba(255,255,255,0.20)',
    hoverBg:    'rgba(255,255,255,0.04)',
  },
  light: {
    bg:         '#F0EEE9',
    fg:         '#0A0A0A',
    muted:      'rgba(0,0,0,0.48)',
    dim:        'rgba(0,0,0,0.28)',
    rule:       'rgba(0,0,0,0.10)',
    toggleBg:   '#1A1A1A',
    toggleFg:   '#FFFFFF',
    toggleHover:'#333333',
    hoverBg:    'rgba(0,0,0,0.04)',
  },
};

const HOME_SANS = "'Inter Tight', system-ui, sans-serif";
const HOME_MONO = "'Space Mono', ui-monospace, monospace";

const ThemeCtx = React.createContext({ theme: THEMES.light, mode: 'light', toggle: () => {} });

function useThemePref() {
  const stored = localStorage.getItem('hub-theme');
  const [mode, setMode] = React.useState(
    stored === 'light' || stored === 'dark' ? stored : 'light'
  );
  const toggle = () => {
    const next = mode === 'dark' ? 'light' : 'dark';
    localStorage.setItem('hub-theme', next);
    setMode(next);
  };
  return { mode, theme: THEMES[mode], toggle };
}

const CASES = [
  {
    id:          'picpay',
    company:     'PicPay',
    projectName: 'Impact System',
    role:        'Head of Design Foundation',
    year:        '2023–2024',
    status:      'live',
    thumb:       '/picpay/assets/img/picpay-featured.png',
    video:       '/assets/video/pp-bank-color.mp4',
  },
  {
    id:          'gubertech',
    company:     'Gubertech',
    projectName: 'Brand Strategy & Identity',
    role:        'Solo Brand Strategist & Designer',
    year:        '2024 – ongoing',
    status:      'live',
    thumb:       '/gubertech/assets/img/gubertech-featured3.png',
    video:       null,
  },
  {
    id:          'nubank',
    company:     'Nubank',
    projectName: 'Negotiation Platform – Design Chassis LATAM',
    role:        'Staff Product Designer',
    year:        '2026',
    status:      'coming-soon',
    thumb:       null,
    video:       null,
  },
  {
    id:          'btg',
    company:     'BTG Pactual',
    projectName: 'Building a Retail bank that millions trust',
    role:        'Associate Design Director',
    year:        '2022–2023',
    status:      'coming-soon',
    thumb:       null,
    video:       null,
  },
];

const ROULETTE_ROLES = [
  'Staff Product Designer – LATAM',
  'Design System and Foundations Lead',
  'Experience Architect',
  'Design Engineer Lead',
];

function useInView(ref, delay = 0) {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setTimeout(() => setVisible(true), delay);
        obs.disconnect();
      }
    }, { threshold: 0.05, rootMargin: '0px 0px -50px 0px' });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [delay]);
  return visible;
}

// ── Icons ─────────────────────────────────────────────────────────────────────

function IconMoon({ color = 'currentColor', size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }}>
      <path d="M21 12.79A9 9 0 1 1 11.21 3a7 7 0 0 0 9.79 9.79Z"
        stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function IconSun({ color = 'currentColor', size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }}>
      <circle cx="12" cy="12" r="4" stroke={color} strokeWidth="1.5" />
      <path d="M12 2v2M12 20v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M2 12h2M20 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"
        stroke={color} strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

// ── NavMenu ───────────────────────────────────────────────────────────────────

function NavMenuLink({ label, href, theme }) {
  const [hovered, setHovered] = React.useState(false);

  return (
    <a
      href={href}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: 'inline-block',
        fontFamily: HOME_MONO,
        fontSize: 12,
        letterSpacing: '0.12em',
        textTransform: 'uppercase',
        textDecoration: 'none',
        color: hovered ? theme.fg : theme.muted,
        transition: 'color 200ms ease',
        position: 'relative',
        overflow: 'hidden',
        height: '20px',
      }}
    >
      <span style={{
        display: 'inline-block',
        transition: hovered
          ? 'transform 350ms cubic-bezier(0.25, 1, 0.5, 1)'
          : 'transform 500ms cubic-bezier(0.34, 1.56, 0.64, 1)',
        transform: hovered ? 'translateY(-120%)' : 'translateY(0)',
      }}>
        {label}
      </span>
      <span style={{
        position: 'absolute',
        top: '100%',
        left: 0,
        display: 'inline-block',
        color: theme.fg,
        transition: hovered
          ? 'transform 350ms cubic-bezier(0.25, 1, 0.5, 1)'
          : 'transform 500ms cubic-bezier(0.34, 1.56, 0.64, 1)',
        transform: hovered ? 'translateY(-100%)' : 'translateY(0)',
      }}>
        {label}
      </span>
    </a>
  );
}

function NavMenuActive({ label, theme }) {
  return (
    <span
      style={{
        display: 'inline-block',
        fontFamily: HOME_MONO,
        fontSize: 12,
        letterSpacing: '0.12em',
        textTransform: 'uppercase',
        color: theme.fg,
        position: 'relative',
        height: '20px',
        lineHeight: '20px',
      }}
    >
      {label}
      <span
        style={{
          position: 'absolute',
          bottom: -6,
          left: 0,
          right: 0,
          height: 1,
          background: theme.fg,
          transform: 'scaleX(0)',
          transformOrigin: 'center',
          animation: 'nav-underline 400ms cubic-bezier(0.25, 1, 0.5, 1) 300ms forwards',
        }}
      />
    </span>
  );
}

function NavMenu({ currentPage = 'hub' }) {
  const { theme } = React.useContext(ThemeCtx);
  const items = [
    { id: 'hub', label: 'Hub', href: '/' },
    { id: 'about', label: 'About', href: '/about/' },
  ];

  return (
    <nav style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
      {items.map((item) => {
        const isActive = currentPage === item.id;
        return isActive
          ? <NavMenuActive key={item.id} label={item.label} theme={theme} />
          : <NavMenuLink key={item.id} label={item.label} href={item.href} theme={theme} />;
      })}
    </nav>
  );
}

// ── ThemeToggle ───────────────────────────────────────────────────────────────

function ThemeToggle() {
  const { mode, theme, toggle } = React.useContext(ThemeCtx);
  const [hovered, setHovered] = React.useState(false);
  const [isAnimating, setIsAnimating] = React.useState(false);
  const isDark = mode === 'dark';

  const handleClick = () => {
    setIsAnimating(true);
    toggle();
    setTimeout(() => setIsAnimating(false), 300);
  };

  const iconColor = isDark ? '#FFFFFF' : '#1A1A1A';

  return (
    <button
      onClick={handleClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      aria-label={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
      style={{
        width: 44, height: 44, borderRadius: '50%',
        border: `1px solid ${isDark ? 'rgba(255,255,255,0.15)' : 'rgba(0,0,0,0.15)'}`,
        background: 'transparent',
        cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'background 200ms ease, transform 200ms ease, border-color 200ms ease',
        transform: hovered ? 'scale(1.08)' : 'scale(1)',
        flexShrink: 0,
        overflow: 'hidden',
        position: 'relative',
      }}
    >
      <div style={{
        position: 'relative',
        width: 18,
        height: 18,
        transition: 'transform 300ms cubic-bezier(.16,1,.3,1)',
        transform: isAnimating
          ? (isDark ? 'rotate(-90deg) scale(0.5)' : 'rotate(90deg) scale(0.5)')
          : 'rotate(0) scale(1)',
        opacity: isAnimating ? 0 : 1,
      }}>
        {isDark
          ? <IconMoon color={iconColor} size={18} />
          : <IconSun color={iconColor} size={18} />
        }
      </div>
    </button>
  );
}

// ── ViewCaseBtn ───────────────────────────────────────────────────────────────

const CASE_BTN_W = 148;

function ViewCaseBtn({ hovered }) {
  const { theme } = React.useContext(ThemeCtx);
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      width: CASE_BTN_W,
      fontFamily: HOME_MONO, fontSize: 11,
      letterSpacing: '0.18em', textTransform: 'uppercase',
      color: hovered ? theme.bg : theme.fg,
      border: `1px solid ${theme.fg}`,
      borderRadius: 4,
      padding: '11px 0',
      background: hovered ? theme.fg : 'transparent',
      transition: 'background 180ms ease, color 180ms ease',
      whiteSpace: 'nowrap',
      boxSizing: 'border-box',
    }}>
      <span>View case</span>
      <span style={{
        display: 'inline-block',
        animation: hovered ? 'hub-bounce 0.55s cubic-bezier(.36,.07,.19,.97) infinite' : 'none',
        fontSize: 13, width: 13,
      }}>↗</span>
    </div>
  );
}

// ── CustomCursor ─────────────────────────────────────────────────────────────

function useCustomCursor() {
  const [pos, setPos]         = React.useState({ x: -200, y: -200 });
  const [active, setActive]   = React.useState(false);
  const isFine = React.useRef(
    typeof window !== 'undefined' && window.matchMedia('(pointer: fine)').matches
  );

  React.useEffect(() => {
    if (!isFine.current) return;
    const onMove = (e) => setPos({ x: e.clientX, y: e.clientY });
    window.addEventListener('mousemove', onMove, { passive: true });
    return () => window.removeEventListener('mousemove', onMove);
  }, []);

  return { pos, active, setActive, enabled: isFine.current };
}

const CursorCtx = React.createContext({ setActive: () => {}, enabled: false });

// ── CaseCard ──────────────────────────────────────────────────────────────────

function CaseCard({ id, company, projectName, role, year, status, thumb, video, index = 0 }) {
  const { theme }             = React.useContext(ThemeCtx);
  const { setActive, enabled} = React.useContext(CursorCtx);
  const ref       = React.useRef(null);
  const videoRef  = React.useRef(null);
  const visible   = useInView(ref, index * 150);
  const [hovered, setHovered] = React.useState(false);
  const isLive = status === 'live';

  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    if (hovered) { v.currentTime = 0; v.play().catch(() => {}); }
    else { v.pause(); v.currentTime = 0; }
  }, [hovered]);

  return (
    <a
      ref={ref}
      href={isLive ? `/${id}/?lang=en` : undefined}
      onMouseEnter={() => { if (isLive) setHovered(true); }}
      onMouseLeave={() => { setHovered(false); }}
      style={{
        display: 'block',
        textDecoration: 'none',
        color: theme.fg,
        cursor: isLive ? 'pointer' : 'default',
        opacity: visible ? 1 : 0,
        transform: visible
          ? (hovered ? 'translateX(6px)' : 'translateX(0)')
          : 'translateY(48px)',
        transition: 'opacity 900ms cubic-bezier(.16,1,.3,1), transform 600ms cubic-bezier(.16,1,.3,1)',
        pointerEvents: isLive ? 'auto' : 'none',
      }}
    >
      <div style={{
        borderTop: `1px solid ${hovered ? (theme.rule.replace(/[\d.]+\)$/, '0.45)')) : theme.rule}`,
        paddingTop: 32, paddingBottom: 32,
        display: 'grid',
        gridTemplateColumns: '1fr auto auto',
        gap: 40,
        alignItems: 'center',
        background: hovered ? theme.hoverBg : 'transparent',
        marginLeft: -24, marginRight: -24, paddingLeft: 24, paddingRight: 24,
        transition: 'border-color 320ms cubic-bezier(.4,0,.2,1), background 320ms cubic-bezier(.4,0,.2,1)',
      }}>
        {/* Text */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{
            fontSize: 'clamp(20px, 2.6vw, 38px)', fontWeight: 500,
            letterSpacing: '-0.04em', lineHeight: 0.95,
            color: isLive ? theme.fg : theme.muted,
            fontFamily: HOME_SANS,
          }}>
            {company}
          </div>
          <div style={{
            fontSize: 'clamp(11px, 1.1vw, 16px)', fontWeight: 400, fontStyle: 'italic',
            letterSpacing: '-0.01em',
            color: isLive ? theme.muted : theme.dim,
            fontFamily: HOME_SANS,
          }}>
            {projectName}
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 4 }}>
            <div style={{
              fontFamily: HOME_MONO, fontSize: 11,
              color: isLive ? theme.muted : theme.dim, letterSpacing: '0.06em',
            }}>{role}</div>
            <div style={{
              fontFamily: HOME_MONO, fontSize: 11,
              color: theme.dim, letterSpacing: '0.10em',
            }}>{year}</div>
          </div>
        </div>

        {/* Thumbnail */}
        <div style={{
          width: 'clamp(180px, 18vw, 280px)',
          aspectRatio: '16/9',
          overflow: 'hidden',
          borderRadius: 8,
          flexShrink: 0,
          background: theme.rule,
          position: 'relative',
          opacity: isLive ? (hovered ? 1 : 0.75) : 0.28,
          transition: 'opacity 320ms cubic-bezier(.4,0,.2,1)',
        }}>
          {thumb && (
            <img
              src={thumb}
              alt={company}
              style={{
                position: 'absolute', inset: 0,
                width: '100%', height: '100%',
                objectFit: 'cover', objectPosition: 'center 30%',
                display: 'block',
                transition: 'opacity 400ms ease',
                opacity: (hovered && video) ? 0 : 1,
              }}
            />
          )}
          {video && (
            <video
              ref={videoRef}
              src={video}
              muted loop playsInline
              style={{
                position: 'absolute', inset: 0,
                width: '100%', height: '100%',
                objectFit: 'cover', objectPosition: '50% 15%',
                display: 'block',
                opacity: hovered ? 1 : 0,
                transition: 'opacity 400ms ease',
              }}
            />
          )}
        </div>

        {/* Action */}
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {isLive ? (
            <ViewCaseBtn hovered={hovered} />
          ) : (
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: CASE_BTN_W,
              fontFamily: HOME_MONO, fontSize: 9,
              letterSpacing: '0.22em', textTransform: 'uppercase',
              color: theme.dim,
              border: `1px solid ${theme.rule}`,
              borderRadius: 4,
              padding: '11px 0',
              boxSizing: 'border-box',
            }}>
              Soon
            </span>
          )}
        </div>
      </div>
    </a>
  );
}

// ── RoleRoulette ──────────────────────────────────────────────────────────────

function RoleRoulette() {
  const { theme } = React.useContext(ThemeCtx);
  const [idx, setIdx] = React.useState(0);
  const [key, setKey] = React.useState(0);

  React.useEffect(() => {
    const iv = setInterval(() => {
      setIdx(i => (i + 1) % ROULETTE_ROLES.length);
      setKey(k => k + 1);
    }, 2600);
    return () => clearInterval(iv);
  }, []);

  return (
    <div style={{ overflow: 'hidden', height: '42px', marginTop: 18 }}>
      <div key={key} style={{
        fontFamily: HOME_SANS, fontWeight: 300,
        fontSize: 'clamp(15px, 1.8vw, 24px)', lineHeight: '42px',
        letterSpacing: '-0.02em',
        color: theme.muted,
        animation: 'hub-roulette 480ms cubic-bezier(.22,.61,.36,1) both',
      }}>
        {ROULETTE_ROLES[idx]}
      </div>
    </div>
  );
}

// ── HomeHeader ────────────────────────────────────────────────────────────────

function HomeHeader() {
  const { theme } = React.useContext(ThemeCtx);
  const [ready, setReady] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setReady(true), 60);
    return () => clearTimeout(t);
  }, []);

  const anim = (delay, duration = 800) => ready ? {
    animation: `pp-fade-up ${duration}ms cubic-bezier(.16,1,.3,1) ${delay}ms both`,
  } : { opacity: 0 };

  return (
    <header style={{ paddingTop: 96, paddingBottom: 72 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{
            fontFamily: HOME_MONO, fontSize: 11,
            letterSpacing: '0.22em', textTransform: 'uppercase',
            color: theme.muted, marginBottom: 20,
            display: 'flex', alignItems: 'center', gap: 14,
            ...anim(0, 700),
          }}>
            <span style={{ width: 32, height: 1, background: 'currentColor', display: 'inline-block', opacity: 0.6 }} />
            <span>Portfolio Design • Case Hub</span>
          </div>

          <div style={{ overflow: 'hidden', lineHeight: 1 }}>
            <h1 style={{
              margin: 0,
              fontFamily: HOME_SANS, fontWeight: 500,
              fontSize: 'clamp(48px, 6.5vw, 88px)', letterSpacing: '-0.05em', lineHeight: 0.88,
              color: theme.fg,
              ...(ready ? {
                animation: 'hub-sunrise 900ms cubic-bezier(.16,1,.3,1) 80ms both',
              } : { transform: 'translateY(110%)' }),
            }}>
              Julio Ferracini
            </h1>
          </div>

          {ready && <RoleRoulette />}
        </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 24, paddingTop: 8, ...anim(200, 700) }}>
            <NavMenu currentPage="hub" />
            <ThemeToggle />
          </div>
      </div>
    </header>
  );
}

// ── RouletteLink ──────────────────────────────────────────────────────────────

function RouletteLink({ label, href, theme }) {
  const [hovered, setHovered] = React.useState(false);

  return (
    <a
      href={href}
      target={(href.startsWith('mailto:') || href.startsWith('/')) ? undefined : '_blank'}
      rel={(href.startsWith('mailto:') || href.startsWith('/')) ? undefined : 'noreferrer'}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: 'inline-block',
        fontFamily: HOME_MONO,
        fontSize: 12,
        letterSpacing: '0.08em',
        textDecoration: 'none',
        color: hovered ? theme.fg : theme.muted,
        transition: 'color 200ms ease',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <span style={{
        display: 'inline-block',
        transition: hovered
          ? 'transform 350ms cubic-bezier(0.25, 1, 0.5, 1)'
          : 'transform 500ms cubic-bezier(0.34, 1.56, 0.64, 1)',
        transform: hovered ? 'translateY(-120%)' : 'translateY(0)',
      }}>
        {label}
      </span>
      <span style={{
        position: 'absolute',
        top: '100%',
        left: 0,
        display: 'inline-block',
        color: theme.fg,
        transition: hovered
          ? 'transform 350ms cubic-bezier(0.25, 1, 0.5, 1)'
          : 'transform 500ms cubic-bezier(0.34, 1.56, 0.64, 1)',
        transform: hovered ? 'translateY(-100%)' : 'translateY(0)',
      }}>
        {label}
      </span>
    </a>
  );
}

// ── LogoMarquee ───────────────────────────────────────────────────────────────
// Definition lives in shared/logo-marquee.jsx (window.LogoMarquee)

function HomeLogoMarquee() {
  const { theme, mode } = React.useContext(ThemeCtx);
  return (
    <LogoMarquee
      theme={theme}
      mode={mode}
      label="Experience"
      moreHref="/about"
      moreLabel="more →"
      RouletteLink={RouletteLink}
      fontMono={HOME_MONO}
    />
  );
}

// ── HomeFooter ────────────────────────────────────────────────────────────────

function HomeFooter() {
  const { theme } = React.useContext(ThemeCtx);
  return <SiteFooter theme={theme} />;
}

// ── HomePage ──────────────────────────────────────────────────────────────────

function HomePage() {
  const themeCtx = useThemePref();
  const { theme } = themeCtx;
  const cursor = useCustomCursor();

  return (
    <ThemeCtx.Provider value={themeCtx}>
    <CursorCtx.Provider value={{ setActive: cursor.setActive, enabled: cursor.enabled }}>
      {cursor.enabled && (
        <div style={{
          position: 'fixed',
          left: cursor.pos.x, top: cursor.pos.y,
          transform: 'translate(-50%, -50%)',
          width: 64, height: 64,
          borderRadius: '50%',
          background: '#000',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          pointerEvents: 'none',
          zIndex: 9999,
          opacity: cursor.active ? 1 : 0,
          scale: cursor.active ? '1' : '0.6',
          transition: 'opacity 200ms ease, scale 200ms ease',
          animation: cursor.active ? 'cursor-spin 1.8s linear infinite' : 'none',
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
            <path d="M7 17L17 7M17 7H7M17 7V17"
              stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      )}
      <div style={{
        background: theme.bg,
        color: theme.fg,
        minHeight: '100vh',
        fontFamily: HOME_SANS,
        paddingLeft: 96, paddingRight: 96,
        transition: 'background 300ms ease, color 300ms ease',
      }}>
        <HomeHeader />
        <main>
          {CASES.map((c, i) => (
            <CaseCard key={c.id} {...c} index={i} />
          ))}
        </main>
        <HomeLogoMarquee />
        <HomeFooter />
      </div>
    </CursorCtx.Provider>
    </ThemeCtx.Provider>
  );
}

Object.assign(window, { HomePage });
