// shell.jsx — cursor, header, footer, particles, mesh, toast, confetti, easter egg

const { useState, useEffect, useRef, useMemo } = React;

// ─── Particles (floating dots) ─────────────────────────────────
function Particles({ count = 24, color = 'rgba(82,242,15,0.5)' }) {
  const dots = useMemo(() =>
    Array.from({ length: count }, (_, i) => ({
      id: i,
      size: 1 + Math.random() * 2.5,
      x: Math.random() * 100,
      y: Math.random() * 100,
      d: 8 + Math.random() * 14,
      delay: -Math.random() * 14,
    })), [count]);
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 1 }}>
      {dots.map(d => (
        <span key={d.id} style={{
          position: 'absolute', left: d.x + '%', top: d.y + '%',
          width: d.size, height: d.size, borderRadius: '50%',
          background: color, boxShadow: `0 0 ${d.size * 4}px ${color}`,
          animation: `floatDot ${d.d}s ease-in-out ${d.delay}s infinite alternate`,
        }} />
      ))}
      <style>{`@keyframes floatDot { from { transform: translateY(0); opacity: .2 } to { transform: translateY(-30px); opacity: .9 } }`}</style>
    </div>
  );
}

// ─── Mesh BG ───────────────────────────────────────────────────
function Mesh() { return <div className="mesh" />; }

// ─── Animated counter ──────────────────────────────────────────
function Counter({ to, duration = 1600, prefix = '', suffix = '', decimals = 0 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    let started = false;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started) {
        started = true;
        const start = performance.now();
        const tick = (t) => {
          const p = Math.min(1, (t - start) / duration);
          const eased = 1 - Math.pow(1 - p, 3);
          setVal(to * eased);
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }
    }, { threshold: 0.3 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to]);
  const formatted = decimals === 0
    ? Math.round(val).toLocaleString('ro-RO')
    : val.toFixed(decimals).toLocaleString('ro-RO');
  return <span ref={ref} className="mono">{prefix}{formatted}{suffix}</span>;
}

// ─── Reveal on scroll ─────────────────────────────────────────
function Reveal({ children, delay = 0, as: As = 'div', className = '', ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    // Immediate check — if already in viewport on mount, reveal now
    const rect = el.getBoundingClientRect();
    const inView = rect.top < window.innerHeight && rect.bottom > 0;
    if (inView) { setTimeout(() => el.classList.add('in'), delay); return; }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setTimeout(() => el.classList.add('in'), delay); io.disconnect(); }
    }, { threshold: 0, rootMargin: '0px 0px -5% 0px' });
    io.observe(el);
    // Failsafe: reveal after 1.2s no matter what
    const fallback = setTimeout(() => { el.classList.add('in'); io.disconnect(); }, 1200 + delay);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, [delay]);
  return <As ref={ref} className={`rv ${className}`} {...rest}>{children}</As>;
}

// ─── Logo ──────────────────────────────────────────────────────
function Logo({ size = 40, onClick, showText = true }) {
  const Wrapper = onClick ? 'button' : 'div';
  return (
    <Wrapper
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        cursor: onClick ? 'pointer' : 'default',
        background: 'transparent', border: 'none', padding: 0,
        font: 'inherit', color: 'inherit',
      }}>
      <img
        src="uploads/4u-agency-logo.png"
        alt="4U Agency"
        style={{
          width: size, height: size,
          objectFit: 'contain', display: 'block',
          transition: 'transform .25s ease',
          pointerEvents: 'none',
        }}
      />
      {showText && (
        <span className="display" style={{
          fontSize: Math.round(size * 0.42),
          letterSpacing: '-0.02em',
          whiteSpace: 'nowrap',
          lineHeight: 1,
          cursor: onClick ? 'pointer' : 'default',
        }}>
          4U Agency<span style={{ color: 'var(--accent-1)', cursor: onClick ? 'pointer' : 'default' }}>.</span>
        </span>
      )}
    </Wrapper>
  );
}

