// Fly Media — Landing Page (rediseño)
// Renders Hero, Problema, Servicios, Showcase, Clientes, CTA, Footer

const { useState, useEffect, useRef } = React;
const { motion, AnimatePresence, useScroll, useTransform, useInView } = window.framerMotion;

// ---------- Lucide icons (inline SVG, 1.75px stroke) ----------
const Svg = ({ children, size = 20, stroke = 1.75, ...rest }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth={stroke}
       strokeLinecap="round" strokeLinejoin="round" {...rest}>
    {children}
  </svg>
);
const PlayCircle = (p) => <Svg {...p}><circle cx="12" cy="12" r="10" /><polygon points="10 8 16 12 10 16 10 8" /></Svg>;
const Play = (p) => <Svg {...p}><polygon points="6 3 20 12 6 21 6 3" /></Svg>;
const ArrowRight = (p) => <Svg {...p}><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></Svg>;
const Instagram = (p) => <Svg {...p}><rect x="2" y="2" width="20" height="20" rx="5" ry="5" /><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" /><line x1="17.5" y1="6.5" x2="17.51" y2="6.5" /></Svg>;
const MessageCircle = (p) => <Svg {...p}><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" /></Svg>;
const WhatsAppIcon = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
  </svg>
);

// ---------- WhatsApp (config.js) ----------
const FLY = window.FLY_CONFIG || {};
const waLink = (msg) =>
  `https://wa.me/${FLY.whatsapp || ""}?text=${encodeURIComponent(msg || FLY.whatsappMsg || "Hola Fly Media, quiero información sobre un video.")}`;

// ---------- prefers-reduced-motion ----------
const useReducedMotion = () => {
  const [r, setR] = useState(false);
  useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    setR(mq.matches);
    const f = (e) => setR(e.matches);
    mq.addEventListener?.('change', f);
    return () => mq.removeEventListener?.('change', f);
  }, []);
  return r;
};

// Expo-out — same curve que la referencia
const EASE = [0.16, 1, 0.3, 1];

// fade + rise + blur (entrada estilo wealth)
const fadeRise = (delay = 0) => ({
  initial: { opacity: 0, y: 24, filter: 'blur(8px)' },
  animate: { opacity: 1, y: 0, filter: 'blur(0px)' },
  transition: { duration: 0.8, ease: EASE, delay }
});
const fadeRiseInView = (delay = 0) => ({
  initial: { opacity: 0, y: 24, filter: 'blur(8px)' },
  whileInView: { opacity: 1, y: 0, filter: 'blur(0px)' },
  viewport: { once: true, margin: '-80px' },
  transition: { duration: 0.7, ease: EASE, delay }
});

// ---------- Nav ----------
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <a href="#top" className="nav-logo" aria-label="Fly Media — Inicio">
        <img className="logo-mark" src="assets/logo-icon.png" alt="" />
        <img className="logo-wordmark" src="assets/logo-wordmark-dark.png" alt="" />
      </a>
      <nav aria-label="Principal" className="nav-center">
        <ul className="nav-links">
          <li><a href="#servicios">Servicios</a></li>
          <li><a href="#trabajo">Trabajo</a></li>
          <li><a href="#nosotros">Nosotros</a></li>
          <li><a href="#contacto">Contacto</a></li>
        </ul>
      </nav>
      <a href="/cotizador" className="btn btn-primary nav-cta">
        Cotiza tu proyecto
      </a>
    </header>
  );
}

// ---------- Hero ----------
const HERO_HEADLINE = "Capturamos cada ángulo.";

const PROCESS = [
  { step: "Brief",      title: "Escuchamos tu marca",   body: "Entendemos qué quieres decir y a quién, antes de encender una cámara." },
  { step: "Producción", title: "Rodamos con intención", body: "Dirección, luz y movimiento al servicio de la historia, no del efecto." },
  { step: "Post",       title: "Editamos con ritmo",    body: "Color, sonido y montaje que sostienen la atención hasta el final." },
  { step: "Entrega",    title: "Listo para publicar",   body: "Formatos para cada plataforma, en tiempo y sin vueltas." }
];

