/* ============================================================
   VANTIK — Componentes reutilizables
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ---------- Imagen con respaldo + placeholder técnico ---------- */
function Img({ imgKey, label, className = '', style }) {
  const data = imgKey ? IMAGES[imgKey] : null;
  const url = data ? data.url : null;
  const fallback = data ? data.fallback : null;
  const text = (data && data.alt) || label || 'IMAGEN';
  const [broken, setBroken] = useState(false);

  const onError = (e) => {
    // 1º intento fallido → probar imagen de respaldo; 2º → placeholder
    if (fallback && e.target.src !== fallback) {
      e.target.src = fallback;
    } else {
      setBroken(true);
    }
  };

  if (url && !broken) {
    return (
      <img src={url} alt={text} title={text}
        className={'v-img ' + className} style={style}
        loading="lazy" onError={onError} />
    );
  }
  return (
    <div className={'v-ph ' + className} style={style} role="img" aria-label={text}>
      <span className="v-ph__grid" />
      <span className="v-ph__label">{label || text}</span>
    </div>
  );
}

/* ---------- Botón ---------- */
function Btn({ children, href = '#/', variant = 'solid', onClick, type, className = '' }) {
  const cls = 'v-btn v-btn--' + variant + ' ' + className;
  if (type) return <button type={type} className={cls} onClick={onClick}>{children}</button>;
  return <a href={href} className={cls} onClick={onClick}>{children}</a>;
}

/* ---------- Eyebrow / kicker técnico ---------- */
function Kicker({ children }) {
  return <div className="v-kicker">{children}</div>;
}

/* ---------- Encabezado de sección ---------- */
function SectionHead({ title, subtitle, align = 'center' }) {
  return (
    <div className={'v-sechead v-sechead--' + align + ' v-reveal'}>
      <h2 className="v-h2">{title}</h2>
      {subtitle && <p className="v-sub">{subtitle}</p>}
    </div>
  );
}

/* ---------- Tarjeta de servicio (icono) ---------- */
function ServiceCard({ icon, title, text, more = true }) {
  return (
    <div className="v-card v-reveal">
      <div className="v-card__icon"><Icon name={icon} size={30} /></div>
      <h3 className="v-card__title">{title}</h3>
      <p className="v-card__text">{text}</p>
      {more && (
        <a className="v-card__more" href="#/servicios">
          MÁS INFO <Icon name="arrow" size={15} strokeWidth={1.8} />
        </a>
      )}
    </div>
  );
}

/* ---------- Tarjeta con foto (proyectos / soluciones) ---------- */
function PhotoCard({ img, tag, title, text, cta = 'VER MÁS', onClick, onCta }) {
  const handleCta = onCta
    ? (e) => { e.preventDefault(); e.stopPropagation(); onCta(); }
    : undefined;
  const cardProps = onClick
    ? { onClick, role: 'button', tabIndex: 0, style: { cursor: 'pointer' },
        onKeyDown: (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(); } } }
    : {};
  return (
    <div className={'v-pcard v-reveal' + (cardProps.className || '')} {...cardProps}>
      <div className="v-pcard__media">
        <Img imgKey={img} />
        {tag && <span className="v-pcard__tag">{tag}</span>}
      </div>
      <div className="v-pcard__body">
        <h3 className="v-pcard__title">{title}</h3>
        {text && <p className="v-pcard__text">{text}</p>}
        {cta && (
          <a className="v-pcard__cta" href="#/proyectos" onClick={handleCta}>
            {cta} <Icon name="arrow" size={15} strokeWidth={1.8} />
          </a>
        )}
      </div>
    </div>
  );
}

