/* ============================================================
   WorkStay — shared UI components
   exports: NavBar, FooterBar, Btn, Badge, Pill, WorkScore,
            MetricBar, RadialStat, SectionHead, Stagger
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ---------------- Buttons ---------------- */
function Btn({ children, variant = 'primary', size = 'md', icon, onClick, style = {}, type }) {
  const [hov, setHov] = useState(false);
  const sizes = {
    sm: { padding: '9px 16px', fontSize: 13 },
    md: { padding: '13px 22px', fontSize: 14.5 },
    lg: { padding: '17px 30px', fontSize: 16 },
  };
  const base = {
    display: 'inline-flex', alignItems: 'center', gap: 9, borderRadius: 999,
    fontFamily: 'var(--sans)', fontWeight: 500, letterSpacing: '0.01em', border: '1px solid transparent',
    transition: 'all .35s cubic-bezier(.16,1,.3,1)', whiteSpace: 'nowrap', ...sizes[size],
  };
  const variants = {
    primary: { background: hov ? 'var(--violet-soft)' : 'var(--violet)', color: '#fff',
      boxShadow: hov ? '0 14px 40px -10px var(--violet-glow)' : '0 8px 24px -12px var(--violet-glow)',
      transform: hov ? 'translateY(-2px)' : 'none' },
    glass: { background: hov ? 'rgba(255,255,255,0.14)' : 'rgba(255,255,255,0.07)', color: 'var(--text)',
      borderColor: 'var(--line-2)', backdropFilter: 'blur(20px)', transform: hov ? 'translateY(-2px)' : 'none' },
    ghost: { background: 'transparent', color: hov ? 'var(--text)' : 'var(--text-dim)', borderColor: 'transparent' },
    line: { background: 'transparent', color: 'var(--text)', borderColor: hov ? 'var(--text-dim)' : 'var(--line-2)',
      transform: hov ? 'translateY(-2px)' : 'none' },
  };
  return (
    <button type={type} onClick={onClick} onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ ...base, ...variants[variant], ...style }}>
      {children}
      {icon && <Icon name={icon} size={size === 'lg' ? 19 : 17} />}
    </button>
  );
}

/* ---------------- Badge / Pill ---------------- */
function Badge({ icon, children, glow = false, style = {} }) {
  return (
    <span className="glass" style={{ display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '8px 14px', borderRadius: 999, fontSize: 12.5, color: 'var(--text-dim)',
      fontWeight: 500, letterSpacing: '0.01em',
      boxShadow: glow ? '0 0 30px -8px var(--violet-glow)' : 'none', ...style }}>
      {icon && <Icon name={icon} size={14} style={{ color: 'var(--violet-soft)' }} />}
      {children}
    </span>
  );
}

function Pill({ children, active = false, onClick, icon }) {
  const [hov, setHov] = useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 16px', borderRadius: 999,
        fontSize: 13, fontWeight: 500, transition: 'all .3s ease',
        border: `1px solid ${active ? 'var(--violet)' : (hov ? 'var(--line-2)' : 'var(--line)')}`,
        background: active ? 'rgba(124,108,240,0.14)' : (hov ? 'var(--surface-2)' : 'transparent'),
        color: active ? 'var(--violet-soft)' : 'var(--text-dim)' }}>
      {icon && <Icon name={icon} size={14} />}
      {children}
    </button>
  );
}