function Hero() {
  const reduced = useReducedMotion();
  const videoRef = useRef(null);

  // Ping-pong loop via timeupdate fallback (reverse playbackRate isn't widely supported)
  useEffect(() => {
    if (reduced) return;
    const v = videoRef.current;
    if (!v) return;

    let dir = 1; // 1 forward, -1 reverse
    let rafId = null;
    let lastTime = performance.now();

    const tick = (now) => {
      if (!v.duration) { rafId = requestAnimationFrame(tick); return; }
      const dt = (now - lastTime) / 1000;
      lastTime = now;
      if (dir === -1) {
        // manual reverse
        v.pause();
        let t = v.currentTime - dt;
        if (t <= 0) { t = 0; dir = 1; v.play().catch(()=>{}); }
        else v.currentTime = t;
      } else {
        if (v.paused) v.play().catch(()=>{});
        if (v.currentTime >= v.duration - 0.08) {
          dir = -1;
          v.pause();
        }
      }
      rafId = requestAnimationFrame(tick);
    };

    const start = () => { lastTime = performance.now(); rafId = requestAnimationFrame(tick); };

    if (v.readyState >= 1) start();
    else v.addEventListener('loadedmetadata', start, { once: true });

    return () => { if (rafId) cancelAnimationFrame(rafId); v.pause(); };
  }, [reduced]);

  const words = HERO_HEADLINE.split(" ");

  return (
    <section className="hero" id="top" aria-label="Hero">
      {/* sin poster: el video es el fondo desde el primer cuadro.
          Con reduced-motion queda quieto en su primer cuadro. */}
      <video
        key="video"
        ref={videoRef}
        className="hero-video"
        src="assets/hero-web.mp4"
        autoPlay={!reduced}
        muted
        playsInline
        preload="auto"
        aria-hidden="true"
      />

      <div key="content" className="hero-content">
        <motion.span key="pill" className="tag-pill" {...fadeRise(0.2)}>
          <span className="dot" aria-hidden="true" />
          Productora audiovisual · Chihuahua
        </motion.span>

        <h1 className="headline">
          {words.map((w, i) => (
            <motion.span
              key={`${w}-${i}`}
              className="blur-word"
              initial={reduced ? false : { opacity: 0, y: 40, filter: 'blur(12px)' }}
              animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}
              transition={{ duration: 0.85, ease: EASE, delay: 0.35 + i * 0.11 }}
            >
              {w}
            </motion.span>
          ))}
        </h1>

        <motion.p key="lead" className="lead" {...fadeRise(0.8)}>
          Video para marcas que quieren verse como se sienten: corporativo,
          comercial, redes sociales y eventos.
          <span className="lead-tag">Bold presence. Precise impact.</span>
        </motion.p>

        <motion.div key="cta" className="hero-cta-row" {...fadeRise(1.0)}>
          <a href="/cotizador" className="btn btn-primary">
            Cotiza tu proyecto <ArrowRight size={16} />
          </a>
          <a href="#trabajo" className="btn btn-ghost">
            <PlayCircle size={18} /> Ver trabajo
          </a>
        </motion.div>

        <motion.div key="soc" className="hero-social" {...fadeRise(1.15)}>
          <span className="dot" />
          +120 marcas ya cuentan su historia con nosotros
        </motion.div>
      </div>

      <motion.div key="card" className="process-wrap" {...fadeRise(1.3)}>
        <div className="process-card">
          <div className="process-grid">
            {PROCESS.map((f, i) => (
              <div className="process-item" key={f.step}>
                <div className="process-step">
                  <span className="step-num">{i + 1}</span>
                  <span>{f.step}</span>
                </div>
                <div className="process-title">{f.title}</div>
                <p className="process-desc">{f.body}</p>
              </div>
            ))}
          </div>
        </div>
      </motion.div>
    </section>
  );
}