// ─── Header ────────────────────────────────────────────────────
function LangSwitcher() {
  const [open, setOpen] = useState(false);
  const [lang, setLang] = useState('RO');
  const langs = [
    { code: 'RO', flag: '🇷🇴', label: 'Română' },
    { code: 'EN', flag: '🇬🇧', label: 'English' },
  ];
  const closeT = useRef(null);
  const cur = langs.find(l => l.code === lang);
  return (
    <div style={{ position: 'relative' }}
      onMouseEnter={() => { if (closeT.current) clearTimeout(closeT.current); setOpen(true); }}
      onMouseLeave={() => { closeT.current = setTimeout(() => setOpen(false), 220); }}>
      <button className="btn btn-ghost btn-sm" title="Limbă" style={{ height: 36 }}>
        <span style={{ fontSize: 13 }}>{cur.flag}</span> {cur.code}
        <span style={{ fontSize: 9, opacity: 0.5, marginLeft: 2 }}>▾</span>
      </button>
      {open && (
        <div className="card-glass" style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0,
          minWidth: 160, padding: 6, animation: 'pageIn .2s', zIndex: 110,
        }}
          onMouseEnter={() => { if (closeT.current) clearTimeout(closeT.current); setOpen(true); }}
          onMouseLeave={() => { closeT.current = setTimeout(() => setOpen(false), 220); }}>
          <div style={{ position: 'absolute', top: -10, left: 0, right: 0, height: 10 }} />
          {langs.map(l => (
            <a key={l.code} onClick={() => { setLang(l.code); setOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
              borderRadius: 8, cursor: 'pointer', fontSize: 13,
              color: lang === l.code ? 'var(--accent-1)' : 'var(--txt-1)',
              background: lang === l.code ? 'rgba(82,242,15,.08)' : 'transparent',
            }}
              onMouseEnter={(e) => { if (lang !== l.code) e.currentTarget.style.background = 'rgba(255,255,255,.04)'; }}
              onMouseLeave={(e) => { if (lang !== l.code) e.currentTarget.style.background = 'transparent'; }}>
              <span style={{ fontSize: 16 }}>{l.flag}</span>
              <span style={{ flex: 1 }}>{l.label}</span>
              <span className="mono" style={{ fontSize: 10, color: 'var(--txt-3)' }}>{l.code}</span>
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

function Header({ page, onNav }) {
  const [scrolled, setScrolled] = useState(false);
  const [openMenu, setOpenMenu] = useState(null);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [mobileExpanded, setMobileExpanded] = useState(null);
  const closeMobile = () => {
    if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
    setMobileOpen(false);
  };
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll); onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  // Body scroll lock + Escape key când meniul mobil e deschis
  useEffect(() => {
    if (!mobileOpen) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') closeMobile(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener('keydown', onKey);
    };
  }, [mobileOpen]);
  // Închide meniul mobil când se schimbă pagina
  useEffect(() => { closeMobile(); setMobileExpanded(null); }, [page]);

  const nav = [
    { id: 'home', label: 'Acasă' },
    { id: 'services', label: 'Servicii', dropdown: [
      { id: 'courses', label: 'Academia TikTok', icon: '🎓' },
      { id: 'profile-design', label: 'Personalizare profil', icon: '🎨' },
      { id: 'studios', label: 'Studiouri', icon: '🎬' },
      { id: 'campaigns', label: 'Campanii cu branduri', icon: '📢' },
    ]},
    { id: 'resources', label: 'Resurse', dropdown: [
      { id: 'blog', label: 'Blog', icon: '📝' },
      { id: 'calculator', label: 'Calculator câștiguri', icon: '🧮' },
      { id: 'faq', label: 'FAQ', icon: '💬' },
      { id: 'hall', label: 'Hall of Fame', icon: '🏆' },
    ]},
    { id: 'team', label: 'Echipa' },
    { id: 'about', label: 'Despre 4U' },
    { id: 'signup-influencer', label: 'Influenceri' },
    { id: 'contact', label: 'Contact' },
  ];

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      transition: 'all .25s ease',
      height: scrolled ? 64 : 80,
      backdropFilter: scrolled ? 'blur(20px) saturate(140%)' : 'none',
      background: scrolled ? 'rgba(10,10,15,.72)' : 'transparent',
      borderBottom: scrolled ? '.5px solid var(--line-soft)' : '.5px solid transparent',
    }}>
      <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: '100%' }}>
        <Logo onClick={() => onNav('home')} />
        <nav style={{ display: 'flex', alignItems: 'center', gap: 4 }} className="nav-desktop">
          {nav.map(item => {
            const closeTimer = React.useRef(null);
            const openIt = () => { if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; } if (item.dropdown) setOpenMenu(item.id); };
            const closeIt = () => { if (closeTimer.current) clearTimeout(closeTimer.current); closeTimer.current = setTimeout(() => setOpenMenu(null), 220); };
            return (
            <div key={item.id} style={{ position: 'relative' }} onMouseEnter={openIt} onMouseLeave={closeIt}>
              <button className="btn btn-ghost btn-sm" onClick={() => !item.dropdown && onNav(item.id)} style={{
                color: page === item.id ? 'var(--accent-1)' : 'var(--txt-1)',
                background: 'transparent', height: 36,
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                {item.label}{item.dropdown && (
                  <span style={{
                    fontSize: 16, opacity: 0.9, fontWeight: 700,
                    display: 'inline-flex', alignItems: 'center', lineHeight: 1,
                    transition: 'transform .2s ease',
                    transform: openMenu === item.id ? 'rotate(180deg)' : 'rotate(0deg)',
                  }}>▾</span>
                )}
              </button>
              {item.dropdown && openMenu === item.id && (
                <div className="card-glass" onMouseEnter={openIt} onMouseLeave={closeIt} style={{
                  position: 'absolute', top: 'calc(100% + 8px)', left: 0,
                  minWidth: 240, padding: 6, animation: 'pageIn .2s',
                }}>
                  <div style={{ position: 'absolute', top: -10, left: 0, right: 0, height: 10 }} />
                  {item.dropdown.map(d => (
                    <a key={d.id} onClick={() => { onNav(d.id); setOpenMenu(null); }} style={{
                      display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
                      borderRadius: 8, cursor: 'pointer', color: 'var(--txt-1)', fontSize: 13,
                    }} onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(82,242,15,.08)'}
                       onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                      <span style={{ fontSize: 16 }}>{d.icon}</span>{d.label}
                    </a>
                  ))}
                </div>
              )}
            </div>
            );
          })}
        </nav>
        <div className="nav-actions-desktop" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <LangSwitcher />
          <button className="btn btn-glass btn-sm" onClick={() => window.showPreLaunchAlert('Conturile vor fi disponibile în curând. Site-ul nostru este momentan în pre-launch — pentru orice solicitare, contactează-ne pe email sau telefon.')}>Intră în cont</button>
          <button className="btn btn-primary btn-sm" onClick={() => window.showPreLaunchAlert('Conturile vor fi disponibile în curând. Site-ul nostru este momentan în pre-launch — pentru orice solicitare, contactează-ne pe email sau telefon.')}>Creează cont</button>
        </div>
        <button
          className="nav-mobile-toggle"
          onClick={() => setMobileOpen(true)}
          aria-label="Deschide meniul"
          aria-expanded={mobileOpen}
        >
          <span /><span /><span />
        </button>
      </div>

      {/* === MOBILE DRAWER === */}
      <div
        className={`mobile-overlay ${mobileOpen ? 'open' : ''}`}
        onClick={() => closeMobile()}
        aria-hidden={!mobileOpen}
      />
      <aside
        className={`mobile-drawer ${mobileOpen ? 'open' : ''}`}
        aria-hidden={!mobileOpen}
        role="dialog"
        aria-label="Meniu navigare"
      >
        <div className="mobile-drawer-header">
          <Logo onClick={() => { onNav('home'); closeMobile(); }} />
          <button
            className="mobile-drawer-close"
            onClick={() => closeMobile()}
            aria-label="Închide meniul"
          >×</button>
        </div>
        <nav className="mobile-drawer-nav">
          {nav.map(item => {
            if (!item.dropdown) {
              const isActive = page === item.id;
              return (
                <a
                  key={item.id}
                  className={`mobile-nav-link ${isActive ? 'active' : ''}`}
                  onClick={() => { onNav(item.id); closeMobile(); }}
                >
                  {item.label}
                </a>
              );
            }
            const isExpanded = mobileExpanded === item.id;
            return (
              <div key={item.id} className="mobile-nav-group">
                <button
                  className={`mobile-nav-link mobile-nav-toggle ${isExpanded ? 'expanded' : ''}`}
                  onClick={() => setMobileExpanded(isExpanded ? null : item.id)}
                  aria-expanded={isExpanded}
                >
                  <span>{item.label}</span>
                  <span className="mobile-nav-chevron">▾</span>
                </button>
                {isExpanded && (
                  <div className="mobile-nav-submenu">
                    {item.dropdown.map(d => (
                      <a
                        key={d.id}
                        className={`mobile-nav-sublink ${page === d.id ? 'active' : ''}`}
                        onClick={() => { onNav(d.id); closeMobile(); }}
                      >
                        <span style={{ fontSize: 16 }}>{d.icon}</span>
                        <span>{d.label}</span>
                      </a>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </nav>
        <div className="mobile-drawer-footer">
          <div style={{ marginBottom: 12 }}><LangSwitcher /></div>
          <button
            className="btn btn-glass"
            style={{ width: '100%', marginBottom: 8 }}
            onClick={() => { window.showPreLaunchAlert('Conturile vor fi disponibile în curând. Site-ul nostru este momentan în pre-launch — pentru orice solicitare, contactează-ne pe email sau telefon.'); closeMobile(); }}
          >Intră în cont</button>
          <button
            className="btn btn-primary"
            style={{ width: '100%' }}
            onClick={() => { window.showPreLaunchAlert('Conturile vor fi disponibile în curând. Site-ul nostru este momentan în pre-launch — pentru orice solicitare, contactează-ne pe email sau telefon.'); closeMobile(); }}
          >Creează cont</button>
        </div>
      </aside>

      <style>{`
        .nav-mobile-toggle {
          display: none;
          flex-direction: column;
          justify-content: center;
          gap: 5px;
          width: 40px;
          height: 40px;
          padding: 0;
          background: transparent;
          border: 1px solid var(--line-soft, rgba(255,255,255,.1));
          border-radius: 8px;
          cursor: pointer;
          align-items: center;
        }
        .nav-mobile-toggle span {
          display: block;
          width: 18px;
          height: 2px;
          background: var(--txt-0, #fff);
          border-radius: 2px;
          transition: background .2s;
        }
        .nav-mobile-toggle:hover span { background: var(--accent-1, #52F20F); }

        .mobile-overlay {
          position: fixed; inset: 0;
          background: rgba(0,0,0,.6);
          backdrop-filter: blur(4px);
          z-index: 200;
          opacity: 0;
          pointer-events: none;
          transition: opacity .25s ease;
        }
        .mobile-overlay.open { opacity: 1; pointer-events: auto; }

        .mobile-drawer {
          position: fixed;
          top: 0; right: 0;
          width: min(360px, 85vw);
          height: 100vh;
          height: 100dvh;
          background: rgba(10,10,15,.97);
          backdrop-filter: blur(20px) saturate(140%);
          border-left: .5px solid var(--line-soft, rgba(255,255,255,.08));
          z-index: 201;
          transform: translateX(100%);
          transition: transform .28s cubic-bezier(.4,0,.2,1);
          display: flex;
          flex-direction: column;
          overflow-y: auto;
          overscroll-behavior: contain;
        }
        .mobile-drawer.open { transform: translateX(0); }

        .mobile-drawer-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 20px 24px;
          border-bottom: .5px solid var(--line-soft, rgba(255,255,255,.08));
        }
        .mobile-drawer-close {
          width: 36px; height: 36px;
          padding: 0;
          font-size: 28px;
          line-height: 1;
          background: transparent;
          border: 1px solid var(--line-soft, rgba(255,255,255,.1));
          border-radius: 8px;
          color: var(--txt-1, rgba(255,255,255,.85));
          cursor: pointer;
          transition: all .2s;
        }
        .mobile-drawer-close:hover {
          background: rgba(255,255,255,.05);
          color: var(--accent-1, #52F20F);
        }

        .mobile-drawer-nav {
          flex: 1;
          padding: 16px 12px;
          display: flex;
          flex-direction: column;
          gap: 2px;
        }
        .mobile-nav-link {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          padding: 14px 16px;
          font-size: 15px;
          font-weight: 500;
          color: var(--txt-1, rgba(255,255,255,.85));
          text-decoration: none;
          background: transparent;
          border: none;
          border-radius: 10px;
          cursor: pointer;
          transition: all .15s;
          text-align: left;
        }
        .mobile-nav-link:hover, .mobile-nav-link:focus-visible {
          background: rgba(82,242,15,.08);
          color: var(--txt-0, #fff);
        }
        .mobile-nav-link.active {
          color: var(--accent-1, #52F20F);
          background: rgba(82,242,15,.06);
        }
        .mobile-nav-chevron {
          font-size: 12px;
          opacity: .6;
          transition: transform .2s;
        }
        .mobile-nav-toggle.expanded .mobile-nav-chevron {
          transform: rotate(180deg);
        }
        .mobile-nav-submenu {
          padding: 4px 0 4px 12px;
          margin-bottom: 4px;
          display: flex;
          flex-direction: column;
          gap: 2px;
        }
        .mobile-nav-sublink {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 10px 14px;
          font-size: 14px;
          color: var(--txt-2, rgba(255,255,255,.65));
          text-decoration: none;
          border-radius: 8px;
          cursor: pointer;
          transition: all .15s;
        }
        .mobile-nav-sublink:hover, .mobile-nav-sublink:focus-visible {
          background: rgba(82,242,15,.06);
          color: var(--txt-0, #fff);
        }
        .mobile-nav-sublink.active { color: var(--accent-1, #52F20F); }

        .mobile-drawer-footer {
          padding: 20px 24px;
          border-top: .5px solid var(--line-soft, rgba(255,255,255,.08));
        }

        @media (max-width: 1100px) {
          .nav-desktop { display: none !important; }
          .nav-actions-desktop { display: none !important; }
          .nav-mobile-toggle { display: flex !important; }
        }
      `}</style>
    </header>
  );
}

// ─── Inline Back button (folosit în pagini, sub header) ───────
function BackButton({ onNav, label = 'Înapoi', style = {} }) {
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={() => onNav('__back')}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 10,
        height: 44, padding: hover ? '0 20px 0 16px' : '0 16px',
        borderRadius: 999,
        background: hover
          ? 'linear-gradient(135deg, var(--accent-1) 0%, #3FD000 100%)'
          : 'rgba(255,255,255,.04)',
        border: hover ? '.5px solid var(--accent-1)' : '.5px solid rgba(82,242,15,.35)',
        color: hover ? '#000' : 'var(--txt-1)',
        boxShadow: hover
          ? '0 8px 28px rgba(82,242,15,.35), 0 0 0 4px rgba(82,242,15,.10)'
          : '0 2px 12px rgba(0,0,0,.25)',
        cursor: 'pointer',
        transition: 'all .25s cubic-bezier(.4,0,.2,1)',
        fontFamily: 'inherit', fontSize: 13, fontWeight: 600, letterSpacing: '-0.01em',
        ...style,
      }}
    >
      <span style={{
        display: 'grid', placeItems: 'center', width: 24, height: 24,
        borderRadius: 999,
        background: hover ? 'rgba(0,0,0,.18)' : 'rgba(82,242,15,.18)',
        color: hover ? '#000' : 'var(--accent-1)',
        fontSize: 14, lineHeight: 1, fontWeight: 700,
        transform: hover ? 'translateX(-2px)' : 'translateX(0)',
        transition: 'transform .25s cubic-bezier(.4,0,.2,1)',
      }}>←</span>
      <span>{label}</span>
    </button>
  );
}

// ─── Floating Back button ──────────────────────────────────────
function BackFab({ onNav }) {
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={() => onNav('__back')}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      title="Înapoi la pagina anterioară"
      style={{
        position: 'fixed', left: 24, bottom: 24, zIndex: 95,
        display: 'flex', alignItems: 'center', gap: 10,
        height: 52, padding: hover ? '0 22px 0 18px' : '0 18px',
        borderRadius: 999,
        background: hover
          ? 'linear-gradient(135deg, var(--accent-1) 0%, #3FD000 100%)'
          : 'rgba(15, 17, 22, .85)',
        border: hover ? '.5px solid var(--accent-1)' : '.5px solid rgba(82,242,15,.35)',
        color: hover ? '#000' : 'var(--txt-1)',
        backdropFilter: 'blur(20px) saturate(160%)',
        boxShadow: hover
          ? '0 12px 40px rgba(82,242,15,.45), 0 0 0 4px rgba(82,242,15,.12)'
          : '0 8px 28px rgba(0,0,0,.55), 0 0 0 1px rgba(82,242,15,.08)',
        cursor: 'pointer',
        transition: 'all .25s cubic-bezier(.4,0,.2,1)',
        fontFamily: 'inherit', fontSize: 14, fontWeight: 600, letterSpacing: '-0.01em',
      }}
    >
      <span style={{
        display: 'grid', placeItems: 'center', width: 28, height: 28,
        borderRadius: 999,
        background: hover ? 'rgba(0,0,0,.18)' : 'rgba(82,242,15,.18)',
        color: hover ? '#000' : 'var(--accent-1)',
        fontSize: 16, lineHeight: 1, fontWeight: 700,
        transform: hover ? 'translateX(-2px)' : 'translateX(0)',
        transition: 'transform .25s cubic-bezier(.4,0,.2,1)',
      }}>←</span>
      <span>Înapoi</span>
    </button>
  );
}

// ─── Footer ────────────────────────────────────────────────────
function Footer({ onNav }) {
  useEffect(() => {
    // În SPA React, scriptul Iubenda scanează DOM-ul la încărcarea inițială,
    // dar Footer-ul se renderează DUPĂ — link-urile cu clasa iubenda-embed
    // „scapă" handler-elor pop-up. Fix: re-încarcă scriptul iubenda.js când Footer e montat.
    const script = document.createElement('script');
    script.src = 'https://cdn.iubenda.com/iubenda.js';
    script.async = true;
    document.body.appendChild(script);
    return () => {
      if (script.parentNode) script.parentNode.removeChild(script);
    };
  }, []);
  return (
    <footer style={{ background: '#08080C', borderTop: '.5px solid var(--line-soft)', padding: '80px 0 32px', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 1, background: 'linear-gradient(90deg, transparent, var(--accent-1), var(--accent-2), transparent)' }} />
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1.2fr', gap: 48, marginBottom: 64 }} className="footer-grid">
          <div>
            <Logo size={56} onClick={() => onNav('home')} />
            <p style={{ color: 'var(--txt-2)', fontSize: 14, lineHeight: 1.6, marginTop: 20, maxWidth: 320 }}>
              Agenția #1 de TikTok Live din România. Construim cariere virale în 8 țări, alături de peste 5.000 de creatori.
            </p>
            <div style={{ display: 'flex', gap: 8, marginTop: 24 }}>
              {[
                ['tt','TikTok','M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z'],
                ['ig','Instagram','M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 1 0 0 12.324 6.162 6.162 0 0 0 0-12.324zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.406-11.845a1.44 1.44 0 1 0 0 2.881 1.44 1.44 0 0 0 0-2.881z'],
                ['yt','YouTube','M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z'],
                ['fb','Facebook','M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z'],
              ].map(([s, t, p]) => (
                <a key={s} className="hov" title={t} style={{
                  width: 36, height: 36, borderRadius: 8, display: 'grid', placeItems: 'center',
                  background: 'rgba(255,255,255,.03)', border: '.5px solid var(--line)',
                  color: 'var(--txt-2)', cursor: 'pointer',
                  transition: 'all .2s',
                }} onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--accent-1)'; e.currentTarget.style.borderColor = 'var(--accent-1)'; }}
                   onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--txt-2)'; e.currentTarget.style.borderColor = 'var(--line)'; }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d={p} /></svg>
                </a>
              ))}
            </div>
          </div>
          <FooterCol title="Link-uri rapide" items={[
            ['Despre', 'about'], ['Servicii', 'services'], ['Echipa', 'team'],
            ['Contact', 'contact'], ['Academia TikTok', 'courses'], ['Hall of Fame', 'hall'],
          ]} onNav={onNav} />
          <FooterCol title="Trimite cerere" items={[
            ['Înscriere creatori', 'signup'], ['Înscriere companii', 'signup-company'], ['Pagina de campanii', 'campaigns'],
          ]} onNav={onNav} />
          <div>
            <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 16 }}>Newsletter</div>
            <p style={{ color: 'var(--txt-2)', fontSize: 13, lineHeight: 1.6, marginBottom: 16 }}>Tactici, studii de caz și anunțuri. O dată pe lună.</p>
            <form onSubmit={(e) => { e.preventDefault(); }} style={{ display: 'flex', gap: 8 }}>
              <input className="input" type="email" placeholder="adresa@email.ro" style={{ height: 40 }} />
              <button className="btn btn-primary" style={{ height: 40 }}>→</button>
            </form>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 24, borderTop: '.5px solid var(--line-soft)', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ color: 'var(--txt-3)', fontSize: 12 }}>© 2026 4U Agency. Toate drepturile rezervate.</div>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="https://www.iubenda.com/terms-and-conditions/26919297" className="iubenda-nostyle iubenda-noiframe iubenda-embed hov" title="Termeni și condiții" style={{ color: 'var(--txt-3)', fontSize: 12 }}>Termeni și condiții</a>
            <a href="https://www.iubenda.com/privacy-policy/49632785" className="iubenda-nostyle iubenda-noiframe iubenda-embed hov" title="Politică de Confidențialitate" style={{ color: 'var(--txt-3)', fontSize: 12 }}>Confidențialitate</a>
            <a href="https://www.iubenda.com/privacy-policy/49632785/cookie-policy" className="iubenda-nostyle iubenda-noiframe iubenda-embed hov" title="Politica privind Cookie" style={{ color: 'var(--txt-3)', fontSize: 12 }}>Cookies</a>
            <a href="#" onClick={(e) => { e.preventDefault(); if (window._iub && window._iub.cs && window._iub.cs.api && window._iub.cs.api.openPreferences) { window._iub.cs.api.openPreferences(); } }} className="hov" style={{ color: 'var(--txt-3)', fontSize: 12, cursor: 'pointer' }}>Preferințe cookie</a>
          </div>
        </div>
      </div>
      <style>{`@media (max-width: 900px) { .footer-grid { grid-template-columns: 1fr 1fr !important; } } @media (max-width: 600px) { .footer-grid { grid-template-columns: 1fr !important; } }`}</style>
    </footer>
  );
}
function FooterCol({ title, items, onNav }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 16 }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(([label, id]) => (
          <a key={label} onClick={() => onNav && onNav(id)} style={{ color: 'var(--txt-2)', fontSize: 14, cursor: 'pointer' }} className="hov"
             onMouseEnter={(e) => e.currentTarget.style.color = 'var(--accent-1)'}
             onMouseLeave={(e) => e.currentTarget.style.color = 'var(--txt-2)'}>
            {label}
          </a>
        ))}
      </div>
    </div>
  );
}

