/* ============================================================
   CLOSING CAPITAL — Componentes compartidos
   Nav, Footer, Logo, hooks de animación, partículas
   ============================================================ */

const { useEffect, useRef, useState, createContext, useContext } = React;

// ============================================================
// LOGO SVG (recreación inspirada en el logo aportado)
// ============================================================

function LogoMark({ size = 42, className = '' }) {
  return (
    <svg viewBox="0 0 100 100" width={size} height={size} className={className} aria-label="Closing Capital">
      <defs>
        <linearGradient id="cc-gold" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="var(--gold-deep)" />
          <stop offset="50%" stopColor="var(--gold-light)" />
          <stop offset="100%" stopColor="var(--gold)" />
        </linearGradient>
        <linearGradient id="cc-silver" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#e8e8ed" />
          <stop offset="100%" stopColor="#9a9aa3" />
        </linearGradient>
      </defs>
      {/* C exterior dorada */}
      <path d="M 50 10 A 40 40 0 1 0 50 90"
        fill="none" stroke="url(#cc-gold)" strokeWidth="5" strokeLinecap="round" />
      {/* C interior plateada (espejo) */}
      <path d="M 50 22 A 28 28 0 1 1 50 78"
        fill="none" stroke="url(#cc-silver)" strokeWidth="3.5" strokeLinecap="round" opacity="0.85" />
      {/* Barras crecientes */}
      <rect x="36" y="58" width="6" height="14" fill="url(#cc-gold)" />
      <rect x="44" y="50" width="6" height="22" fill="url(#cc-gold)" />
      <rect x="52" y="42" width="6" height="30" fill="url(#cc-gold)" />
      {/* Flecha */}
      <path d="M 60 38 L 68 30 L 62 30 M 68 30 L 68 36"
        fill="none" stroke="url(#cc-gold)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ============================================================
// NAVIGATION
// ============================================================

function Nav({ active }) {
  const [scrolled, setScrolled] = useState(false);
  const [lang, setLang] = useState('ES');

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { id: 'inicio', label: 'Inicio', href: 'index.html' },
    { id: 'agencia', label: 'Agencia Closing', href: 'agencia-closing.html' },
    { id: 'academia', label: 'Academia Closing', href: 'academia-closing.html' },
    { id: 'agents', label: 'Closing Agents', href: 'closing-agents.html' },
  ];

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <a href="index.html" className="nav-logo">
        <LogoMark size={42} className="mark" />
        <div className="name">
          CLOSING
          <small>CAPITAL</small>
        </div>
      </a>

      <div className="nav-links">
        {links.map(l => (
          <a key={l.id} href={l.href} className={`nav-link ${active === l.id ? 'active' : ''}`}>
            {l.label}
          </a>
        ))}
      </div>

      <div className="nav-actions">
        <div className="lang-switch">
          <button className={lang === 'ES' ? 'active' : ''} onClick={() => setLang('ES')}>ES</button>
          <span className="sep">/</span>
          <button className={lang === 'EN' ? 'active' : ''} onClick={() => setLang('EN')}>EN</button>
        </div>
        <a href="#contacto" className="nav-cta">Agendar llamada</a>
      </div>
    </nav>
  );
}

// ============================================================
// FOOTER
// ============================================================

function Footer() {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div className="footer-brand">
          <LogoMark size={56} style={{ marginBottom: 18 }} />
          <div className="name">CLOSING CAPITAL</div>
          <div className="tag">Cerramos tratos. Generamos resultados.</div>
          <p>
            Agencia de marketing digital y closing de ventas para emprendedores
            que valoran la excelencia y la rentabilidad medible.
          </p>
        </div>

        <div className="footer-col">
          <h5>Compañía</h5>
          <ul>
            <li><a href="index.html">Inicio</a></li>
            <li><a href="agencia-closing.html">Agencia Closing</a></li>
            <li><a href="academia-closing.html">Academia</a></li>
            <li><a href="closing-agents.html">Closing Agents</a></li>
          </ul>
        </div>

        <div className="footer-col">
          <h5>Servicios</h5>
          <ul>
            <li><a href="agencia-closing.html">IA & Automatización</a></li>
            <li><a href="agencia-closing.html">Funnels de alta conversión</a></li>
            <li><a href="agencia-closing.html">Cerradores expertos</a></li>
            <li><a href="agencia-closing.html">Campañas premium</a></li>
          </ul>
        </div>

        <div className="footer-col">
          <h5>Contacto</h5>
          <ul>
            <li><a href="mailto:hola@closingcapital.com">hola@closingcapital.com</a></li>
            <li><a href="#">+34 600 000 000</a></li>
            <li><a href="#">Madrid · Marbella</a></li>
            <li><a href="#" className="gold-text">Agendar llamada →</a></li>
          </ul>
        </div>
      </div>

      <div className="footer-bottom">
        <span>© 2026 Closing Capital · Todos los derechos reservados</span>
        <span>Aviso legal · Privacidad · Cookies</span>
      </div>
    </footer>
  );
}

// ============================================================
// HOOK: scroll reveal
// ============================================================

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -80px 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ============================================================
// PARTICULAS DORADAS
// ============================================================

function GoldParticles({ count = 25 }) {
  const particles = Array.from({ length: count }, (_, i) => {
    const left = Math.random() * 100;
    const dur = 8 + Math.random() * 14;
    const delay = Math.random() * 12;
    const size = 1 + Math.random() * 2.5;
    return (
      <span
        key={i}
        className="particle"
        style={{
          left: `${left}%`,
          width: `${size}px`,
          height: `${size}px`,
          animationDuration: `${dur}s`,
          animationDelay: `${delay}s`,
        }}
      />
    );
  });
  return <div className="particles" aria-hidden="true">{particles}</div>;
}

// ============================================================
// COUNTER ANIMADO
// ============================================================

function Counter({ to, duration = 2200, suffix = '', prefix = '', decimals = 0 }) {
  const [n, setN] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);

  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !started.current) {
        started.current = true;
        const start = performance.now();
        const tick = (now) => {
          const t = Math.min(1, (now - start) / duration);
          // easeOutCubic
          const eased = 1 - Math.pow(1 - t, 3);
          setN(to * eased);
          if (t < 1) requestAnimationFrame(tick);
          else setN(to);
        };
        requestAnimationFrame(tick);
      }
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);

  return <span ref={ref}>{prefix}{n.toFixed(decimals)}{suffix}</span>;
}

// ============================================================
// EXPORT GLOBAL
// ============================================================

Object.assign(window, {
  LogoMark,
  Nav,
  Footer,
  useReveal,
  GoldParticles,
  Counter,
});