// ---------- Problema (word-by-word scroll reveal) ----------
function Problema() {
  const reduced = useReducedMotion();
  const sectionRef = useRef(null);
  const { scrollYProgress } = useScroll({
    target: sectionRef,
    offset: ["start 0.9", "end 0.6"]
  });

  const text = "Un video sin intención no vende. Un corporativo sin pulso. Un reel más que el feed olvida. Tu marca merece cine.";
  const words = text.split(" ");
  // Las palabras terminan dentro del primer tramo del recorrido; el resto
  // sostiene la frase completa en pantalla antes de que la sección salga.
  const REVEAL_SPAN = 0.78;

  return (
    <section ref={sectionRef} className="problema" id="problema" aria-label="Problema">
      <p className="problema-text">
        {words.map((w, i) => {
          const start = (i / words.length) * REVEAL_SPAN;
          const end = ((i + 1) / words.length) * REVEAL_SPAN;
          const isHighlight = w.startsWith("cine");
          return (
            <ProblemWord
              key={i}
              word={w}
              isHighlight={isHighlight}
              progress={scrollYProgress}
              start={start}
              end={end}
              reduced={reduced}
            />
          );
        })}
      </p>
    </section>
  );
}
function ProblemWord({ word, isHighlight, progress, start, end, reduced }) {
  const opacity = useTransform(progress, [start, end], reduced ? [1,1] : [0.18, 1]);
  const color   = useTransform(progress, [start, end], isHighlight ? ['#FAF6F0', '#D4321A'] : ['#FAF6F0', '#FAF6F0']);
  return (
    <motion.span className="problema-word" style={{ opacity, color }}>
      {word}
    </motion.span>
  );
}

// ---------- Servicios ----------
// Recap de lo que hacemos. Los videos de cada área viven en la sección Trabajo.
// `from`/`to` pintan el panel degradado detrás de cada tarjeta (paleta ember/amber).
const Building = (p) => <Svg {...p}><rect x="4" y="2" width="16" height="20" rx="2" /><path d="M9 22v-4h6v4" /><path d="M8 6h.01M16 6h.01M12 6h.01M12 10h.01M12 14h.01M16 10h.01M16 14h.01M8 10h.01M8 14h.01" /></Svg>;
const Home = (p) => <Svg {...p}><path d="M3 10.5 12 3l9 7.5" /><path d="M5 9.5V21h14V9.5" /><path d="M10 21v-6h4v6" /></Svg>;
const Smartphone = (p) => <Svg {...p}><rect x="6" y="2" width="12" height="20" rx="2" /><path d="M12 18h.01" /></Svg>;
const Drone = (p) => <Svg {...p}><circle cx="5" cy="5" r="2.5" /><circle cx="19" cy="5" r="2.5" /><circle cx="5" cy="19" r="2.5" /><circle cx="19" cy="19" r="2.5" /><rect x="9.5" y="9.5" width="5" height="5" rx="1" /><path d="M7 7l2.5 2.5M17 7l-2.5 2.5M7 17l2.5-2.5M17 17l-2.5-2.5" /></Svg>;
const Sparkles = (p) => <Svg {...p}><path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z" /><path d="M19 17l.8 2.2L22 20l-2.2.8L19 23l-.8-2.2L16 20l2.2-.8z" /><path d="M4 2l.6 1.4L6 4l-1.4.6L4 6l-.6-1.4L2 4l1.4-.6z" /></Svg>;

const SERVICES = [
  {
    title: "Corporativo",
    sub: "Institucional, cultura y comunicación interna. Tu empresa, contada con oficio.",
    points: ["Institucional", "Cultura y equipo", "Capacitación"],
    icon: Building, from: "#D4321A", to: "#F26A1F"
  },
  {
    title: "Inmobiliario",
    sub: "Recorridos y desarrollos. La propiedad se entiende antes de visitarla.",
    points: ["Recorridos", "Desarrollos", "Casa muestra"],
    icon: Home, from: "#F26A1F", to: "#FFC947"
  },
  {
    title: "Redes Sociales",
    sub: "Verticales, reels y contenido recurrente que sostiene la atención.",
    points: ["Reels y verticales", "Contenido mensual", "Cobertura"],
    icon: Smartphone, from: "#F9A825", to: "#D4321A"
  },
  {
    title: "Tomas aéreas",
    sub: "Drones para dar escala y perspectiva. Aperturas, transiciones y cobertura que desde tierra no existen.",
    points: ["Aperturas y transiciones", "Inmobiliario y arquitectura", "Eventos y cobertura"],
    icon: Drone, from: "#FFC947", to: "#F26A1F"
  },
  {
    title: "Producción con IA",
    sub: "Híbrida o generada de principio a fin. Tomas reales que la IA extiende, o escenas que ninguna cámara alcanza. Aplica a cualquiera de las otras áreas.",
    points: ["Híbrida: grabado + IA", "100% generado", "Complemento de tomas"],
    icon: Sparkles, from: "#D4321A", to: "#F9A825"
  }
];