/* ---------------- WorkScore radial ring ---------------- */
function WorkScore({ value = 92, size = 132, label = 'Work Score', stroke = 8 }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const [shown, setShown] = useState(0);
  useEffect(() => {
    let raf; const t0 = performance.now(); const dur = 1400;
    const tick = (t) => { const k = Math.min(1, (t - t0) / dur); const e = 1 - Math.pow(1 - k, 3);
      setShown(Math.round(value * e)); if (k < 1) raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf);
  }, [value]);
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <defs>
          <linearGradient id="wsgrad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor="var(--violet-soft)" />
            <stop offset="1" stopColor="var(--amber)" />
          </linearGradient>
        </defs>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="url(#wsgrad)" strokeWidth={stroke}
          strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c - c * (shown/100)}
          style={{ transition: 'stroke-dashoffset .1s linear', filter: 'drop-shadow(0 0 6px var(--violet-glow))' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ fontFamily: 'var(--serif)', fontSize: size * 0.34, lineHeight: 1 }}>{shown}</div>
        <div style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--text-faint)', marginTop: 4 }}>{label}</div>
      </div>
    </div>
  );
}

/* ---------------- Metric bar ---------------- */
function MetricBar({ label, value, icon, suffix = '', delay = 0 }) {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const ob = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setVis(true); ob.disconnect(); } }, { threshold: 0.4 });
    ob.observe(el); return () => ob.disconnect();
  }, []);
  return (
    <div ref={ref} style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontSize: 13.5, color: 'var(--text-dim)' }}>
          {icon && <Icon name={icon} size={15} style={{ color: 'var(--violet-soft)' }} />}{label}
        </span>
        <span style={{ fontSize: 13.5, fontVariantNumeric: 'tabular-nums', color: 'var(--text)' }}>{value}{suffix}</span>
      </div>
      <div style={{ height: 5, borderRadius: 999, background: 'var(--surface-3)', overflow: 'hidden' }}>
        <div style={{ height: '100%', width: vis ? `${value}%` : '0%', borderRadius: 999,
          background: 'linear-gradient(90deg, var(--violet), var(--amber))',
          transition: `width 1.1s cubic-bezier(.16,1,.3,1) ${delay}s` }} />
      </div>
    </div>
  );
}

/* ---------------- Section head ---------------- */
function SectionHead({ eyebrow, title, sub, align = 'left', style = {} }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === 'center' ? 720 : 640,
      marginInline: align === 'center' ? 'auto' : 0, ...style }}>
      {eyebrow && <div className="eyebrow" style={{ marginBottom: 18 }}>{eyebrow}</div>}
      <h2 className="d2" style={{ margin: 0 }}>{title}</h2>
      {sub && <p style={{ marginTop: 18, fontSize: 18, lineHeight: 1.55, color: 'var(--text-dim)' }}>{sub}</p>}
    </div>
  );
}

/* ---------------- Scroll-reveal wrapper ---------------- */
function Reveal({ children, delay = 0, y = 24, style = {} }) {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const ob = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setVis(true); ob.disconnect(); } }, { threshold: 0.15 });
    ob.observe(el); return () => ob.disconnect();
  }, []);
  return (
    <div ref={ref} style={{ opacity: vis ? 1 : 0, transform: vis ? 'none' : `translateY(${y}px)`,
      transition: `opacity .9s cubic-bezier(.16,1,.3,1) ${delay}s, transform .9s cubic-bezier(.16,1,.3,1) ${delay}s`, ...style }}>
      {children}
    </div>
  );
}

