// Primitive UI components shared across sections.
const { motion, useScroll, useTransform, useInView, useMotionValue, useSpring, AnimatePresence } = window.framerMotion || {};

// Detect prefers-reduced-motion
const prefersReducedMotion = typeof window !== 'undefined' && window.matchMedia
  ? window.matchMedia('(prefers-reduced-motion: reduce)').matches
  : false;

// ---------- Buttons ----------
function Button({ variant = 'primary', size = 'md', children, className = '', as: Tag = 'button', magnetic = false, ...rest }) {
  const sizes = {
    sm: 'h-9 px-3.5 text-sm gap-1.5',
    md: 'h-11 px-5 text-[15px] gap-2',
    lg: 'h-12 px-6 text-[15px] gap-2',
  };
  const variants = {
    primary: 'bg-cyan-500 hover:bg-cyan-400 text-white shadow-[0_4px_24px_-6px_rgba(14,165,233,0.6)] hover:shadow-[0_8px_32px_-4px_rgba(14,165,233,0.7)]',
    'primary-dark': 'bg-brand-600 hover:bg-brand-500 text-white',
    secondary: 'bg-ink-100 dark:bg-ink-800 hover:bg-ink-200 dark:hover:bg-ink-700 text-ink-800 dark:text-ink-100 border border-ink-200 dark:border-ink-700',
    ghost: 'text-ink-700 dark:text-ink-200 hover:bg-ink-100 dark:hover:bg-ink-800',
    outline: 'border border-ink-200 dark:border-ink-700 hover:bg-ink-50 dark:hover:bg-ink-800 text-ink-800 dark:text-ink-100',
  };

  const ref = React.useRef(null);
  const x = useMotionValue ? useMotionValue(0) : null;
  const y = useMotionValue ? useMotionValue(0) : null;
  const sx = x && useSpring ? useSpring(x, { stiffness: 200, damping: 18 }) : 0;
  const sy = y && useSpring ? useSpring(y, { stiffness: 200, damping: 18 }) : 0;

  const handleMove = (e) => {
    if (!magnetic || !ref.current || prefersReducedMotion) return;
    const rect = ref.current.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    const dx = (e.clientX - cx) * 0.25;
    const dy = (e.clientY - cy) * 0.35;
    x.set(Math.max(-6, Math.min(6, dx)));
    y.set(Math.max(-4, Math.min(4, dy)));
  };
  const handleLeave = () => { if (x && y) { x.set(0); y.set(0); } };

  const Comp = magnetic && motion ? motion[Tag] || motion.button : Tag;
  const motionProps = magnetic && motion ? { style: { x: sx, y: sy }, onMouseMove: handleMove, onMouseLeave: handleLeave } : {};

  return (
    <Comp
      ref={ref}
      className={`inline-flex items-center justify-center font-medium rounded-xl transition-all duration-200 active:scale-[0.97] focus-visible:outline-cyan-400 ${sizes[size]} ${variants[variant]} ${className}`}
      {...motionProps}
      {...rest}
    >
      {children}
    </Comp>
  );
}

// ---------- Eyebrow / Badge ----------
function Eyebrow({ children, className = '' }) {
  return <div className={`eyebrow text-cyan-500 dark:text-cyan-400 ${className}`}>{children}</div>;
}