function VideoSlot({ src, title }) {
  if (src) {
    return <video src={src} autoPlay muted loop playsInline preload="metadata" />;
  }
  return (
    <div className="video-slot" role="img" aria-label={`Video de ${title}, próximamente`}>
      <div className="video-slot-ring">
        <Play size={20} />
      </div>
      <span className="video-slot-text">Portafolio · Próximamente</span>
    </div>
  );
}

function Servicios() {
  // En táctil no hay hover: un tap abre/cierra la tarjeta (solo una a la vez).
  const [open, setOpen] = useState(null);
  return (
    <section className="section-pad section-wrap" id="servicios" aria-label="Servicios">
      <motion.div className="section-head" {...fadeRiseInView(0)}>
        <div className="eyebrow"><span className="eyebrow-dot" />Lo que hacemos</div>
        <h2>Nuestros<br/>servicios.</h2>
      </motion.div>

      <div className="servicios-grid">
        {SERVICES.map((sv, i) => (
          <motion.article
            key={sv.title}
            className={"service-card" + (open === i ? " is-open" : "")}
            style={{ "--sv-from": sv.from, "--sv-to": sv.to }}
            onClick={() => setOpen(open === i ? null : i)}
            {...fadeRiseInView(i * 0.08)}
          >
            <span className="service-card-skew" aria-hidden="true" />
            <span className="service-card-glow" aria-hidden="true" />
            <div className="service-card-body">
              <span className="service-card-icon"><sv.icon size={22} /></span>
              <h3>{sv.title}</h3>
              <p>{sv.sub}</p>
              <ul className="service-points">
                {sv.points.map((pt) => (
                  <li key={pt}><span className="point-dot" aria-hidden="true" />{pt}</li>
                ))}
              </ul>
              <a className="service-card-arrow" href="#trabajo">
                Ver trabajo <ArrowRight size={14} />
              </a>
            </div>
          </motion.article>
        ))}
      </div>
    </section>
  );
}

// ---------- Trabajo ----------
// Un teaser de 10 s por área, sin audio. Los masters viven fuera del repo (videos/).
const WORK = [
  { tag: "Corporativo",        title: "Institucional",           src: "assets/trabajo-corporativo.mp4" },
  { tag: "Producción con IA",  title: "Pieza híbrida",           src: "assets/trabajo-hibrida.mp4" },
  { tag: "Inmobiliario",       title: "Recorrido de desarrollo", src: "assets/trabajo-inmobiliario.mp4" },
  { tag: "Redes Sociales",     title: "Contenido vertical",      src: "assets/trabajo-redes.mp4" }
];

// Entrada sin blur: Framer deja `filter: blur(0px)` inline al terminar, y un
// filter sobre el contenedor saca al video de la capa acelerada del navegador
// (parpadeo al hacer hover mientras reproduce).
const workReveal = (delay = 0) => ({
  initial: { opacity: 0, y: 24 },
  whileInView: { opacity: 1, y: 0 },
  viewport: { once: true, margin: '-80px' },
  transition: { duration: 0.7, ease: EASE, delay }
});

function Trabajo() {
  return (
    <section className="section-pad section-wrap" id="trabajo" aria-label="Trabajo">
      <motion.div className="section-head" {...fadeRiseInView(0)}>
        <div className="eyebrow"><span className="eyebrow-dot" />Lo que hemos hecho</div>
        <h2>Trabajo<br/>reciente.</h2>
      </motion.div>

      <div className="trabajo-grid">
        {WORK.map((w, i) => (
          <motion.article
            key={w.tag}
            className="work-card"
            {...workReveal(i * 0.08)}
          >
            <div className="service-card-image">
              <VideoSlot src={w.src} title={w.title} />
            </div>
            <div className="work-card-body">
              <span className="work-card-tag">{w.tag}</span>
              <h3>{w.title}</h3>
            </div>
          </motion.article>
        ))}
      </div>
    </section>
  );
}