/* ---------- Banda azul de conceptos / capacidades ---------- */
function ConceptBand({ title, items, variant = 'dark' }) {
  return (
    <section className={'v-band ' + (variant === 'light' ? 'v-band--light' : '')}>
      <div className="v-wrap">
        {title && <h2 className="v-band__title">{title}</h2>}
        <div className="v-band__grid" style={{ '--n': items.length }}>
          {items.map((it, i) => {
            const delay = i < 3 ? ' v-reveal-delay-' + (i + 1) : '';
            return (
              <div className={'v-band__item v-reveal' + delay} key={i}>
                <div className="v-band__icon"><Icon name={it.icon} size={32} strokeWidth={1.5} /></div>
                <div className="v-band__label">{it.label}</div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------- Logo ---------- */
function Logo({ light = false }) {
  // light=false (header blanco): VANTIK en azul oscuro + naranja, fondo transparente
  // light=true  (footer oscuro):  VANTIK en blanco  + naranja, fondo transparente
  const src = light ? BRAND.footer : BRAND.header;
  const h   = light ? 32 : 30;
  return (
    <a href="#/" className="v-logo" aria-label="VANTIK — ir al inicio">
      <img
        src={src}
        alt="VANTIK"
        style={{ display: 'block', height: h + 'px', width: 'auto', objectFit: 'contain', maxWidth: '180px' }}
      />
    </a>
  );
}

/* ---------- Header ---------- */
function Header({ route }) {
  const [open, setOpen] = useState(false);
  const headerRef = useRef(null);
  const firstLinkRef = useRef(null);

  // Cierra al cambiar de ruta
  useEffect(() => { setOpen(false); }, [route]);

  // Escape + click fuera + scroll lock
  useEffect(() => {
    if (!open) return;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    const onClickOut = (e) => {
      if (headerRef.current && !headerRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('keydown', onKey);
    document.addEventListener('mousedown', onClickOut);
    // Foco al primer enlace del menú
    if (firstLinkRef.current) firstLinkRef.current.focus();
    return () => {
      document.body.style.overflow = '';
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('mousedown', onClickOut);
    };
  }, [open]);

  return (
    <header className="v-header" ref={headerRef}>
      <div className="v-wrap v-header__inner">
        <Logo />
        <nav className="v-nav" aria-label="Navegación principal">
          {NAV.map((n) => {
            const active = route === n.href || (n.href === '#/' && route === '#/');
            return (
              <a key={n.href} href={n.href}
                className={'v-nav__link ' + (active ? 'is-active' : '')}
                aria-current={active ? 'page' : undefined}>
                {n.label}
              </a>
            );
          })}
        </nav>
        <div className="v-header__cta">
          <Btn href="#/contacto" variant="solid">{CTA_LABEL}</Btn>
        </div>
        <button
          className="v-burger"
          aria-label={open ? 'Cerrar menú' : 'Abrir menú'}
          aria-expanded={open}
          aria-controls="v-mobnav"
          onClick={() => setOpen(!open)}
        >
          <span /><span /><span />
        </button>
      </div>
      {open && (
        <nav id="v-mobnav" className="v-mobnav" aria-label="Menú móvil">
          {NAV.map((n, i) => (
            <a key={n.href} href={n.href}
              ref={i === 0 ? firstLinkRef : undefined}
              className="v-mobnav__link"
              aria-current={route === n.href ? 'page' : undefined}
              onClick={() => setOpen(false)}>
              {n.label}
            </a>
          ))}
          <Btn href="#/contacto" variant="solid" className="v-mobnav__cta"
            onClick={() => setOpen(false)}>{CTA_LABEL}</Btn>
        </nav>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  const soc = SITE_CONFIG.social;
  const hasSocial = soc.linkedin || soc.instagram || soc.youtube || soc.x;
  return (
    <footer className="v-footer">
      <div className="v-wrap v-footer__top">
        <div className="v-footer__brand">
          <Logo light />
          <p className="v-footer__tag">{FOOTER_TAGLINE}</p>
        </div>
        {FOOTER_COLS.map((col) => (
          <div className="v-footer__col" key={col.title}>
            <h4>{col.title}</h4>
            <ul>
              {col.links.map((l) => (
                <li key={l.label}><a href={l.href}>{l.label}</a></li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div className="v-footer__bar">
        <div className="v-wrap v-footer__barin">
          <span>{FOOTER_COPY}</span>
          {hasSocial && (
            <div className="v-social">
              {soc.linkedin  && <a href={soc.linkedin}  target="_blank" rel="noopener noreferrer" aria-label="LinkedIn"><Icon name="linkedin" size={17} /></a>}
              {soc.instagram && <a href={soc.instagram} target="_blank" rel="noopener noreferrer" aria-label="Instagram"><Icon name="instagram" size={17} /></a>}
              {soc.youtube   && <a href={soc.youtube}   target="_blank" rel="noopener noreferrer" aria-label="YouTube"><Icon name="youtube" size={17} /></a>}
              {soc.x         && <a href={soc.x}         target="_blank" rel="noopener noreferrer" aria-label="X"><Icon name="x" size={17} /></a>}
            </div>
          )}
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Img, Btn, Kicker, SectionHead, ServiceCard, PhotoCard,
  ConceptBand, Logo, Header, Footer,
});