// ─── Toast ─────────────────────────────────────────────────────
function useToast() {
  const [msg, setMsg] = useState(null);
  useEffect(() => { if (msg) { const t = setTimeout(() => setMsg(null), 2400); return () => clearTimeout(t); } }, [msg]);
  const Toast = msg ? <div className="toast show">✓ {msg}</div> : null;
  return [Toast, setMsg];
}

// ─── Confetti (easter egg "4U") ────────────────────────────────
function fireWelcomeBanner() {
  const old = document.getElementById('welcome-banner');
  if (old) old.remove();
  const b = document.createElement('div');
  b.id = 'welcome-banner';
  b.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(.6);z-index:10000;padding:32px 56px;border-radius:24px;background:linear-gradient(135deg,rgba(15,15,20,.95),rgba(20,30,15,.95));border:1px solid rgba(82,242,15,.4);box-shadow:0 30px 100px rgba(82,242,15,.35),0 0 0 1px rgba(255,215,0,.2),inset 0 1px 0 rgba(255,255,255,.08);text-align:center;backdrop-filter:blur(20px);opacity:0;transition:transform .5s cubic-bezier(.2,.9,.3,1.4),opacity .35s;pointer-events:none;font-family:Geist,sans-serif;';
  b.innerHTML = `
    <div style="font-family:'JetBrains Mono',monospace;font-size:clamp(9px, 2.5vw, 11px);letter-spacing:.15em;color:#52F20F;margin-bottom:14px;white-space:nowrap;">★ AI GĂSIT SURPRIZA ★</div>
    <div style="font-size:36px;font-weight:700;letter-spacing:-.02em;line-height:1.1;color:#fff;margin-bottom:10px;">
      <span style="background:linear-gradient(135deg,#52F20F,#FFD700);-webkit-background-clip:text;-webkit-text-fill-color:transparent;">4U Agency</span> îți urează
    </div>
    <div style="font-size:56px;font-weight:800;letter-spacing:-.04em;line-height:1;color:#FFD700;margin-bottom:12px;text-shadow:0 0 30px rgba(255,215,0,.5);">BUN VENIT! 🎉</div>
    <div style="font-size:13px;color:rgba(255,255,255,.55);">Mulțumim că ești aici 💚</div>
  `;
  document.body.appendChild(b);
  requestAnimationFrame(() => { b.style.opacity = '1'; b.style.transform = 'translate(-50%,-50%) scale(1)'; });
  setTimeout(() => shatterBannerIntoConfetti(b), 3200);
}
window.fireWelcomeBanner = fireWelcomeBanner;

