// Capabilities section — min-h-screen, full-bleed video bg, 3 cards

const { motion: capMotion } = window.Motion;
const { useEffect: capUseEffect, useRef: capUseRef, useState: capUseState } = React;
const CAP_VIDEO = "https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260418_094631_d30ab262-45ee-4b7d-99f3-5d5848c8ef13.mp4";

// whileInView is unreliable on the framer-motion 10.18.0 UMD build. Use a
// hook-driven IntersectionObserver that flips an `animate` prop instead.
function useInViewOnce(threshold = 0.2) {
  const ref = capUseRef(null);
  const [shown, setShown] = capUseState(false);
  capUseEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setShown(true);
            io.disconnect();
          }
        });
      },
      { threshold }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, shown];
}

const fadeUp = (delay = 0, shown = true) => ({
  initial: { filter: 'blur(10px)', opacity: 0, y: 20 },
  animate: shown
    ? { filter: 'blur(0px)', opacity: 1, y: 0 }
    : { filter: 'blur(10px)', opacity: 0, y: 20 },
  transition: { duration: 0.8, ease: 'easeOut', delay },
});

function CapTag({ children }) {
  return (
    <span className="liquid-glass rounded-full px-3 py-1 text-[11px] text-white/90 font-body whitespace-nowrap">
      {children}
    </span>
  );
}

function CapCard({ icon, tags, title, body, delay }) {
  const [ref, shown] = useInViewOnce(0.15);
  return (
    <capMotion.article
      ref={ref}
      {...fadeUp(delay, shown)}
      className="liquid-glass p-8 min-h-[440px] flex flex-col items-start text-left"
      style={{ borderRadius: '1.5rem' }}
    >
      {/* Large gold icon */}
      <div
        className="liquid-glass mb-8 flex items-center justify-center shrink-0"
        style={{ borderRadius: '1.25rem', width: 84, height: 84 }}
      >
        <span className="relative z-10 inline-flex" style={{ filter: 'drop-shadow(0 0 10px rgba(212,168,82,0.35))' }}>
          {icon}
        </span>
      </div>

      {/* Big title */}
      <h3
        className="font-heading italic text-white leading-none"
        style={{ fontSize: 'clamp(56px, 6.5vw, 84px)', letterSpacing: '-2px' }}
      >
        {title}
      </h3>

      {/* Tag pills */}
      <div className="flex flex-wrap gap-2 mt-5">
        {tags.map((t) => (
          <CapTag key={t}>{t}</CapTag>
        ))}
      </div>

      {/* Body */}
      <p className="mt-6 text-[15px] text-white/85 font-body font-light leading-relaxed max-w-[34ch]">
        {body}
      </p>
    </capMotion.article>
  );
}

function Capabilities() {
  return (
    <section id="la-app" className="relative w-full min-h-screen overflow-hidden bg-black scroll-mt-24">
      <FadingVideo
        src={CAP_VIDEO}
        className="absolute inset-0 w-full h-full object-cover z-0"
      />

      <CapContent />
    </section>
  );
}

function CapContent() {
  const [kickerRef, kickerShown] = useInViewOnce(0.2);
  const [headRef, headShown] = useInViewOnce(0.2);
  return (
    <div className="relative z-10 px-8 md:px-16 lg:px-20 pt-24 pb-10 flex flex-col min-h-screen">
      <div className="mb-auto">
        <capMotion.div ref={kickerRef} {...fadeUp(0, kickerShown)}>
          <p className="text-sm font-body text-white/80 mb-6">// Cómo funciona</p>
        </capMotion.div>

        <capMotion.h2
          ref={headRef}
          {...fadeUp(0.1, headShown)}
          className="font-heading italic text-white text-6xl md:text-7xl lg:text-[6rem]"
          style={{ lineHeight: 0.9, letterSpacing: '-3px' }}
        >
          Tu energía,<br />explicada.
        </capMotion.h2>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mt-16">
        <CapCard
          delay={0.0}
          icon={<FeatClockCheck size={48} />}
          tags={['20 seg', 'Automático']}
          title="Medí"
          body="Respondé 3 preguntas en 20 segundos cada mañana o conectá tu wearable y WuClock lo hace solo."
        />
        <CapCard
          delay={0.12}
          icon={<FeatBrainSpark size={48} />}
          tags={['MTC', 'Personalizado']}
          title="Entendé"
          body="WuClock te explica por qué te sentís como te sentís hoy. En tu idioma. Sin jerga técnica. Con la precisión de 5.000 años de medicina oriental."
        />
        <CapCard
          delay={0.24}
          icon={<FeatLotus size={48} />}
          tags={['8 min', 'Tu elemento']}
          title="Actuá"
          body="Un ritual personalizado según tu elemento, tu clasificación del día y cómo dormiste anoche."
        />
      </div>
    </div>
  );
}

function CapStatsRow() {
  const [ref, shown] = useInViewOnce(0.2);
  const stats = [
    { num: '200+',         label: 'Usuarios activos' },
    { num: '5.000 años',   label: 'De sabiduría MTC' },
    { num: 'Latam',        label: 'Hecho desde Argentina' },
  ];
  return (
    <capMotion.div
      ref={ref}
      {...fadeUp(0.1, shown)}
      className="mt-12 liquid-glass flex flex-col md:flex-row items-stretch justify-around gap-2 md:gap-0 px-6 py-6 md:py-5"
      style={{ borderRadius: '1.5rem' }}
    >
      {stats.map((s, i) => (
        <React.Fragment key={s.label}>
          {i > 0 && (
            <div
              className="hidden md:block self-stretch w-px"
              style={{ background: 'linear-gradient(180deg, transparent, rgba(255,255,255,0.18), transparent)' }}
            />
          )}
          <div className="flex-1 flex flex-col items-center justify-center text-center">
            <div
              className="font-heading italic text-white leading-none"
              style={{ fontSize: 'clamp(32px, 3.6vw, 44px)', letterSpacing: '-1px' }}
            >
              {s.num}
            </div>
            <div className="mt-2 text-xs text-white/70 font-body font-light" style={{ letterSpacing: '0.12em', textTransform: 'uppercase' }}>
              {s.label}
            </div>
          </div>
        </React.Fragment>
      ))}
    </capMotion.div>
  );
}

Object.assign(window, { Capabilities, useInViewOnce, fadeUp });