// ---------- Clientes ----------
// Logos de clientes: versiones monocromo blancas en assets/clientes/ (fondo oscuro).
const CLIENTES = [
  { name: "ECA LNG", logo: "assets/clientes/eca-lng.png" },
  { name: "Stay Fit Fitness Center", logo: "assets/clientes/stay-fit.png" },
  { name: "SOC | FIINBRO", logo: "assets/clientes/soc-fiinbro.png" },
  { name: "Vocablo Idiomas Premium", logo: "assets/clientes/vocablo.png" },
  { name: "Quesería Dos Lagunas", logo: "assets/clientes/queseria-dos-lagunas.png" },
  { name: "American School Chihuahua", logo: "assets/clientes/american-school.png" },
  { name: "María Bonita", logo: "assets/clientes/maria-bonita.png" },
  { name: "Habitual", logo: "assets/clientes/habitual.png" },
  { name: "Quota Arquitectos", logo: "assets/clientes/quota.png" },
  { name: "Chiquitito Café", logo: "assets/clientes/chiquitito-cafe.png" }
];

function Clientes() {
  // La lista va duplicada: la segunda copia es la que hace el loop sin costura.
  const track = [...CLIENTES, ...CLIENTES];
  return (
    <section className="section-pad section-wrap" id="clientes" aria-label="Clientes">
      <motion.div className="section-head" {...fadeRiseInView(0)}>
        <div className="eyebrow"><span className="eyebrow-dot" />Confían en nosotros</div>
        <h2>Marcas que ya<br/>confiaron.</h2>
      </motion.div>

      <motion.div className="clients-marquee" {...fadeRiseInView(0.08)}>
        <div className="clients-track">
          {track.map((c, i) => (
            <div
              className="client-logo"
              key={i}
              aria-hidden={i >= CLIENTES.length ? "true" : undefined}
            >
              {c.logo
                ? <img src={c.logo} alt={c.name} />
                : <span className="client-placeholder">{c.name}</span>}
            </div>
          ))}
        </div>
      </motion.div>
    </section>
  );
}

// ---------- Nosotros ----------
const TEAM = [
  { name: "Alejandro Peralta", role: "Director", img: "assets/equipo-alejandro.jpg" },
  { name: "Carlos García", role: "Gerente de Producciones", img: "assets/equipo-carlos.jpg" }
];

// Galería de la empresa (detrás de cámaras).
const GALLERY = ["assets/bts-1.jpg", "assets/bts-2.jpg", "assets/bts-3.jpg"];

const initials = (name) => name.split(" ").slice(0, 2).map(w => w[0]).join("");

