/* =====================================================================
   Core UI — Logo, MagButton, Pill, SectionHead, Nav, Footer
   Responsive-first. Mobile menu. Time-of-day aware.
   ===================================================================== */

const { useEffect, useRef, useState, useLayoutEffect } = React;

// -------------- MagButton with magnetic pull --------------
function MagButton({ children, variant = 'primary', size = 'md', onClick, href, style = {}, full, iconAfter = '→', noArrow }) {
  const ref = useRef(null);
  const labelRef = useRef(null);
  const [pressed, setPressed] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    if (window.matchMedia('(hover: none)').matches) return; // skip magnetic on touch
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width/2, cy = r.top + r.height/2;
      const dx = e.clientX - cx, dy = e.clientY - cy;
      const d = Math.hypot(dx, dy);
      const range = 110;
      if (d < range) {
        const f = (1 - d/range) * 0.30;
        el.style.transform = `translate(${dx*f}px,${dy*f}px)`;
        if (labelRef.current) labelRef.current.style.transform = `translate(${dx*f*0.6}px,${dy*f*0.6}px)`;
      } else {
        el.style.transform = '';
        if (labelRef.current) labelRef.current.style.transform = '';
      }
    };
    const onLeave = () => { el.style.transform = ''; if (labelRef.current) labelRef.current.style.transform = ''; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseleave', onLeave);
    return () => { window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseleave', onLeave); };
  }, []);
  const sizes = {
    sm: { padding: '8px 14px', fontSize: 11 },
    md: { padding: '14px 22px', fontSize: 13 },
    lg: { padding: '18px 28px', fontSize: 14 },
  };
  const base = {
    display: full ? 'flex' : 'inline-flex', width: full ? '100%' : undefined,
    justifyContent: 'center',
    alignItems: 'center', gap: 10,
    fontFamily: 'var(--font-mono)', fontWeight: 500,
    letterSpacing: '0.12em', textTransform: 'uppercase',
    border: '1px solid var(--border-strong)',
    cursor: 'pointer', userSelect: 'none',
    transition: 'transform .25s var(--ease-out), background .18s, color .18s, border-color .18s, box-shadow .25s',
    position: 'relative', overflow: 'hidden',
    textDecoration: 'none',
    ...sizes[size],
    ...style,
  };
  const variants = {
    primary: { background: pressed ? 'var(--fg-1)' : 'var(--accent)', color: pressed ? 'var(--bg)' : 'var(--accent-ink)', border: '1px solid var(--accent)', boxShadow: pressed ? 'none' : '0 0 40px -12px color-mix(in oklab, var(--accent) 80%, transparent)' },
    ghost: { background: 'transparent', color: 'var(--fg-1)' },
    ink: { background: 'var(--fg-1)', color: 'var(--bg)', border: '1px solid var(--fg-1)' },
  };
  const Tag = href ? 'a' : 'button';
  return (
    <Tag ref={ref} href={href} onClick={onClick}
      onMouseDown={() => setPressed(true)} onMouseUp={() => setPressed(false)} onMouseLeave={() => setPressed(false)}
      style={{ ...base, ...variants[variant] }}>
      <span ref={labelRef} style={{ position: 'relative', zIndex: 1, display: 'inline-flex', alignItems: 'center', gap: 10, transition: 'transform .25s var(--ease-out)' }}>
        {children}{!noArrow && iconAfter && <span style={{ opacity: .75 }}>{iconAfter}</span>}
      </span>
    </Tag>
  );
}

// -------------- Pill --------------
function Pill({ children, dot, color }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '5px 10px',
      border: '1px solid var(--border-strong)',
      borderRadius: 999,
      fontFamily: 'var(--font-mono)', fontSize: 10,
      letterSpacing: '0.14em', textTransform: 'uppercase',
      color: color || 'var(--fg-2)', background: 'color-mix(in oklab, var(--bg) 40%, transparent)',
      backdropFilter: 'blur(6px)',
    }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--accent)', boxShadow: '0 0 8px var(--accent)', animation: 'mwBreathe 2s ease-in-out infinite' }}/>}
      {children}
    </span>
  );
}