function shatterBannerIntoConfetti(b) {
  if (!b || !b.parentNode) return;
  const rect = b.getBoundingClientRect();
  const wrap = document.createElement('div');
  wrap.className = 'confetti-wrap';
  document.body.appendChild(wrap);
  const colors = ['#52F20F','#FFD700','#FFFFFF','#52F20F','#FFD700'];
  // Spawn confetti distributed across banner's box
  const count = 1000;
  for (let i = 0; i < count; i++) {
    const c = document.createElement('div');
    c.className = 'cfp';
    const x = rect.left + Math.random() * rect.width;
    const y = rect.top + Math.random() * rect.height;
    c.style.left = x + 'px';
    c.style.top = y + 'px';
    c.style.background = colors[i % colors.length];
    c.style.setProperty('--tx', ((Math.random() - 0.5) * 280) + 'px');
    c.style.animation = `cfFall ${2.0 + Math.random() * 3.0}s cubic-bezier(.3,.7,.3,1) ${Math.random() * 0.6}s forwards`;
    c.style.transform = `rotate(${Math.random() * 360}deg)`;
    c.style.width = (5 + Math.random() * 7) + 'px';
    c.style.height = (8 + Math.random() * 10) + 'px';
    c.style.opacity = (0.25 + Math.random() * 0.20).toFixed(2);
    wrap.appendChild(c);
  }
  // Hide the banner immediately
  b.style.transition = 'opacity .15s';
  b.style.opacity = '0';
  setTimeout(() => b.remove(), 200);
  setTimeout(() => wrap.remove(), 5500);
}