/* ---------------- NavBar ---------------- */
function NavBar({ route, go, onWish, wishCount = 0 }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const h = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', h, { passive: true }); h();
    return () => window.removeEventListener('scroll', h);
  }, []);
  const links = [['explore', 'Explore'], ['intelligence', 'Workspace Intelligence'], ['operators', 'Operators']];
  return (
    <header style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      transition: 'all .4s ease', padding: scrolled ? '12px 0' : '20px 0',
      background: scrolled ? 'rgba(10,10,12,0.72)' : 'transparent',
      backdropFilter: scrolled ? 'blur(20px) saturate(140%)' : 'none',
      borderBottom: `1px solid ${scrolled ? 'var(--line)' : 'transparent'}` }}>
      <div className="wrap" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={() => go('home')} style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'none', border: 'none', padding: 0 }}>
          <Logo />
          <span style={{ fontFamily: 'var(--serif)', fontSize: 23, color: 'var(--text)', letterSpacing: '-0.01em' }}>WorkStay</span>
        </button>
        <nav style={{ display: 'flex', alignItems: 'center', gap: 4 }} className="ws-navlinks">
          {links.map(([r, label]) => (
            <button key={r} onClick={() => go(r === 'explore' ? 'explore' : 'home')}
              style={{ background: 'none', border: 'none', padding: '8px 14px', fontSize: 13.5, fontFamily: 'var(--sans)',
                color: route === r ? 'var(--text)' : 'var(--text-dim)', transition: 'color .25s' }}
              onMouseEnter={e => e.currentTarget.style.color = 'var(--text)'}
              onMouseLeave={e => e.currentTarget.style.color = route === r ? 'var(--text)' : 'var(--text-dim)'}>
              {label}
            </button>
          ))}
        </nav>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={onWish} title="Wishlist" style={{ position: 'relative', background: 'none', border: 'none', color: 'var(--text-dim)', padding: 8, display: 'flex' }}
            onMouseEnter={e => e.currentTarget.style.color = 'var(--text)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--text-dim)'}>
            <Icon name="heart" size={19} />
            {wishCount > 0 && <span style={{ position: 'absolute', top: 2, right: 2, width: 7, height: 7, borderRadius: 999, background: 'var(--violet)' }} />}
          </button>
          <span className="ws-nav-cta"><Btn variant="glass" size="sm" onClick={() => go('explore')}>Find a stay</Btn></span>
        </div>
      </div>
    </header>
  );
}

function Logo({ size = 30 }) {
  return (
    <span style={{ position: 'relative', width: size, height: size, display: 'inline-flex' }}>
      <span style={{ position: 'absolute', inset: 0, borderRadius: 9,
        background: 'linear-gradient(135deg, var(--violet), var(--violet-deep))',
        boxShadow: '0 6px 18px -6px var(--violet-glow)' }} />
      <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'var(--serif)', fontSize: size * 0.62, color: '#fff' }}>W</span>
    </span>
  );
}

/* ---------------- Footer ---------------- */
function FooterBar({ go }) {
  const cols = [
    ['Platform', ['Explore stays', 'Workspace Intelligence', 'Become an Operator', 'Focus Score']],
    ['Company', ['Our story', 'Standards', 'Careers', 'Press']],
    ['Support', ['Help center', 'Trust & safety', 'Cancellation', 'Contact']],
  ];
  return (
    <footer style={{ borderTop: '1px solid var(--line)', background: 'var(--bg-2)', paddingBlock: '72px 40px' }}>
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr repeat(3, 1fr)', gap: 40 }} className="ws-footgrid">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 18 }}>
              <Logo /><span style={{ fontFamily: 'var(--serif)', fontSize: 23 }}>WorkStay</span>
            </div>
            <p style={{ fontSize: 14.5, lineHeight: 1.6, color: 'var(--text-dim)', maxWidth: 300, margin: 0 }}>
              A premium operating system for modern living and remote work.
            </p>
          </div>
          {cols.map(([h, items]) => (
            <div key={h}>
              <div style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--text-faint)', marginBottom: 18 }}>{h}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
                {items.map(it => <li key={it}><a style={{ fontSize: 14, color: 'var(--text-dim)', transition: 'color .2s' }}
                  onMouseEnter={e => e.currentTarget.style.color = 'var(--text)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--text-dim)'}>{it}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 56, paddingTop: 28, borderTop: '1px solid var(--line)', display: 'flex',
          justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
          <span style={{ fontSize: 13, color: 'var(--text-faint)' }}>© 2026 WorkStay. Designed for deep work.</span>
          <span style={{ fontSize: 13, color: 'var(--text-faint)' }}>Manali · Bir · Dharamshala · Spiti Valley</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Btn, Badge, Pill, WorkScore, MetricBar, SectionHead, Reveal, NavBar, FooterBar, Logo });