// -------------- SectionHead --------------
function SectionHead({ eyebrow, title, kicker, right }) {
  const ref = useRef(null);
  useReveal(ref);
  return (
    <div ref={ref} className="mw-reveal" style={{
      display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
      gap: 24, marginBottom: 40, borderBottom: '1px solid var(--border)', paddingBottom: 20,
      flexWrap: 'wrap',
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, flex: '1 1 300px', minWidth: 0 }}>
        {eyebrow && <div className="mw-eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 6, height: 6, background: 'var(--accent)', display: 'inline-block' }}/>
          {eyebrow}
        </div>}
        <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 'clamp(32px, 5.2vw, 64px)', fontWeight: 500, lineHeight: 0.95, letterSpacing: '-0.035em' }}>{title}</h2>
        {kicker && <div style={{ color: 'var(--fg-3)', maxWidth: 640, fontSize: 'clamp(14px, 1.6vw, 17px)', lineHeight: 1.5 }}>{kicker}</div>}
      </div>
      {right && <div style={{ flexShrink: 0 }}>{right}</div>}
    </div>
  );
}

// -------------- useReveal — scroll-triggered reveal --------------
function useReveal(ref, opts = {}) {
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          el.classList.add('is-in');
          io.unobserve(el);
        }
      });
    }, { threshold: opts.threshold || 0.15, rootMargin: opts.rootMargin || '0px 0px -10% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
}

// -------------- Logo --------------
function Logo({ size = 28, wordmark = true }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--fg-1)' }}>
      <svg width={size} height={size} viewBox="0 0 68 68" fill="none" shapeRendering="geometricPrecision" style={{ flexShrink: 0 }}>
        <circle cx="34" cy="34" r="31" stroke="currentColor" strokeWidth="2"/>
        <path d="M19 48 L19 22 L34 35 L49 22 L49 48" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
        <path d="M13 22 L55 22" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round"/>
        <circle cx="34" cy="34" r="1.75" fill="var(--accent)"/>
      </svg>
      {wordmark && (
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13, letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>MIDWEST&nbsp;TECHNOLOGIES</span>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 8, letterSpacing: '0.22em', opacity: 0.6, marginTop: 4 }}>OKLAHOMA&nbsp;STATE&nbsp;·&nbsp;STUDIO</span>
        </div>
      )}
    </div>
  );
}