function fireConfetti() {
  const wrap = document.createElement('div');
  wrap.className = 'confetti-wrap';
  document.body.appendChild(wrap);
  const colors = ['#52F20F','#FFD700','#FFFFFF','#52F20F','#FFD700','#52F20F','#FFD700'];
  for (let i = 0; i < 3000; i++) {
    const c = document.createElement('div');
    c.className = 'cfp';
    const x = Math.random() * 100;
    c.style.left = x + '%';
    c.style.top = '-30px';
    c.style.background = colors[i % colors.length];
    c.style.setProperty('--tx', ((Math.random() - 0.5) * 320) + 'px');
    c.style.animation = `cfFall ${2.0 + Math.random() * 3.0}s cubic-bezier(.3,.7,.3,1) ${Math.random() * 2.0}s forwards`;
    c.style.transform = `rotate(${Math.random() * 360}deg)`;
    c.style.width = (5 + Math.random() * 7) + 'px';
    c.style.height = (8 + Math.random() * 10) + 'px';
    wrap.appendChild(c);
  }
  setTimeout(() => wrap.remove(), 7500);
}
window.fireConfetti = fireConfetti;

function useEasterEgg(toast) {
  useEffect(() => {
    const COOLDOWN_MS = 60000;
    const SESSION_MAX = 5;
    const PERSIST_KEY = '4u_egg_lastfire';

    // Expune funcția globală pentru butonul mobil din home.jsx
    window.fireEasterEgg = function() {
      const now = Date.now();
      let lastFire = 0;
      let sessionCount = 0;
      try {
        lastFire = parseInt(sessionStorage.getItem(PERSIST_KEY) || '0', 10);
        sessionCount = parseInt(sessionStorage.getItem(PERSIST_KEY + '_count') || '0', 10);
      } catch (e) {}

      if (sessionCount >= SESSION_MAX) {
        if (toast) toast('Easter egg consumat pentru sesiunea asta 😄');
        return;
      }
      const remaining = COOLDOWN_MS - (now - lastFire);
      if (remaining > 0) {
        if (toast) toast(`Mai așteaptă ${Math.ceil(remaining / 1000)}s ⏳`);
        return;
      }

      try {
        sessionStorage.setItem(PERSIST_KEY, String(now));
        sessionStorage.setItem(PERSIST_KEY + '_count', String(sessionCount + 1));
      } catch (e) {}
      fireConfetti();
      fireWelcomeBanner();
    };

    // Listener pentru tastatură (desktop)
    let buf = '';
    const onKey = (e) => {
      if (e.repeat) return;
      const tag = e.target?.tagName;
      if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable) return;
      buf = (buf + e.key).slice(-2).toUpperCase();
      if (buf !== '4U') return;
      buf = '';
      window.fireEasterEgg();
    };
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('keydown', onKey);
      delete window.fireEasterEgg;
    };
  }, [toast]);
}