// Lightbox: la foto crece desde la tarjeta con fade + blur; cierra con clic o Esc.
function Lightbox({ item, onClose }) {
  const reduced = useReducedMotion();
  useEffect(() => {
    if (!item) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [item, onClose]);

  const dur = reduced ? 0 : 0.5;
  return (
    <AnimatePresence>
      {item && (
        <motion.div
          className="lightbox"
          role="dialog"
          aria-modal="true"
          aria-label={item.alt}
          onClick={onClose}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: dur * 0.7, ease: EASE }}
        >
          <motion.figure
            className="lightbox-figure"
            onClick={(e) => e.stopPropagation()}
            initial={{ opacity: 0, scale: 0.88, y: 24, filter: 'blur(12px)' }}
            animate={{ opacity: 1, scale: 1, y: 0, filter: 'blur(0px)' }}
            exit={{ opacity: 0, scale: 0.94, y: 12, filter: 'blur(8px)' }}
            transition={{ duration: dur, ease: EASE }}
          >
            <img src={item.src} alt={item.alt} />
            <figcaption>
              <span className="lightbox-title">{item.title}</span>
              {item.sub && <span className="lightbox-sub">{item.sub}</span>}
            </figcaption>
          </motion.figure>
          <button className="lightbox-close" onClick={onClose} aria-label="Cerrar">×</button>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

function Nosotros() {
  const [active, setActive] = useState(null);
  const close = () => setActive(null);
  return (
    <section className="section-pad section-wrap" id="nosotros" aria-label="Nosotros">
      <motion.div className="section-head" {...fadeRiseInView(0)}>
        <div className="eyebrow"><span className="eyebrow-dot" />Quiénes somos</div>
        <h2>Fly Media.</h2>
      </motion.div>

      <motion.p className="nosotros-intro" {...fadeRiseInView(0.07)}>
        Somos una productora audiovisual en Chihuahua. Hacemos video para marcas
        que necesitan verse serias sin verse frías: corporativo, comercial,
        inmobiliario y redes. Criterio propio y una obsesión por que cada pieza
        tenga una razón de existir.
      </motion.p>

      <motion.div className="eyebrow eyebrow-center team-lead-label" {...fadeRiseInView(0.1)}>
        <span className="eyebrow-dot" />Al frente
      </motion.div>

      <div className="team-grid">
        {TEAM.map((m, i) => (
          <motion.figure key={m.name} className="team-card" {...fadeRiseInView(0.14 + i * 0.08)}>
            <div className="team-photo">
              {m.img
                ? <button type="button" className="photo-btn"
                    onClick={() => setActive({ src: m.img, alt: `${m.name} — ${m.role}`, title: m.name, sub: m.role })}
                    aria-label={`Ver foto de ${m.name}`}>
                    <img src={m.img} alt={`${m.name} — ${m.role}`} />
                  </button>
                : <div className="team-photo-empty" role="img" aria-label={`Foto de ${m.name}, próximamente`}>
                    <span className="team-initials">{initials(m.name)}</span>
                    <span className="video-slot-text">Foto · Próximamente</span>
                  </div>}
            </div>
            <figcaption className="team-foot">
              <span className="team-name">{m.name}</span>
              <span className="team-role">{m.role}</span>
            </figcaption>
          </motion.figure>
        ))}
      </div>

      <div className="gallery-grid">
        {GALLERY.map((g, i) => (
          <motion.div key={i} className={`gallery-item${g ? ' has-img' : ''}`} {...fadeRiseInView(0.3 + i * 0.06)}>
            {g
              ? <button type="button" className="photo-btn"
                  onClick={() => setActive({ src: g, alt: `Detrás de cámaras ${i + 1}`, title: 'Detrás de cámaras', sub: `${i + 1} / ${GALLERY.length}` })}
                  aria-label={`Ver foto detrás de cámaras ${i + 1}`}>
                  <img src={g} alt={`Detrás de cámaras ${i + 1}`} loading="lazy" />
                </button>
              : <span className="video-slot-text">Detrás de cámaras · Próximamente</span>}
          </motion.div>
        ))}
      </div>

      <Lightbox item={active} onClose={close} />
    </section>
  );
}

// ---------- Gradient Bars (fondo animado) ----------
// Barras verticales con gradiente ember, altas en los extremos y bajas al
// centro, pulsando en loop. Puro CSS + inline styles; sin dependencias.
function GradientBars({
  numBars = 13,
  gradientFrom = 'rgba(242, 106, 31, 0.42)',
  gradientTo = 'transparent',
  animationDuration = 2.8,
  className = '',
}) {
  const scaleFor = (index, total) => {
    const distanceFromCenter = Math.abs(index / (total - 1) - 0.5);
    const minHeight = 30, maxHeight = 100;
    return (minHeight + (maxHeight - minHeight) * Math.pow(distanceFromCenter * 2, 1.2)) / 100;
  };

  return (
    <div className={`gradient-bars ${className}`.trim()} aria-hidden="true">
      <div className="gradient-bars-row">
        {Array.from({ length: numBars }).map((_, i) => {
          const scale = scaleFor(i, numBars);
          return (
            <div
              key={i}
              className="gradient-bar"
              style={{
                flex: `1 0 calc(100% / ${numBars})`,
                maxWidth: `calc(100% / ${numBars})`,
                background: `linear-gradient(to top, ${gradientFrom}, ${gradientTo})`,
                transform: `scaleY(${scale})`,
                animationDelay: `${i * 0.12}s`,
                '--initial-scale': scale,
                '--bar-dur': `${animationDuration}s`,
              }}
            />
          );
        })}
      </div>
    </div>
  );
}

// ---------- CTA Final ----------
function CtaFinal() {
  return (
    <section className="cta-final" id="contacto" aria-label="Contacto">
      <GradientBars />
      <div className="cta-band-inner">
        <motion.div key="ceb" className="eyebrow eyebrow-center" {...fadeRiseInView(0)}>
          <span className="eyebrow-dot" />Siguiente proyecto
        </motion.div>
        <motion.h2 key="ch" {...fadeRiseInView(0.07)}>
          ¿Listos para<br/>elevar tu marca?
        </motion.h2>
        <motion.p key="cp" {...fadeRiseInView(0.14)}>
          Cuéntanos el proyecto. Te armamos la propuesta.
        </motion.p>
        <motion.div key="cb" className="cta-btn-row" {...fadeRiseInView(0.21)}>
          <a href="/cotizador" className="btn btn-primary">
            Cotiza tu proyecto <ArrowRight size={16}/>
          </a>
          <a href={waLink()} target="_blank" rel="noopener" className="btn btn-ghost btn-wa">
            <WhatsAppIcon size={17} /> Mándanos un WhatsApp
          </a>
        </motion.div>
        <motion.div key="cf" className="cta-foot" {...fadeRiseInView(0.28)}>
          Respuesta en 24 h <span className="sep">·</span> Sin compromiso
        </motion.div>
      </div>
    </section>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="footer" id="footer">
      <div className="footer-grid">
        <div className="footer-col footer-brand">
          <a href="#top" className="nav-logo nav-logo-lg" aria-label="Fly Media — Inicio">
            <img className="logo-mark" src="assets/logo-icon.png" alt="" />
            <img className="logo-wordmark" src="assets/logo-wordmark-dark.png" alt="" />
          </a>
          <p>Productora audiovisual.<br/>Chihuahua, México.</p>
        </div>
        <div className="footer-col">
          <h4>Servicios</h4>
          <ul>
            <li><a href="#servicios">Corporativo</a></li>
            <li><a href="#servicios">Producción con IA</a></li>
            <li><a href="#servicios">Inmobiliario</a></li>
            <li><a href="#servicios">Redes Sociales</a></li>
            <li><a href="#servicios">Tomas aéreas</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Empresa</h4>
          <ul>
            <li><a href="#nosotros">Nosotros</a></li>
            <li><a href="#trabajo">Trabajo</a></li>
            <li><a href="#contacto">Contacto</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Conecta</h4>
          <ul>
            <li><a href="https://www.instagram.com/flymediacuu/" target="_blank" rel="noopener" aria-label="Instagram"><Instagram size={16}/> Instagram</a></li>
            <li><a href={waLink()} target="_blank" rel="noopener" aria-label="WhatsApp"><WhatsAppIcon size={16}/> WhatsApp</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bar">
        <div className="copy">© 2026 Fly Media · Bold presence. Precise impact.</div>
        <div className="legal">
          <a href="/legal#aviso-de-privacidad">Aviso de Privacidad</a>
          <a href="/legal#terminos">Términos</a>
        </div>
      </div>
    </footer>
  );
}

// ---------- WhatsApp FAB ----------
function WhatsAppFab() {
  return (
    <a
      href={waLink()}
      target="_blank"
      rel="noopener"
      className="wa-fab"
      aria-label="Escríbenos por WhatsApp"
      title="Escríbenos por WhatsApp"
    >
      <WhatsAppIcon size={27} />
    </a>
  );
}

// ---------- App ----------
function App() {
  return (
    <>
      <Nav />
      <main>
        <Hero />
        <Problema />
        <Servicios />
        <Trabajo />
        <Nosotros />
        <Clientes />
        <CtaFinal />
      </main>
      <Footer />
      <WhatsAppFab />
    </>
  );
}

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