// Globals
const { useEffect, useState, useRef } = React;


// ===== components/placeholders.jsx =====
// Reusable SVG image placeholders — abstract "studio" imagery
// Different palette/composition per id so each tile reads as a distinct piece of work

const Placeholder = ({ id = 1, label = "image", className = "" }) => {
  const variants = [
  // 0 – warm dunes

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <defs>
          <linearGradient id={`g${id}a`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#2a2520" />
            <stop offset="50%" stopColor="#4a3a2a" />
            <stop offset="100%" stopColor="#7a5a3a" />
          </linearGradient>
        </defs>
        <rect width="800" height="600" fill={`url(#g${id}a)`} />
        <ellipse cx="400" cy="700" rx="600" ry="200" fill="#1a1410" opacity="0.7" />
        <ellipse cx="200" cy="650" rx="400" ry="160" fill="#0e0a08" opacity="0.6" />
        <circle cx="620" cy="160" r="48" fill="#f3d6a8" opacity="0.85" />
      </svg>,

  // 1 – architectural lines

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <rect width="800" height="600" fill="#0e1318" />
        <g stroke="#3b556d" strokeWidth="1.2" fill="none" opacity="0.7">
          {Array.from({ length: 24 }).map((_, i) =>
      <line key={i} x1="0" y1={i * 30} x2="800" y2={i * 30 - 200} />
      )}
          {Array.from({ length: 20 }).map((_, i) =>
      <line key={i} x1={i * 60} y1="0" x2={i * 60 + 200} y2="600" />
      )}
        </g>
        <rect x="80" y="120" width="280" height="380" fill="#1a2530" stroke="#4E85BF" strokeWidth="2" />
        <rect x="380" y="200" width="340" height="320" fill="#11181f" stroke="#89AACC" strokeWidth="2" />
      </svg>,

  // 2 – portrait silhouette

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <defs>
          <radialGradient id={`g${id}c`} cx="50%" cy="40%" r="60%">
            <stop offset="0%" stopColor="#4a3328" />
            <stop offset="60%" stopColor="#1f1612" />
            <stop offset="100%" stopColor="#0a0807" />
          </radialGradient>
        </defs>
        <rect width="800" height="600" fill={`url(#g${id}c)`} />
        <ellipse cx="400" cy="240" rx="120" ry="150" fill="#0a0807" />
        <path d="M 250 600 Q 250 380 400 380 Q 550 380 550 600 Z" fill="#0a0807" />
      </svg>,

  // 3 – brand mark

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <rect width="800" height="600" fill="#f3efe7" />
        <rect width="800" height="600" fill="#dcd4c4" opacity="0.4" />
        <g transform="translate(400 300)">
          <circle r="160" fill="none" stroke="#1a1a1a" strokeWidth="3" />
          <text textAnchor="middle" dominantBaseline="central" fill="#1a1a1a"
      fontFamily="Instrument Serif, serif" fontStyle="italic" fontSize="220">M</text>
        </g>
      </svg>,

  // 4 – chrome curves

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <defs>
          <linearGradient id={`g${id}e`} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#1a1d22" />
            <stop offset="40%" stopColor="#5a6470" />
            <stop offset="70%" stopColor="#252830" />
            <stop offset="100%" stopColor="#0a0c10" />
          </linearGradient>
        </defs>
        <rect width="800" height="600" fill={`url(#g${id}e)`} />
        <path d="M 0 400 Q 200 200 400 350 T 800 320 L 800 600 L 0 600 Z" fill="#0a0c10" opacity="0.7" />
        <ellipse cx="500" cy="180" rx="220" ry="40" fill="#bcc6d2" opacity="0.5" />
      </svg>,

  // 5 – grid product

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <rect width="800" height="600" fill="#161514" />
        <g stroke="#2a2826" strokeWidth="1">
          {Array.from({ length: 16 }).map((_, i) =>
      <line key={`v${i}`} x1={i * 50} y1="0" x2={i * 50} y2="600" />
      )}
          {Array.from({ length: 12 }).map((_, i) =>
      <line key={`h${i}`} x1="0" y1={i * 50} x2="800" y2={i * 50} />
      )}
        </g>
        <rect x="280" y="180" width="240" height="240" fill="#e8e2d3" rx="8" />
        <rect x="300" y="200" width="200" height="200" fill="#bcb09a" rx="4" />
      </svg>,

  // 6 – cool wash

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <defs>
          <linearGradient id={`g${id}g`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#0e1a26" />
            <stop offset="100%" stopColor="#1d3a52" />
          </linearGradient>
        </defs>
        <rect width="800" height="600" fill={`url(#g${id}g)`} />
        <circle cx="600" cy="200" r="180" fill="#89AACC" opacity="0.15" />
        <circle cx="200" cy="450" r="140" fill="#4E85BF" opacity="0.2" />
      </svg>,

  // 7 – type spec

  <svg viewBox="0 0 800 600" preserveAspectRatio="xMidYMid slice" className="w-full h-full">
        <rect width="800" height="600" fill="#0a0a0a" />
        <text x="60" y="340" fill="#f3efe7" fontFamily="Instrument Serif, serif"
    fontStyle="italic" fontSize="320" letterSpacing="-12">Aa</text>
        <text x="62" y="420" fill="#7a7a7a" fontFamily="Inter, sans-serif"
    fontSize="14" letterSpacing="6">TYPOGRAPHIC STUDY · 01</text>
      </svg>];


  const idx = (id % variants.length + variants.length) % variants.length;
  return (
    <div className={`relative overflow-hidden ${className}`}>
      {variants[idx]}
      {/* Halftone overlay */}
      <div className="absolute inset-0 halftone opacity-20 mix-blend-multiply pointer-events-none" />
    </div>);

};

window.Placeholder = Placeholder;


// ===== components/loading.jsx =====
const LoadingScreen = ({ onComplete }) => {
  const [count, setCount] = useState(0);
  const [wordIdx, setWordIdx] = useState(0);
  const [exiting, setExiting] = useState(false);
  const words = ["Design", "Create", "Inspire"];

  useEffect(() => {
    const start = performance.now();
    const duration = 2700;
    let raf;
    const tick = (t) => {
      const elapsed = t - start;
      const pct = Math.min(100, Math.floor(elapsed / duration * 100));
      setCount(pct);
      if (pct < 100) {
        raf = requestAnimationFrame(tick);
      } else {
        setTimeout(() => {
          setExiting(true);
          setTimeout(() => onComplete && onComplete(), 500);
        }, 400);
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [onComplete]);

  useEffect(() => {
    const iv = setInterval(() => setWordIdx((i) => (i + 1) % words.length), 900);
    return () => clearInterval(iv);
  }, []);

  return (
    <div
      className="fixed inset-0 z-[9999] bg-bg transition-opacity duration-500"
      style={{ opacity: exiting ? 0 : 1, pointerEvents: exiting ? 'none' : 'auto' }}>
      
      {/* Top-left label */}
      <div
        className="absolute top-6 left-6 md:top-10 md:left-10 text-xs text-muted uppercase tracking-[0.3em]"
        style={{ animation: 'blur-in 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) 0.2s both' }}>
        
        Portfolio
      </div>
      <div
        className="absolute top-6 right-6 md:top-10 md:right-10 text-xs text-muted uppercase tracking-[0.3em]"
        style={{ animation: 'blur-in 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) 0.3s both' }}>
        
        '26 — Loading
      </div>

      {/* Center: rotating words */}
      <div className="absolute inset-0 flex items-center justify-center">
        <div className="relative h-[1.2em] overflow-hidden text-4xl md:text-6xl lg:text-7xl font-display italic text-text-primary/80">
          <div key={wordIdx} style={{ animation: 'word-in 0.5s cubic-bezier(0.25, 0.1, 0.25, 1)' }}>
            {words[wordIdx]}
          </div>
        </div>
      </div>

      {/* Bottom-right counter */}
      <div className="absolute bottom-12 right-6 md:bottom-16 md:right-10 text-6xl md:text-8xl lg:text-9xl font-display text-text-primary tabular-nums leading-none">
        {String(count).padStart(3, "0")}
      </div>

      {/* Bottom-left mini meta */}
      <div className="absolute bottom-12 left-6 md:bottom-16 md:left-10 text-xs text-muted uppercase tracking-[0.3em] max-w-[200px]">
        Initialising visual<br />system & assets
      </div>

      {/* Progress bar */}
      <div className="absolute bottom-0 left-0 right-0 h-[3px] bg-stroke/50">
        <div
          className="h-full accent-gradient origin-left"
          style={{
            transform: `scaleX(${count / 100})`,
            transition: 'transform 0.1s linear',
            boxShadow: '0 0 8px rgba(137, 170, 204, 0.35)'
          }} />
        
      </div>
    </div>);

};

window.LoadingScreen = LoadingScreen;


// ===== components/navbar.jsx =====
const Navbar = ({ active = "Home", onNav }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 100);
    fn();
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);

  // Lock body scroll while mobile menu is open
  React.useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  const links = ["Home", "Áreas de Atuação"];

  const handleNav = (label) => {
    setMenuOpen(false);
    onNav && onNav(label);
  };

  return (
    <React.Fragment>
    <nav
      className={`fixed top-0 left-0 right-0 z-50 flex items-start md:items-center justify-between px-6 md:px-10 lg:px-16 py-4 md:py-6 transition-all duration-300 ${
        scrolled || menuOpen ? 'backdrop-blur-md bg-bg/70' : ''
      }`}
    >
      {/* Logo + wordmark — stacked on mobile, inline on md+ */}
      <a
        href="#home"
        onClick={(e) => { e.preventDefault(); handleNav('Home'); }}
        className="inline-flex flex-col md:flex-row md:items-center items-start gap-2 md:gap-0 transition-transform duration-300 hover:scale-105"
        aria-label="Home"
      >
        <img src="assets/logo.svg" alt="Logo" width="81" height="37" style={{ display: 'block' }}/>
        <span
          className="md:ml-[10px]"
          style={{
            fontFamily: "'IBM Plex Sans', sans-serif",
            fontStyle: 'italic',
            fontWeight: 400,
            color: '#917F2F',
            whiteSpace: 'nowrap',
            fontSize: '17px',
            letterSpacing: '0.01em',
          }}
        >
          Flavio Cardoso e Advogados
        </span>
      </a>

      {/* Desktop links — hidden on mobile */}
      <div className="hidden md:flex items-center gap-1 sm:gap-2">
        {links.map((l) => (
          <a
            key={l}
            href={`#${l.toLowerCase()}`}
            onClick={(e) => { e.preventDefault(); handleNav(l); }}
            className={`text-xs sm:text-sm px-3 sm:px-4 py-2 rounded-full transition-colors ${
              active === l
                ? 'text-text-primary'
                : 'text-muted hover:text-text-primary'
            }`}
          >
            {l}
          </a>
        ))}

        <a
          href="https://wa.me/message/YHHYJC34GJ3CB1"
          target="_blank"
          rel="noopener noreferrer"
          className="group relative inline-flex items-center gap-2 rounded-full text-xs sm:text-sm px-5 sm:px-6 py-2 sm:py-2.5 bg-brand text-white hover:bg-bg hover:text-brand transition-colors gradient-ring hover:scale-105 duration-300 ml-1 sm:ml-2"
        >
          <span className="relative z-10">Fale Conosco</span>
          <span className="relative z-10">→</span>
        </a>
      </div>

      {/* Hamburger — mobile only */}
      <button
        type="button"
        onClick={() => setMenuOpen((v) => !v)}
        aria-label={menuOpen ? "Close menu" : "Open menu"}
        aria-expanded={menuOpen}
        className="md:hidden relative z-[60] inline-flex items-center justify-center w-10 h-10 mt-1 rounded-full text-text-primary"
      >
        <span className="relative block w-6 h-4">
          <span
            className="absolute left-0 right-0 h-[2px] bg-text-primary rounded-full transition-all duration-300"
            style={{ top: menuOpen ? '50%' : '0', transform: menuOpen ? 'translateY(-50%) rotate(45deg)' : 'none' }}
          />
          <span
            className="absolute left-0 right-0 h-[2px] bg-text-primary rounded-full transition-opacity duration-200"
            style={{ top: '50%', transform: 'translateY(-50%)', opacity: menuOpen ? 0 : 1 }}
          />
          <span
            className="absolute left-0 right-0 h-[2px] bg-text-primary rounded-full transition-all duration-300"
            style={{ top: menuOpen ? '50%' : '100%', transform: menuOpen ? 'translateY(-50%) rotate(-45deg)' : 'translateY(-100%)' }}
          />
        </span>
      </button>
    </nav>

      {/* Mobile menu overlay — outside <nav> so `fixed` is relative to the
          viewport (nav's backdrop-filter would otherwise contain it) */}
      <div
        className={`md:hidden fixed inset-0 z-[55] bg-bg flex flex-col items-center justify-center gap-6 transition-opacity duration-300 ${
          menuOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
        }`}
      >
        {links.map((l) => (
          <a
            key={l}
            href={`#${l.toLowerCase()}`}
            onClick={(e) => { e.preventDefault(); handleNav(l); }}
            className={`text-2xl font-display italic transition-colors ${
              active === l ? 'text-text-primary' : 'text-muted hover:text-text-primary'
            }`}
          >
            {l}
          </a>
        ))}
        <a
          href="https://wa.me/message/YHHYJC34GJ3CB1"
          target="_blank"
          rel="noopener noreferrer"
          className="group relative inline-flex items-center gap-2 rounded-full text-base px-7 py-3 bg-brand text-white gradient-ring mt-4"
        >
          <span className="relative z-10">Fale Conosco</span>
          <span className="relative z-10">→</span>
        </a>
      </div>
    </React.Fragment>
  );
};

window.Navbar = Navbar;


// ===== components/hero.jsx =====
const Hero = () => {
  const sectionRef = useRef(null);
  const glowRef = useRef(null);

  // Mouse-follow glow
  useEffect(() => {
    const sec = sectionRef.current;
    const glow = glowRef.current;
    if (!sec || !glow) return;
    let raf,tx = 0,ty = 0,x = 0,y = 0;
    // Start centered
    const init = () => {
      const r = sec.getBoundingClientRect();
      tx = x = r.width / 2;
      ty = y = r.height / 2;
      glow.style.transform = `translate3d(${x - 400}px, ${y - 400}px, 0)`;
    };
    init();
    const onMove = (e) => {
      const r = sec.getBoundingClientRect();
      tx = e.clientX - r.left;
      ty = e.clientY - r.top;
    };
    const tick = () => {
      x += (tx - x) * 0.08;
      y += (ty - y) * 0.08;
      glow.style.transform = `translate3d(${x - 400}px, ${y - 400}px, 0)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    sec.addEventListener('mousemove', onMove);
    window.addEventListener('resize', init);
    return () => {
      cancelAnimationFrame(raf);
      sec.removeEventListener('mousemove', onMove);
      window.removeEventListener('resize', init);
    };
  }, []);

  const roles = ["empresarial", "societário", "tributário", "civilista"];
  const [roleIdx, setRoleIdx] = useState(0);
  useEffect(() => {
    const iv = setInterval(() => setRoleIdx((i) => (i + 1) % roles.length), 2000);
    return () => clearInterval(iv);
  }, []);

  // Geometric shapes — thin ghost-line work
  const shapes = [
  // Big outlined circle, upper-left
  { kind: 'circle', top: '8%', left: '6%', size: 380, rot: 0, depth: 0.02, stroke: 'hsl(var(--text) / 0.10)' },
  // Diagonal line slicing across
  { kind: 'line', top: '0%', left: '-5%', w: 700, h: 700, rot: 30, depth: 0.015, stroke: 'hsl(var(--text) / 0.08)' },
  // Another diagonal, lower-right
  { kind: 'line', top: '30%', left: '40%', w: 1100, h: 4, rot: -8, depth: 0.012, stroke: 'hsl(var(--text) / 0.06)' },
  // Tiny periwinkle accent dot
  { kind: 'dot', top: '14%', left: '74%', size: 8, rot: 0, depth: 0.06, fill: '#7D9BDC' },
  // Faint smaller circle, mid-right
  { kind: 'circle', top: '55%', left: '82%', size: 120, rot: 0, depth: 0.025, stroke: 'hsl(var(--text) / 0.08)' }];


  // Parallax for shapes
  const shapesRef = useRef(null);
  useEffect(() => {
    const sec = sectionRef.current;
    const wrap = shapesRef.current;
    if (!sec || !wrap) return;
    let raf;
    let mx = 0,my = 0,cx = 0,cy = 0;
    const onMove = (e) => {
      const r = sec.getBoundingClientRect();
      mx = (e.clientX - r.left) / r.width - 0.5;
      my = (e.clientY - r.top) / r.height - 0.5;
    };
    const tick = () => {
      cx += (mx - cx) * 0.06;
      cy += (my - cy) * 0.06;
      const kids = wrap.children;
      for (let i = 0; i < kids.length; i++) {
        const d = parseFloat(kids[i].dataset.depth || '0.04');
        kids[i].style.transform = `translate3d(${-cx * 80 * (d * 25)}px, ${-cy * 80 * (d * 25)}px, 0) rotate(${kids[i].dataset.rot}deg)`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    sec.addEventListener('mousemove', onMove);
    return () => {
      cancelAnimationFrame(raf);
      sec.removeEventListener('mousemove', onMove);
    };
  }, []);

  const renderShape = (s, i) => {
    if (s.kind === 'line') {
      return (
        <div
          key={i}
          data-depth={s.depth}
          data-rot={s.rot}
          className="absolute pointer-events-none will-change-transform"
          style={{ top: s.top, left: s.left, width: s.w, height: s.h || 1, transform: `rotate(${s.rot}deg)`, transformOrigin: '0 0' }}>
          
          <div style={{ width: '100%', height: 1, background: s.stroke }} />
        </div>);

    }
    if (s.kind === 'dot') {
      return (
        <div
          key={i}
          data-depth={s.depth}
          data-rot={s.rot || 0}
          className="absolute pointer-events-none will-change-transform rounded-full"
          style={{
            top: s.top, left: s.left, width: s.size, height: s.size,
            background: s.fill,
            boxShadow: `0 0 16px ${s.fill}55`
          }} />);


    }
    // circle (outlined)
    return (
      <div
        key={i}
        data-depth={s.depth}
        data-rot={s.rot || 0}
        className="absolute pointer-events-none will-change-transform rounded-full"
        style={{
          top: s.top, left: s.left, width: s.size, height: s.size,
          border: `1px solid ${s.stroke}`
        }} />);


  };

  return (
    <section
      ref={sectionRef}
      id="home"
      className="relative h-screen min-h-[640px] w-full overflow-hidden flex items-center bg-bg">
      
      {/* Background color glows — soft periwinkle blob follows the mouse,
          with two complementary static blobs (lavender + teal) */}
      <div className="absolute inset-0 overflow-hidden">
        {/* Static lavender blob — top right */}
        <div
          className="absolute pointer-events-none"
          style={{
            top: '-10%',
            right: '-8%',
            width: 720,
            height: 720,
            background: 'radial-gradient(circle, rgba(200,180,235,0.34) 0%, rgba(210,195,240,0.18) 30%, rgba(225,215,245,0.08) 55%, rgba(235,225,250,0) 75%)',
            filter: 'blur(32px)'
          }} />

        {/* Static soft teal blob — bottom left */}
        <div
          className="absolute pointer-events-none"
          style={{
            bottom: '-15%',
            left: '-10%',
            width: 760,
            height: 760,
            background: 'radial-gradient(circle, rgba(160,210,225,0.32) 0%, rgba(180,220,232,0.16) 30%, rgba(205,230,238,0.08) 55%, rgba(220,238,243,0) 75%)',
            filter: 'blur(32px)'
          }} />

        {/* Mouse-follow periwinkle blob */}
        <div
          ref={glowRef}
          className="absolute pointer-events-none"
          style={{
            width: 800,
            height: 800,
            background: 'radial-gradient(circle, rgba(175,195,235,0.42) 0%, rgba(195,210,240,0.22) 28%, rgba(215,225,245,0.10) 50%, rgba(225,235,250,0) 72%)',
            filter: 'blur(28px)'
          }} />
        
      </div>

      {/* Geometric shapes */}
      <div ref={shapesRef} className="absolute inset-0 pointer-events-none">
        {shapes.map(renderShape)}
      </div>

      {/* Bottom fade into page */}
      <div className="absolute bottom-0 left-0 right-0 h-48 bg-gradient-to-t from-bg to-transparent" />

      {/* Content */}
      <div className="relative z-10 w-full max-w-[1200px] mx-auto px-6 md:px-10 lg:px-16">
        <div className="max-w-3xl">
          <h1 className="text-[53px] md:text-[79px] lg:text-[106px] font-display italic leading-[0.9] tracking-tight text-text-primary mb-6 name-reveal" style={{ maxWidth: "850px" }}>Flavio<br className="md:hidden"/> Cardoso

          </h1>

          <p className="text-lg md:text-2xl text-text-primary/85 mb-4 blur-in" style={{ animationDelay: '0.5s' }}>
            Advogado{" "}
            <span
              key={roleIdx}
              className="font-display italic text-text-primary inline-block animate-role-fade-in">
              {roles[roleIdx]}
            </span><span className="text-muted">.</span>
          </p>

          <p className="text-sm md:text-base text-muted mb-8 blur-in" style={{ animationDelay: '0.7s', maxWidth: '620px', textWrap: 'balance' }}>
            Consultoria integrada e suporte jurídico para negócios e empreendedores Middle.
            <br/>
            Seu jurídico consultivo e contencioso com leitura de negócios e soluções eficientes.
          </p>

          <div className="inline-flex flex-wrap gap-4 blur-in" style={{ animationDelay: '0.9s' }}>
            <a
              href="#work"
              className="group relative inline-flex items-center gap-2 rounded-full text-sm px-7 py-3.5 border-2 border-stroke bg-bg text-text-primary hover:border-transparent transition-all gradient-ring hover:scale-105 duration-300">
              
              <span className="relative z-10">Ver Conteúdos</span>
              <span className="relative z-10">→</span>
            </a>
          </div>
        </div>
      </div>

      {/* Scroll indicator */}
      <div className="absolute bottom-8 left-1/2 -translate-x-1/2 flex flex-col items-center gap-3 z-10">
        <span className="text-xs text-muted uppercase tracking-[0.2em]">Scroll</span>
        <div className="relative w-px h-10 bg-stroke overflow-hidden">
          <div className="absolute left-0 right-0 h-4 accent-gradient animate-scroll-down" />
        </div>
      </div>
    </section>);

};

window.Hero = Hero;


// ===== components/section-header.jsx =====
const useInView = (ref, opts = {}) => {
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setInView(true);
        obs.disconnect();
      }
    }, { threshold: 0.1, rootMargin: '-100px', ...opts });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return inView;
};

const SectionHeader = ({ eyebrow, title, italic, subtext, cta }) => {
  const ref = React.useRef(null);
  const inView = useInView(ref);
  return (
    <div ref={ref} className={`fade-up ${inView ? 'in-view' : ''} flex flex-col md:flex-row md:items-end justify-between gap-6 mb-12 md:mb-16`}>
      <div className="max-w-2xl">
        <div className="flex items-center gap-3 mb-6">
          <span className="w-8 h-px bg-stroke" />
          <span className="text-xs text-muted uppercase tracking-[0.3em]">{eyebrow}</span>
        </div>
        <h2 className="text-5xl md:text-6xl lg:text-7xl font-display tracking-tight leading-[0.95] text-text-primary mb-4">
          {title}{" "}<em className="font-display italic">{italic}</em>
        </h2>
        {subtext && <p className="text-sm md:text-base text-muted max-w-md">{subtext}</p>}
      </div>
      {cta &&
      <a
        href="#"
        className="hidden md:inline-flex items-center gap-2 rounded-full text-sm px-5 py-2.5 border border-stroke text-text-primary gradient-ring transition-all hover:scale-105 self-start md:self-end">
        
          <span className="relative">{cta}</span>
          <span className="relative opacity-70">→</span>
        </a>
      }
    </div>);

};

window.useInView = useInView;
window.SectionHeader = SectionHeader;


// ===== components/works.jsx =====
const WorkCard = ({ title, kind, span, aspect, phId }) => {
  const ref = React.useRef(null);
  const inView = window.useInView(ref);
  return (
    <a
      ref={ref}
      href="#"
      className={`group relative ${span} ${aspect} bg-surface border border-stroke rounded-3xl overflow-hidden block fade-up ${inView ? 'in-view' : ''}`}>
      
      <div className="absolute inset-0 transition-transform duration-700 group-hover:scale-105">
        <window.Placeholder id={phId} className="absolute inset-0" />
      </div>

      {/* Meta in corner */}
      <div className="absolute top-5 left-5 z-10 flex items-center gap-2 text-xs text-white/85 uppercase tracking-[0.2em] mix-blend-difference">
        <span className="w-1.5 h-1.5 rounded-full bg-white/80" />
        {kind}
      </div>
      <div className="absolute top-5 right-5 z-10 text-xs text-white/85 uppercase tracking-[0.2em] mix-blend-difference">
        '26
      </div>

      {/* Hover veil */}
      <div className="absolute inset-0 bg-bg/70 opacity-0 group-hover:opacity-100 backdrop-blur-lg transition-opacity duration-500 flex items-center justify-center">
        <div className="relative inline-flex items-center gap-2 rounded-full bg-brand text-white px-5 py-2.5 text-sm gradient-ring gradient-ring-always">
          <span className="relative">View — <em className="font-display italic">{title}</em></span>
        </div>
      </div>

      {/* Bottom label (always visible, fades on hover) */}
      <div className="absolute bottom-5 left-5 right-5 z-10 flex items-end justify-between group-hover:opacity-0 transition-opacity duration-300">
        <h3 className="text-2xl md:text-3xl font-display italic text-white leading-none mix-blend-difference">
          {title}
        </h3>
        <span className="text-xs text-white/80 uppercase tracking-[0.2em] mix-blend-difference">↗</span>
      </div>
    </a>);

};

const Works = () => {
  const projects = [
  { title: "Automotive Motion", kind: "Motion", span: "md:col-span-7", aspect: "aspect-[7/5]", phId: 4 },
  { title: "Urban Architecture", kind: "Architectural", span: "md:col-span-5", aspect: "aspect-[5/5] md:aspect-[7/5]", phId: 1 },
  { title: "Human Perspective", kind: "Portrait", span: "md:col-span-5", aspect: "aspect-[5/5] md:aspect-[7/5]", phId: 2 },
  { title: "Brand Identity", kind: "Identity", span: "md:col-span-7", aspect: "aspect-[7/5]", phId: 3 }];


  return (
    <section id="work" className="bg-bg py-20 md:py-28">
      <div className="max-w-[1200px] mx-auto px-6 md:px-10 lg:px-16">
        <window.SectionHeader
          eyebrow="Selected Work"
          title="Featured"
          italic="projects"
          subtext="A selection of projects I've worked on, from concept to launch."
          cta="View all work" />
        

        <div className="grid grid-cols-1 md:grid-cols-12 gap-5 md:gap-6">
          {projects.map((p, i) => <WorkCard key={i} {...p} />)}
        </div>
      </div>
    </section>);

};

window.Works = Works;


// ===== components/services.jsx =====
const ServiceCard = ({ phId, image, tags, title, italic, desc, footer }) => {
  const ref = React.useRef(null);
  const inView = window.useInView(ref);
  return (
    <article
      ref={ref}
      className={`fade-up ${inView ? 'in-view' : ''} group flex flex-col border border-stroke rounded-3xl overflow-hidden p-3 transition-transform duration-300 hover:scale-[1.03] hover:border-brand/30`}
      style={{ background: '#FEFEFE' }}
    >
      {/* Top image */}
      <div className="relative aspect-[4/3] rounded-2xl overflow-hidden bg-bg">
        {image
          ? <img src={image} alt={italic} className="absolute inset-0 w-full h-full object-cover"/>
          : <window.Placeholder id={phId}/>}
      </div>

      {/* Content */}
      <div className="px-4 md:px-5 pt-6 pb-5 flex-1 flex flex-col">
        {/* Category line with vertical accent bar */}
        <div className="flex items-start gap-2.5 mb-5">
          <span className="block w-px h-3.5 mt-0.5 bg-text-primary"/>
          <span className="text-[11px] text-text-primary uppercase tracking-[0.2em] leading-relaxed">
            {tags}
          </span>
        </div>

        {/* Heading */}
        <h3 className="text-2xl md:text-[1.7rem] font-display text-text-primary leading-[1.2] tracking-tight mb-3">
          {title}{title && " "}<em className="font-display italic">{italic}</em>
        </h3>

        {/* Description */}
        <p className="text-sm md:text-[15px] text-muted leading-relaxed mb-6">
          {desc}
        </p>

        {/* Footer */}
        <div className="mt-auto pt-4 text-xs text-muted/70">
          {footer}
        </div>
      </div>
    </article>
  );
};

const Services = () => {
  const items = [
    {
      phId: 7,
      image: "assets/card-1-v2.png",
      tags: "Planejamento · Defesa · Recuperação",
      title: "",
      italic: "Tributário",
      desc: "Planejamento fiscal, defesa em execuções e autuações, recuperação de créditos e estratégias para reduzir a carga tributária.",
      footer: "01",
    },
    {
      phId: 1,
      image: "assets/card-2.png",
      tags: "Contratos · Família · Sucessões",
      title: "Direito",
      italic: "civil",
      desc: "Atuação em contratos, responsabilidade civil, sucessões, família e demandas patrimoniais — sempre protegendo os interesses do cliente.",
      footer: "02",
    },
    {
      phId: 3,
      image: "assets/card-3.png",
      tags: "Societário · Contratos · Governança",
      title: "Direito",
      italic: "empresarial",
      desc: "Constituição e reestruturação societária, contratos comerciais, governança e prevenção de litígios para empresas de todos os portes.",
      footer: "03",
    },
    {
      phId: 6,
      image: "assets/card-4-v2.png",
      tags: "Crédito · Garantias · Estruturação",
      title: "Contratos",
      italic: "financeiros e bancários",
      desc: "Estruturação, revisão e negociação de contratos financeiros e bancários, garantias e instrumentos de crédito para empresas e investidores.",
      footer: "04",
    },
    {
      phId: 5,
      image: "assets/card-5.png",
      tags: "Pareceres · Suporte · Estratégia",
      title: "Consultoria",
      italic: "estratégica",
      desc: "Acompanhamento jurídico contínuo, pareceres técnicos e suporte preventivo para decisões de negócio com visão de longo prazo.",
      footer: "05",
    },
  ];

  return (
    <section id="services" className="bg-bg py-20 md:py-28 border-t border-stroke">
      <div className="max-w-[1200px] mx-auto px-6 md:px-10 lg:px-16">
        <window.SectionHeader
          eyebrow="Serviços"
          title="Áreas de"
          italic="atuação"
          subtext="Soluções jurídicas sob medida, com clareza, técnica e proximidade — em cada etapa do processo."
        />

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 md:gap-6">
          {items.map((it, i) => (
            <ServiceCard key={i} {...it}/>
          ))}
        </div>
      </div>
    </section>
  );
};

window.Services = Services;


// ===== components/journal.jsx =====
const JournalRow = ({ title, readTime, date, phId }) => {
  const ref = React.useRef(null);
  const inView = window.useInView(ref);
  return (
    <a
      ref={ref}
      href="#"
      className={`group flex items-center gap-5 md:gap-6 p-4 bg-surface/40 hover:bg-surface border border-stroke rounded-[40px] sm:rounded-full transition-all hover:scale-[1.01] fade-up ${inView ? 'in-view' : ''}`}>
      
      <div className="shrink-0 w-20 h-20 md:w-24 md:h-24 rounded-full overflow-hidden">
        <window.Placeholder id={phId} />
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-1 text-xs text-muted uppercase tracking-[0.25em]">
          <span>{date}</span>
          <span className="w-1 h-1 rounded-full bg-stroke" />
          <span>{readTime}</span>
        </div>
        <h3 className="text-xl md:text-2xl font-display italic text-text-primary truncate">{title}</h3>
      </div>
      <div className="shrink-0 pr-3 md:pr-5 text-text-primary/60 group-hover:text-text-primary group-hover:translate-x-1 transition-all">
        ↗
      </div>
    </a>);

};

const Journal = () => {
  const entries = [
  { title: "On the patience of building visual systems", date: "Mar 12", readTime: "6 min read", phId: 6 },
  { title: "Notes from a slow studio in March", date: "Feb 28", readTime: "4 min read", phId: 7 },
  { title: "Designing the in-between, ambient interaction", date: "Feb 04", readTime: "8 min read", phId: 5 },
  { title: "Why I keep a paper notebook on the desk", date: "Jan 18", readTime: "3 min read", phId: 0 }];


  return (
    <section id="journal" className="bg-bg py-16 md:py-24">
      <div className="max-w-[1200px] mx-auto px-6 md:px-10 lg:px-16">
        <window.SectionHeader
          eyebrow="Journal"
          title="Recent"
          italic="thoughts"
          subtext="Slow writing on craft, systems, and what I'm noticing in the studio."
          cta="View all writing" />
        
        <div className="flex flex-col gap-3 md:gap-4">
          {entries.map((e, i) => <JournalRow key={i} {...e} />)}
        </div>
      </div>
    </section>);

};

window.Journal = Journal;


// ===== components/about.jsx =====
const About = () => {
  const ref = React.useRef(null);
  const inView = window.useInView(ref);
  return (
    <section id="about" className="relative bg-bg py-24 md:py-32">
      <div ref={ref} className={`max-w-[1200px] mx-auto px-6 md:px-10 lg:px-16 fade-up ${inView ? 'in-view' : ''}`}>
        <div className="grid grid-cols-1 md:grid-cols-12 gap-10 md:gap-14 items-stretch">

          {/* Left column — content */}
          <div className="md:col-span-7 flex flex-col justify-center">
            {/* Eyebrow */}
            <div className="flex items-center gap-3 mb-8">
              <span className="w-8 h-px bg-stroke"/>
              <span className="text-xs text-muted uppercase tracking-[0.3em]">Sobre</span>
            </div>

            {/* Heading */}
            <h2 className="text-5xl md:text-6xl lg:text-7xl font-display tracking-tight leading-[0.95] text-text-primary mb-8 md:mb-10">
              Sobre <em className="font-display italic">mim</em>
            </h2>

            {/* Body */}
            <div className="text-base md:text-lg text-text-primary/85 leading-relaxed space-y-5">
              <p>
                Há mais de 12 anos trabalhando dentro de estruturas jurídicas de Grandes Empresas e Escritórios, em ambientes onde o erro jurídico tem custo alto e a tolerância para processos lentos e estruturação de negócios de forma ineficiente é zero.
              </p>
              <p className="text-muted">
                Foi nesse cenário que desenvolvi uma forma diferente de trabalhar com Direito, unindo leitura de negócios e metodologias ao serviço jurídico qualificado, prestando um serviço orientado por dados e processos para resultados eficientes.
              </p>
              <p className="text-muted">
                Ofereço um jurídico com inteligência, usando metodologias ágeis para resultados eficazes, soluções de Grandes Empresas que também cabem em Empresas de Pequeno e Médio Porte, familiares e Holdings de negócios e patrimoniais que estão crescendo e precisam que sua estrutura jurídica cresça junto.
              </p>
            </div>

          </div>

          {/* Right column — portrait */}
          <div className="md:col-span-5">
            <div className="relative w-full h-full min-h-[420px] rounded-3xl overflow-hidden border border-stroke">
              <img
                src="assets/portrait.jpeg"
                alt="Flavio Cardoso"
                className="absolute inset-0 w-full h-full object-cover"
                loading="lazy"
              />
            </div>
          </div>

        </div>
      </div>
    </section>
  );
};

window.About = About;


// ===== components/stats.jsx =====
const Stats = () => {
  const items = [
  { num: "+12", label: "de experiência" },
  { num: "+50", label: "Projetos societários e governança" },
  { num: "+3,7M", label: "Tributos recuperados" }];

  return (
    <section className="bg-bg py-16 md:py-24 border-t border-stroke">
      <div className="max-w-[1200px] mx-auto px-6 md:px-10 lg:px-16">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-10 md:gap-6">
          {items.map((s, i) => {
            const ref = React.useRef(null);
            const inView = window.useInView(ref);
            return (
              <div
                key={i}
                ref={ref}
                className={`fade-up ${inView ? 'in-view' : ''} relative`}
                style={{ animationDelay: `${i * 0.1}s` }}>
                
                <div className="text-7xl md:text-8xl lg:text-9xl font-display italic text-text-primary leading-none tracking-tight">
                  {s.num}
                </div>
                <div className="mt-3 text-xs text-muted uppercase tracking-[0.3em]">
                  {s.label}
                </div>
                {i < items.length - 1 &&
                <div className="hidden md:block absolute top-1/2 -right-3 w-px h-16 -translate-y-1/2 bg-stroke" />
                }
              </div>);

          })}
        </div>
      </div>
    </section>);

};

window.Stats = Stats;


// ===== components/footer.jsx =====
const Contact = () => {
  const social = [
  { label: "LinkedIn", href: "https://www.linkedin.com/in/cardosoflavio" },
  { label: "Instagram", href: "https://www.instagram.com/adv.flaviocardoso/" }];


  return (
    <section id="contact" className="relative bg-bg pt-16 md:pt-20 pb-8 md:pb-12 overflow-hidden border-t border-stroke">
      {/* Subtle minimal gradient background */}
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          background:
            'radial-gradient(ellipse 80% 60% at 50% 100%, rgba(125,155,220,0.18) 0%, rgba(175,195,235,0.08) 40%, rgba(175,195,235,0) 75%)',
        }}
      />
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          background: 'linear-gradient(to bottom, hsl(var(--bg)) 0%, transparent 30%, transparent 70%, hsl(var(--bg)) 100%)',
        }}
      />

      <div className="relative z-10 max-w-[1400px] mx-auto px-6 md:px-10 lg:px-16">
        {/* CTA */}
        <div className="text-center mb-20 md:mb-24">
          <p className="text-sm text-muted uppercase tracking-[0.3em] mb-6">Precisando de ajuda?</p>
          <a
            href="https://wa.me/message/YHHYJC34GJ3CB1"
            target="_blank"
            rel="noopener noreferrer"
            className="group relative inline-flex items-center gap-3 rounded-full text-base md:text-lg px-8 py-4 bg-brand text-white gradient-ring hover:scale-105 transition-all duration-300">
            
            <span className="relative">Entre em contato</span>
            <span className="relative">↗</span>
          </a>
        </div>

        {/* Footer bar */}
        <div className="pt-8 border-t border-stroke flex flex-col gap-4">
          {/* Desktop: 3-col grid */}
          <div className="hidden md:grid md:grid-cols-3 md:items-center gap-4">
            <div className="flex items-center gap-5 text-sm text-muted">
              {social.map((s) =>
              <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" className="hover:text-text-primary transition-colors">
                  {s.label}
                </a>
              )}
            </div>
            <div className="text-xs text-muted uppercase tracking-[0.25em] text-center">
              © 2026 Flavio Cardoso e Advogados
            </div>
            <div className="flex justify-end">
              <a href="https://carolchang.com/" target="_blank" rel="noopener noreferrer" aria-label="Carol Chang" style={{ display: 'inline-flex', animation: 'spin-star 6s linear infinite' }}>
                <img src="assets/star.svg" alt="star" width="23" height="23" />
              </a>
            </div>
          </div>

          {/* Mobile row 1: social left, star right */}
          <div className="flex md:hidden items-center justify-between">
            <div className="flex items-center gap-5 text-sm text-muted">
              {social.map((s) =>
              <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" className="hover:text-text-primary transition-colors">
                  {s.label}
                </a>
              )}
            </div>
            <a href="https://carolchang.com/" target="_blank" rel="noopener noreferrer" aria-label="Carol Chang" style={{ display: 'inline-flex', animation: 'spin-star 6s linear infinite' }}>
              <img src="assets/star.svg" alt="star" width="23" height="23" />
            </a>
          </div>

          {/* Mobile row 2: copyright left */}
          <div className="flex md:hidden items-center">
            <div className="text-xs text-muted uppercase tracking-[0.25em]">
              © 2026 Flavio Cardoso e Advogados
            </div>
          </div>
        </div>
        <style>{`@keyframes spin-star { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
      </div>
    </section>);

};

window.Contact = Contact;


// ===== components/app.jsx =====
const App = () => {
  const [active, setActive] = useState('Home');

  // Track active section while scrolling
  useEffect(() => {
    const ids = ['home', 'work', 'contact'];
    const labelOf = { home: 'Home', work: 'Áreas de Atuação', contact: 'Contact' };
    const fn = () => {
      const y = window.scrollY + window.innerHeight / 2;
      let cur = 'home';
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) cur = id;
      }
      setActive(labelOf[cur]);
    };
    fn();
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);

  const onNav = (label) => {
    const map = { Home: 'home', 'Áreas de Atuação': 'work', Contact: 'contact' };
    const el = document.getElementById(map[label]);
    if (el) {
      window.scrollTo({ top: el.offsetTop - 20, behavior: 'smooth' });
    }
    setActive(label);
  };

  return (
    <>
      <window.Navbar active={active} onNav={onNav} />
      <main>
        <window.Hero />
        <window.Services />
        <window.About />
        <window.Stats />
        <window.Contact />
      </main>
    </>);

};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);