// ─── Pre-launch Alert Modal ────────────────────────────────────
function showPreLaunchAlert(message) {
  const old = document.getElementById('pre-launch-modal');
  if (old) old.remove();

  const overlay = document.createElement('div');
  overlay.id = 'pre-launch-modal';
  overlay.style.cssText = 'position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.75);backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;padding:20px;animation:plFadeIn .2s ease-out;';

  const modal = document.createElement('div');
  modal.style.cssText = 'background:#0f1116;border:.5px solid rgba(82,242,15,.3);border-radius:16px;padding:36px 32px;max-width:460px;width:100%;text-align:center;color:#fff;box-shadow:0 30px 100px rgba(0,0,0,.6),0 0 0 1px rgba(82,242,15,.08);font-family:Geist,sans-serif;animation:plScaleIn .25s cubic-bezier(.2,.9,.3,1.1);';

  modal.innerHTML = '<div style="font-size:48px;margin-bottom:16px;">🚧</div><div style="font-size:15px;line-height:1.55;margin-bottom:28px;color:rgba(255,255,255,.85);">' + message + '</div><button id="plClose" style="background:linear-gradient(135deg,#52F20F,#3FD000);color:#000;border:none;padding:12px 36px;border-radius:999px;font-weight:600;cursor:pointer;font-family:inherit;font-size:14px;letter-spacing:-.01em;box-shadow:0 8px 24px rgba(82,242,15,.35);">OK</button>';

  overlay.appendChild(modal);
  document.body.appendChild(overlay);

  const close = () => { overlay.style.opacity = '0'; setTimeout(() => overlay.remove(), 180); };
  overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
  modal.querySelector('#plClose').addEventListener('click', close);

  if (!document.getElementById('pl-modal-style')) {
    const s = document.createElement('style');
    s.id = 'pl-modal-style';
    s.textContent = '@keyframes plFadeIn{from{opacity:0}to{opacity:1}}@keyframes plScaleIn{from{transform:scale(.9);opacity:0}to{transform:scale(1);opacity:1}}';
    document.head.appendChild(s);
  }
}

Object.assign(window, {
  Particles, Mesh, Counter, Reveal, Logo, Header, Footer,
  useToast, fireConfetti, fireWelcomeBanner, useEasterEgg,
  showPreLaunchAlert,
});