function Pill({ children, tone = 'default', className = '' }) {
  const tones = {
    default: 'bg-ink-100 dark:bg-ink-800 text-ink-700 dark:text-ink-200 border-ink-200/60 dark:border-ink-700',
    cyan: 'bg-cyan-500/10 text-cyan-600 dark:text-cyan-300 border-cyan-500/20',
    emerald: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-300 border-emerald-500/20',
    amber: 'bg-amber-500/10 text-amber-600 dark:text-amber-300 border-amber-500/20',
    rose: 'bg-rose-500/10 text-rose-600 dark:text-rose-300 border-rose-500/20',
    brand: 'bg-brand-600/10 text-brand-600 dark:text-brand-200 border-brand-500/20',
  };
  return <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[11px] font-medium border ${tones[tone]} ${className}`}>{children}</span>;
}

// ---------- Reveal on scroll ----------
function Reveal({ children, delay = 0, y = 20, className = '', as: Tag = 'div' }) {
  if (!motion) return <Tag className={className}>{children}</Tag>;
  const M = motion[Tag] || motion.div;
  return (
    <M
      className={className}
      initial={{ opacity: 0, y: prefersReducedMotion ? 0 : y }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: '-80px' }}
      transition={{ duration: prefersReducedMotion ? 0.2 : 0.6, delay, ease: [0.16, 1, 0.3, 1] }}
    >
      {children}
    </M>
  );
}

// ---------- Stagger group ----------
function Stagger({ children, delayChildren = 0, staggerChildren = 0.06, className = '' }) {
  if (!motion) return <div className={className}>{children}</div>;
  return (
    <motion.div
      className={className}
      initial="hidden"
      whileInView="show"
      viewport={{ once: true, margin: '-80px' }}
      variants={{
        hidden: {},
        show: { transition: { delayChildren, staggerChildren } },
      }}
    >
      {children}
    </motion.div>
  );
}
function StaggerItem({ children, className = '', y = 20, as: Tag = 'div' }) {
  if (!motion) return <Tag className={className}>{children}</Tag>;
  const M = motion[Tag] || motion.div;
  return (
    <M
      className={className}
      variants={{
        hidden: { opacity: 0, y: prefersReducedMotion ? 0 : y },
        show:   { opacity: 1, y: 0, transition: { duration: 0.5, ease: [0.16, 1, 0.3, 1] } },
      }}
    >
      {children}
    </M>
  );
}

// ---------- Scroll progress bar ----------
function ScrollProgress() {
  if (!useScroll || !motion) return null;
  const { scrollYProgress } = useScroll();
  const scale = useTransform ? useTransform(scrollYProgress, [0, 1], [0, 1]) : 0;
  return (
    <motion.div
      className="fixed left-0 top-0 right-0 h-[2px] origin-left z-[60]"
      style={{
        scaleX: scale,
        background: 'linear-gradient(90deg, #0EA5E9 0%, #3DD0FF 50%, #0EA5E9 100%)',
      }}
    />
  );
}

// ---------- CountUp ----------
function CountUp({ to, duration = 1800, format = (v) => v.toLocaleString('pt-BR'), suffix = '' }) {
  const [val, setVal] = React.useState(0);
  const ref = React.useRef(null);
  const inView = useInView ? useInView(ref, { once: true, margin: '-80px' }) : false;

  React.useEffect(() => {
    if (!inView) return;
    if (prefersReducedMotion) { setVal(to); return; }
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(eased * to));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [inView, to, duration]);

  return <span ref={ref} className="tabular">{format(val)}{suffix}</span>;
}

// ---------- Section wrapper ----------
const Section = React.forwardRef(function Section({ id, className = '', children, ...rest }, ref) {
  return (
    <section ref={ref} id={id} className={`relative ${className}`} {...rest}>
      {children}
    </section>
  );
});

// ---------- Container ----------
function Container({ children, className = '', size = 'default' }) {
  const sizes = { default: 'max-w-7xl', narrow: 'max-w-5xl', wide: 'max-w-[88rem]' };
  return <div className={`${sizes[size]} mx-auto px-5 sm:px-8 ${className}`}>{children}</div>;
}

// ---------- Word-by-word animated heading ----------
function AnimatedHeading({ text, className = '', as: Tag = 'h1' }) {
  if (!motion) return <Tag className={className}>{text}</Tag>;
  const words = text.split(' ');
  const M = motion[Tag] || motion.h1;
  return (
    <M
      className={className}
      initial="hidden"
      animate="show"
      variants={{ hidden: {}, show: { transition: { staggerChildren: prefersReducedMotion ? 0 : 0.04, delayChildren: 0.1 } } }}
    >
      {words.map((w, i) => (
        <motion.span
          key={i}
          className="inline-block"
          variants={{
            hidden: { opacity: 0, y: prefersReducedMotion ? 0 : 30, filter: 'blur(8px)' },
            show:   { opacity: 1, y: 0, filter: 'blur(0px)', transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1] } },
          }}
        >
          {w}{i < words.length - 1 ? '\u00A0' : ''}
        </motion.span>
      ))}
    </M>
  );
}

// Split version: animates pre-text words then a highlighted phrase as a single gradient block.
function AnimatedHeadingSplit({ pre, highlight, className = '', as: Tag = 'h1' }) {
  if (!motion) return <Tag className={className}>{pre} <span className="hl">{highlight}</span></Tag>;
  const preWords = pre.split(' ');
  const M = motion[Tag] || motion.h1;
  const variants = {
    hidden: { opacity: 0, y: prefersReducedMotion ? 0 : 30, filter: 'blur(8px)' },
    show:   { opacity: 1, y: 0, filter: 'blur(0px)', transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1] } },
  };
  return (
    <M
      className={className}
      initial="hidden"
      animate="show"
      variants={{ hidden: {}, show: { transition: { staggerChildren: prefersReducedMotion ? 0 : 0.035, delayChildren: 0.1 } } }}
    >
      {preWords.map((w, i) => (
        <motion.span key={i} className="inline-block" variants={variants}>
          {w}{'\u00A0'}
        </motion.span>
      ))}
      <motion.span className="inline-block hl" variants={variants}>{highlight}</motion.span>
    </M>
  );
}

// ---------- Mockup chrome (browser-style) ----------
function MockupChrome({ children, label, className = '', dark = true }) {
  return (
    <div className={`relative overflow-hidden rounded-2xl ${dark ? 'bg-ink-900 border border-ink-700/60' : 'bg-white border border-ink-200'} shadow-card-dark ${className}`}>
      <div className={`flex items-center gap-2 px-4 h-9 border-b ${dark ? 'border-ink-700/60 bg-ink-900' : 'border-ink-200 bg-ink-50'}`}>
        <div className="flex gap-1.5">
          <span className="w-2.5 h-2.5 rounded-full bg-rose-500/70"/>
          <span className="w-2.5 h-2.5 rounded-full bg-amber-500/70"/>
          <span className="w-2.5 h-2.5 rounded-full bg-emerald-500/70"/>
        </div>
        {label && <div className={`flex-1 text-center text-[11px] ${dark ? 'text-ink-400' : 'text-ink-500'} font-mono`}>{label}</div>}
      </div>
      {children}
    </div>
  );
}

window.UI = { Button, Eyebrow, Pill, Reveal, Stagger, StaggerItem, ScrollProgress, CountUp, Section, Container, AnimatedHeading, AnimatedHeadingSplit, MockupChrome, prefersReducedMotion };