// -------------- Time-of-day picker --------------
function TodIndicator({ tod, setTod, auto, setAuto }) {
  const labels = { night: '◐ NIGHT', sunrise: '◓ SUNRISE', day: '◑ DAY', sunset: '◒ SUNSET' };
  const [open, setOpen] = useState(false);
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(!open)} style={{
        padding: '6px 10px', background: 'transparent',
        border: '1px solid var(--border-strong)', color: 'var(--fg-2)',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em',
        cursor: 'pointer', textTransform: 'uppercase',
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        <span style={{ width: 6, height: 6, background: 'var(--accent)', display: 'inline-block', boxShadow: '0 0 8px var(--accent)' }}/>
        {labels[tod]} {auto && <span style={{ opacity: .5 }}>· AUTO</span>}
      </button>
      {open && (
        <div style={{ position: 'absolute', right: 0, top: 'calc(100% + 6px)', background: 'var(--bg-elev-2)', border: '1px solid var(--border-strong)', zIndex: 100, minWidth: 180, padding: 6, boxShadow: '0 20px 48px rgba(0,0,0,0.4)' }}>
          <div style={{ padding: '6px 10px', fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.16em', color: 'var(--fg-4)' }}>— THEME</div>
          {Object.entries(labels).map(([k, l]) => (
            <button key={k} onClick={() => { setTod(k); setAuto(false); setOpen(false); }} style={{
              display: 'flex', width: '100%', padding: '8px 10px', background: tod === k ? 'var(--accent)' : 'transparent', color: tod === k ? 'var(--accent-ink)' : 'var(--fg-2)',
              border: 'none', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', cursor: 'pointer', textAlign: 'left',
            }}>{l}</button>
          ))}
          <button onClick={() => { setAuto(true); setOpen(false); }} style={{
            display: 'flex', width: '100%', padding: '8px 10px', background: auto ? 'var(--fg-1)' : 'transparent', color: auto ? 'var(--bg)' : 'var(--fg-3)',
            border: 'none', borderTop: '1px solid var(--border)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', cursor: 'pointer', textAlign: 'left', marginTop: 4,
          }}>{auto ? '✓ ' : '↻ '}AUTO (BY TIME)</button>
        </div>
      )}
    </div>
  );
}

// -------------- Nav with mobile menu --------------
function Nav({ tod, setTod, auto, setAuto }) {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const links = ['Work', 'Services', 'SEO', 'AI', 'Contact'];
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: scrolled ? '10px 20px' : '16px 24px',
      background: 'color-mix(in oklab, var(--bg) 82%, transparent)',
      backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
      borderBottom: '1px solid var(--border)',
      transition: 'padding .25s var(--ease-out)',
    }}>
      <a href="#top" style={{ textDecoration: 'none' }}><Logo/></a>
      <nav className="mw-nav-desktop" style={{ display: 'flex', gap: 28 }}>
        {links.map(l => (
          <a key={l} href={`#${l.toLowerCase()}`} style={{
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase',
            color: 'var(--fg-3)', textDecoration: 'none',
            transition: 'color .15s', position: 'relative',
          }} onMouseEnter={e => e.currentTarget.style.color = 'var(--fg-1)'}
             onMouseLeave={e => e.currentTarget.style.color = 'var(--fg-3)'}>{l}</a>
        ))}
      </nav>
      <div className="mw-nav-desktop" style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
        <TodIndicator tod={tod} setTod={setTod} auto={auto} setAuto={setAuto}/>
        <MagButton size="sm" variant="primary" href="#contact">Get a free quote</MagButton>
      </div>
      <button className="mw-nav-mobile" onClick={() => setOpen(!open)} aria-label="Menu" style={{
        display: 'none',
        width: 40, height: 40, padding: 0, background: 'transparent',
        border: '1px solid var(--border-strong)', cursor: 'pointer',
        flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 4,
      }}>
        <span style={{ width: 18, height: 1.5, background: 'var(--fg-1)', transform: open ? 'translateY(2.75px) rotate(45deg)' : 'none', transition: 'transform .3s var(--ease-out)' }}/>
        <span style={{ width: 18, height: 1.5, background: 'var(--fg-1)', transform: open ? 'translateY(-2.75px) rotate(-45deg)' : 'none', transition: 'transform .3s var(--ease-out)' }}/>
      </button>
      {/* Mobile drawer */}
      <div style={{
        position: 'fixed', inset: '61px 0 0 0', zIndex: 49,
        background: 'var(--bg)', padding: 24,
        display: 'flex', flexDirection: 'column', gap: 0,
        transform: open ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform .35s var(--ease-out)',
        pointerEvents: open ? 'auto' : 'none',
      }}>
        {links.map((l, i) => (
          <a key={l} href={`#${l.toLowerCase()}`} onClick={() => setOpen(false)} style={{
            padding: '20px 0', borderBottom: '1px solid var(--border)',
            fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em',
            color: 'var(--fg-1)', textDecoration: 'none',
            opacity: open ? 1 : 0, transform: open ? 'translateX(0)' : 'translateX(20px)',
            transition: `opacity .4s ${i*0.05+0.1}s, transform .4s var(--ease-out) ${i*0.05+0.1}s`,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <span>{l}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-4)' }}>0{i+1} →</span>
          </a>
        ))}
        <div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <TodIndicator tod={tod} setTod={setTod} auto={auto} setAuto={setAuto}/>
          <MagButton full variant="primary" size="lg" href="#contact" onClick={() => setOpen(false)}>Get a free quote</MagButton>
        </div>
        <div style={{ marginTop: 'auto', paddingTop: 32, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', color: 'var(--fg-4)' }}>
          MIDWEST TECHNOLOGIES · OKLAHOMA STATE · 2026
        </div>
      </div>
    </header>
  );
}

Object.assign(window, { MagButton, Pill, SectionHead, Logo, Nav, TodIndicator, useReveal });
