// components.jsx — shared Viewbot.to glass primitives & icons

// ===== ICONS (line, 1.6 stroke) =================================
const Icon = ({ children, size = 18, ...rest }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...rest}>
    {children}
  </svg>
);

const IconKick = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M3 3h5v6h2V6h2V3h5v6h-2v3h-2v3h2v3h2v3h-5v-3h-2v-3H8v6H3V3z"/>
  </svg>
);

const IconTwitch = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 6v12M8 3v18M12 7v10M16 4v16M20 8v8" />
  </svg>
);

const IconViewers = (p) => <Icon {...p}><circle cx="12" cy="12" r="3"/><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/></Icon>;
const IconBolt = (p) => <Icon {...p}><path d="M13 3 4 14h7l-1 7 9-11h-7l1-7z"/></Icon>;
const IconShield = (p) => <Icon {...p}><path d="M12 2 4 6v6c0 5 3.5 9 8 10 4.5-1 8-5 8-10V6l-8-4z"/></Icon>;
const IconChat = (p) => <Icon {...p}><path d="M21 12a8 8 0 1 1-3.2-6.4L21 5l-1 3.5A8 8 0 0 1 21 12z"/></Icon>;
const IconHeart = (p) => <Icon {...p}><path d="M12 21s-7-4.5-9.5-9C.5 8.5 3 4 7 4c2 0 3.5 1 5 3 1.5-2 3-3 5-3 4 0 6.5 4.5 4.5 8-2.5 4.5-9.5 9-9.5 9z"/></Icon>;
const IconClip = (p) => <Icon {...p}><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M20 4 8.12 14.88M14.5 14.5 20 20M8.12 9.12 12 13"/></Icon>;
const IconPlay = (p) => <Icon {...p}><path d="M6 4l14 8-14 8V4z"/></Icon>;
const IconCheck = (p) => <Icon {...p}><path d="m4 12 5 5L20 6"/></Icon>;
const IconArrow = (p) => <Icon {...p}><path d="M5 12h14M13 5l7 7-7 7"/></Icon>;
const IconChevron = (p) => <Icon {...p}><path d="m6 9 6 6 6-6"/></Icon>;
const IconClose = (p) => <Icon {...p}><path d="M6 6l12 12M18 6 6 18"/></Icon>;
const IconPlus = (p) => <Icon {...p}><path d="M12 5v14M5 12h14"/></Icon>;
const IconMinus = (p) => <Icon {...p}><path d="M5 12h14"/></Icon>;
const IconSearch = (p) => <Icon {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></Icon>;
const IconBell = (p) => <Icon {...p}><path d="M6 8a6 6 0 1 1 12 0c0 6 3 7 3 7H3s3-1 3-7zM10 21a2 2 0 0 0 4 0"/></Icon>;
const IconUser = (p) => <Icon {...p}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></Icon>;
const IconCard = (p) => <Icon {...p}><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M2 11h20"/></Icon>;
const IconCog = (p) => <Icon {...p}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 0 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 0 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 0 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 0 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 0 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 0 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 0 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></Icon>;
const IconHome = (p) => <Icon {...p}><path d="m3 11 9-8 9 8M5 9v12h14V9"/></Icon>;
const IconChart = (p) => <Icon {...p}><path d="M3 3v18h18M7 14l4-4 3 3 5-7"/></Icon>;
const IconReceipt = (p) => <Icon {...p}><path d="M5 3h14v18l-3-2-2 2-2-2-2 2-2-2-3 2V3z"/><path d="M9 8h6M9 12h6M9 16h4"/></Icon>;
const IconLink = (p) => <Icon {...p}><path d="M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 1 0-5.66-5.66l-1.5 1.5"/><path d="M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1.5-1.5"/></Icon>;
const IconTrend = (p) => <Icon {...p}><path d="M3 17 9 11l4 4 8-9"/><path d="M14 6h7v7"/></Icon>;
const IconLock = (p) => <Icon {...p}><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></Icon>;
const IconClock = (p) => <Icon {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></Icon>;
const IconGlobe = (p) => <Icon {...p}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></Icon>;
const IconSpark = (p) => <Icon {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></Icon>;
const IconCopy = (p) => <Icon {...p}><rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h4"/></Icon>;
const IconMic = (p) => <Icon {...p}><rect x="9" y="2" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8"/></Icon>;

// ===== Brand glyph (Viewbot.to logo mark) ========================
const VbLogo = ({ size = 28 }) => (
  <div style={{
    width: size, height: size, borderRadius: size * 0.28,
    background: 'linear-gradient(135deg, oklch(0.92 0.27 142), oklch(0.62 0.23 295))',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    boxShadow: '0 1px 0 rgba(255,255,255,0.4) inset, 0 0 16px -4px oklch(0.7 0.2 200 / 0.5)',
    position: 'relative', overflow: 'hidden', flexShrink: 0,
  }}>
    <svg width={size * 0.55} height={size * 0.55} viewBox="0 0 20 20" fill="none">
      <path d="M3 5l4 9 3-7 3 7 4-9" stroke="white" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
    <span style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(255,255,255,0.3), transparent 40%)', pointerEvents: 'none' }} />
  </div>
);

// ===== Background stage =========================================
const Stage = ({ children, orbs = true, className = '', style = {} }) => (
  <div className={`vb-stage ${className}`} style={style}>
    {orbs && (
      <div className="vb-orbs">
        <div className="vb-orb vb-orb-a" />
        <div className="vb-orb vb-orb-b" />
        <div className="vb-orb vb-orb-c" />
        <div className="vb-orb vb-orb-d" />
      </div>
    )}
    <div style={{ position: 'relative', zIndex: 1, height: '100%' }}>{children}</div>
  </div>
);

// ===== Glass card ===============================================
const Glass = ({ children, soft, flat, className = '', style = {}, ...rest }) => {
  const cls = soft ? 'vb-glass-soft' : flat ? 'vb-glass-flat' : 'vb-glass';
  return <div className={`${cls} ${className}`} style={style} {...rest}>{children}</div>;
};

// ===== Button (renders as <a> when href is given) ===============
const Btn = ({ variant = 'primary', size, children, icon, iconRight, href, onClick, style, ...rest }) => {
  const cls = `vb-btn vb-btn-${variant} ${size ? `vb-btn-${size}` : ''}`;
  const inner = (
    <>
      {icon}
      {children && <span>{children}</span>}
      {iconRight}
    </>
  );
  if (href) {
    return (
      <a className={cls} href={href} style={{ textDecoration: 'none', ...style }} {...rest}>{inner}</a>
    );
  }
  return (
    <button className={cls} onClick={onClick} style={style} {...rest}>{inner}</button>
  );
};

// ===== Tabs (segmented control with thumb) ======================
const Tabs = ({ items, value, onChange, style }) => {
  const ref = React.useRef(null);
  const [thumb, setThumb] = React.useState({ left: 4, width: 0 });
  React.useLayoutEffect(() => {
    if (!ref.current) return;
    const idx = items.findIndex((it) => (it.value ?? it) === value);
    const btn = ref.current.querySelectorAll('.vb-tab')[idx];
    if (btn) setThumb({ left: btn.offsetLeft, width: btn.offsetWidth });
  }, [value, items]);
  return (
    <div ref={ref} className="vb-tabs" style={style}>
      <div className="vb-tab-thumb" style={{ left: thumb.left, width: thumb.width }} />
      {items.map((it) => {
        const v = it.value ?? it;
        const label = it.label ?? it;
        return (
          <button key={v} className="vb-tab" data-active={v === value} onClick={() => onChange(v)}>
            {it.icon}{label}
          </button>
        );
      })}
    </div>
  );
};

// ===== Platform pill =============================================
const PlatformPill = ({ platform, size = 'sm' }) => {
  if (platform === 'kick') return (
    <span className="vb-badge vb-badge-kick"><IconKick size={11}/>Kick</span>
  );
  return <span className="vb-badge vb-badge-twitch"><IconTwitch size={11}/>Twitch</span>;
};

// ===== Live pill =================================================
const LivePill = () => (
  <span className="vb-live-pill"><span className="vb-dot vb-dot-pulse"/>LIVE</span>
);

// ===== Stat ======================================================
const Stat = ({ label, value, change, accent }) => (
  <div className="vb-col" style={{ gap: 6 }}>
    <span className="vb-caption">{label}</span>
    <span className="vb-mono" style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em', color: accent || 'var(--vb-fg-0)' }}>{value}</span>
    {change && (
      <span style={{ fontSize: 12, color: change.startsWith('+') ? 'oklch(0.85 0.18 142)' : 'oklch(0.75 0.18 25)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        <IconTrend size={12}/> {change}
      </span>
    )}
  </div>
);

// ===== Number ticker (animated) ==================================
const useTicker = (target, duration = 1500) => {
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const from = 0;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(Math.round(from + (target - from) * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return v;
};

// ===== Sparkline =================================================
const Sparkline = ({ data, color = 'rgba(255,255,255,0.6)', width = 120, height = 36, fill = true }) => {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((v - min) / range) * height * 0.85 - 2;
    return [x, y];
  });
  const d = pts.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(' ');
  const area = `${d} L${width},${height} L0,${height} Z`;
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      {fill && (
        <path d={area} fill={color} opacity="0.18"/>
      )}
      <path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

// ===== Live viewer count animator ================================
const LiveCounter = ({ base, jitter = 12, interval = 1500, format = (n) => n.toLocaleString() }) => {
  const [n, setN] = React.useState(base);
  React.useEffect(() => {
    const t = setInterval(() => {
      setN((cur) => {
        const drift = Math.round((Math.random() - 0.5) * jitter * 2);
        const next = cur + drift;
        return Math.max(base - jitter * 4, Math.min(base + jitter * 4, next));
      });
    }, interval);
    return () => clearInterval(t);
  }, [base, jitter, interval]);
  return <span className="vb-mono">{format(n)}</span>;
};

// ===== Stepper (number input with +/-) ============================
const Stepper = ({ value, onChange, min = 0, max = 99999, step = 1, suffix }) => (
  <div className="vb-row" style={{
    height: 44, padding: '0 4px',
    background: 'rgba(255,255,255,0.04)',
    border: '1px solid rgba(255,255,255,0.08)',
    borderRadius: 14, gap: 0, width: 'fit-content',
  }}>
    <button onClick={() => onChange(Math.max(min, value - step))}
      style={{ width: 36, height: 36, border: 'none', background: 'transparent', color: 'var(--vb-fg-1)', borderRadius: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <IconMinus size={14}/>
    </button>
    <input type="number" value={value} onChange={(e) => onChange(Number(e.target.value))}
      style={{ width: 60, textAlign: 'center', background: 'transparent', border: 'none', outline: 'none', color: 'var(--vb-fg-0)', fontFamily: 'var(--vb-font-mono)', fontSize: 14, fontWeight: 500 }}/>
    {suffix && <span style={{ color: 'var(--vb-fg-3)', fontSize: 12, paddingRight: 6 }}>{suffix}</span>}
    <button onClick={() => onChange(Math.min(max, value + step))}
      style={{ width: 36, height: 36, border: 'none', background: 'transparent', color: 'var(--vb-fg-1)', borderRadius: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <IconPlus size={14}/>
    </button>
  </div>
);

// ===== Avatar circle with gradient ================================
const Avatar = ({ name = '?', size = 32, hue = 200 }) => (
  <div style={{
    width: size, height: size, borderRadius: '50%',
    background: `linear-gradient(135deg, oklch(0.7 0.18 ${hue}), oklch(0.5 0.2 ${hue + 40}))`,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    color: '#fff', fontSize: size * 0.42, fontWeight: 600, letterSpacing: '-0.02em',
    flexShrink: 0,
    boxShadow: '0 1px 0 rgba(255,255,255,0.2) inset, 0 0 0 0.5px rgba(0,0,0,0.4)',
  }}>{name.charAt(0).toUpperCase()}</div>
);

// ===== Format helpers ============================================
const fmtMoney = (n) => '$' + n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const fmtNum = (n) => n.toLocaleString();
const fmtCompact = (n) => {
  if (n >= 1e6) return (n/1e6).toFixed(1) + 'M';
  if (n >= 1e3) return (n/1e3).toFixed(1) + 'K';
  return String(n);
};

// ===== Shared site nav (reused on landing + pricing) =============
function SiteNav({ platform, setPlatform }) {
  const links = [
    { label: 'Services', href: 'index.html#services' },
    { label: 'AI Chat', href: 'ai-chat.html' },
    { label: 'Pricing', href: 'pricing.html' },
    { label: 'Network', href: 'index.html#network' },
    { label: 'Affiliate', href: 'affiliates.html' },
  ];
  return (
    <header style={{ position: 'sticky', top: 16, zIndex: 50, padding: '0 80px', maxWidth: 1440, margin: '16px auto 0' }}>
      <Glass style={{ display: 'flex', alignItems: 'center', height: 64, padding: '0 8px 0 24px', borderRadius: 999 }}>
        <a href="index.html" className="vb-row" style={{ gap: 10, textDecoration: 'none', color: 'inherit' }}>
          <span style={{ fontWeight: 600, fontSize: 16, letterSpacing: '-0.015em' }}>Viewbot<span style={{ color: 'var(--vb-fg-3)' }}>.to</span></span>
        </a>
        <nav style={{ display: 'flex', gap: 4, marginLeft: 40 }}>
          {links.map((x) => (
            <a key={x.label} href={x.href} className="vb-btn vb-btn-ghost vb-btn-sm" style={{ height: 32, textDecoration: 'none' }}>{x.label}</a>
          ))}
        </nav>
        <div className="vb-spacer"/>
        <Tabs items={[
          { value: 'kick', label: 'Kick', icon: <IconKick size={12}/> },
          { value: 'twitch', label: 'Twitch', icon: <IconTwitch size={12}/> },
        ]} value={platform} onChange={setPlatform} style={{ marginRight: 12 }}/>
        <Btn variant="ghost" size="sm" href="dashboard.html">Sign in</Btn>
        <Btn variant="primary" size="sm" iconRight={<IconArrow size={13}/>} href="dashboard.html" style={{ marginLeft: 8 }}>Dashboard</Btn>
      </Glass>
    </header>
  );
}

// ===== Shared footer =============================================
function SiteFooter() {
  return (
    <footer style={{ borderTop: '1px solid rgba(255,255,255,0.06)', padding: '40px 80px', maxWidth: 1440, margin: '0 auto' }}>
      <div className="vb-row" style={{ justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
        <div className="vb-row" style={{ gap: 10 }}>
          <VbLogo size={22}/>
          <span style={{ fontSize: 13, color: 'var(--vb-fg-2)' }}>© 2026 Viewbot.to · A Stratum Networks product</span>
        </div>
        <div className="vb-row" style={{ gap: 24, fontSize: 13, color: 'var(--vb-fg-2)' }}>
          <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Status</a>
          <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Privacy</a>
          <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Terms</a>
          <a href="#" style={{ color: 'inherit', textDecoration: 'none' }}>Press</a>
        </div>
      </div>
    </footer>
  );
}

// ===== EXPORT =====================================================
Object.assign(window, {
  Icon, IconKick, IconTwitch, IconViewers, IconBolt, IconShield, IconChat, IconHeart,
  IconClip, IconPlay, IconCheck, IconArrow, IconChevron, IconClose, IconPlus, IconMinus,
  IconSearch, IconBell, IconUser, IconCard, IconCog, IconHome, IconChart, IconReceipt,
  IconLink, IconTrend, IconLock, IconClock, IconGlobe, IconSpark, IconCopy, IconMic,
  VbLogo, Stage, Glass, Btn, Tabs, PlatformPill, LivePill, Stat, Sparkline,
  LiveCounter, Stepper, Avatar, useTicker,
  fmtMoney, fmtNum, fmtCompact,
  SiteNav, SiteFooter,
});
