// PitStop UI Kit — primitives
// Brand atoms recreated from climb-wise-routes/apps/web/src/components/dots/*
// and the shadcn button/card usage across the app. Cosmetic only.

const { useState, useEffect, useRef } = React;

// ── Icon — self-rendering lucide wrapper. Builds the SVG into a ref'd span
//    imperatively so React never reconciles lucide's node-swap (which caused
//    icons to "stick" from a previous render when DOM nodes were reused). ──
function Icon({ name, size = 20, color = 'currentColor', strokeWidth = 2, style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el || !window.lucide) return;
    el.innerHTML = `<i data-lucide="${name}"></i>`;
    window.lucide.createIcons({ attrs: { 'stroke-width': strokeWidth, width: size, height: size } });
    const svg = el.querySelector('svg');
    if (svg) { svg.style.width = size + 'px'; svg.style.height = size + 'px'; svg.style.display = 'block'; }
  }, [name, size, strokeWidth]);
  return <span ref={ref} style={{ width: size, height: size, color, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, ...style }} />;
}
// Kept for any stray <i data-lucide> in static markup; Icon self-converts.
function useLucide() {
  useEffect(() => {
    const id = requestAnimationFrame(() => {
      if (window.lucide) window.lucide.createIcons({ attrs: { 'stroke-width': 2 } });
    });
    return () => cancelAnimationFrame(id);
  });
}

// ── DotsLogo — the PitStop mark (faithful to DotsLogo.tsx) ────────────────
function DotsLogo({ width = 44, height = 22, style = {} }) {
  return (
    <svg width={width} height={height} viewBox="0 0 60 24" style={style} aria-hidden>
      <path d="M 8 18 Q 30 -2, 52 18" fill="none" stroke="hsl(var(--ink))" strokeWidth="2.5" strokeLinecap="round"/>
      <path d="M 8 18 Q 30 -2, 52 18" fill="none" stroke="hsl(var(--ember))" strokeWidth="2.5" strokeDasharray="1 4" strokeLinecap="round" opacity="0.7"/>
      <circle cx="8" cy="18" r="3.5" fill="hsl(var(--ink))"/>
      <circle cx="52" cy="18" r="5.5" fill="hsl(var(--ink))"/>
      <circle cx="52" cy="18" r="2.5" fill="hsl(var(--ember))"/>
    </svg>
  );
}

// ── HopArc — the journey glyph, doubles as "new activity" (HopArc.tsx) ────
function HopArc({ width = 48, height = 16, style = {} }) {
  return (
    <svg width={width} height={height} viewBox="0 0 60 18" style={{ display: 'block', ...style }} aria-hidden>
      <path d="M 4 14 Q 30 1, 56 14" fill="none" stroke="hsl(var(--ink) / 0.22)" strokeWidth="1.5" strokeLinecap="round"/>
      <path d="M 4 14 Q 30 1, 56 14" fill="none" stroke="hsl(var(--ember))" strokeWidth="1.5" strokeDasharray="1 4" strokeLinecap="round" opacity="0.9"/>
      <circle cx="4" cy="14" r="3" fill="hsl(var(--ink))"/>
      <circle cx="56" cy="14" r="5" fill="hsl(var(--ink))"/>
      <circle cx="56" cy="14" r="2.6" fill="hsl(var(--ember))"/>
    </svg>
  );
}

// ── Kicker — mono uppercase micro-label ───────────────────────────────────
// Mono sentence-case kicker (#620 T1). `caps` keeps the uppercase register for
// short fixed labels. Small kickers stay ink/muted-ink, never ember (T2).
function Kicker({ children, color, caps = false, style = {} }) {
  return <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, textTransform: caps ? 'uppercase' : 'none',
    letterSpacing: caps ? '0.16em' : '0.02em', fontSize: caps ? 9 : 11, color: color || 'hsl(var(--muted-ink))', ...style }}>{children}</div>;
}

// ── Button — pill, heavy uppercase label ──────────────────────────────────
function Btn({ children, variant = 'primary', size = 'md', onClick, style = {}, full, disabled = false, label }) {
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    borderRadius: 999, fontFamily: 'var(--font-sans)', fontWeight: 800,
    textTransform: 'uppercase', letterSpacing: '0.06em', cursor: 'pointer', border: 'none',
    whiteSpace: 'nowrap', transition: 'all .15s', width: full ? '100%' : undefined,
    height: size === 'lg' ? 48 : size === 'sm' ? 36 : 44,
    fontSize: size === 'sm' ? 12 : 13, padding: size === 'sm' ? '0 14px' : '0 20px',
  };
  const variants = {
    primary: { background: 'hsl(var(--ember))', color: '#fff', boxShadow: 'var(--shadow-soft)' },
    outline: { background: 'transparent', color: 'hsl(var(--ink))', border: '1px solid hsl(var(--border))' },
    ghost:   { background: 'transparent', color: 'hsl(var(--ink))' },
    solidInk:{ background: 'hsl(var(--ink))', color: 'hsl(var(--bg))' },
  };
  return <button onClick={onClick} disabled={disabled} aria-label={label} style={{ ...base, ...variants[variant], ...style }}>{children}</button>;
}

// ── Card — borderless, lifted ─────────────────────────────────────────────
function Card({ children, onClick, style = {}, hoverable }) {
  const [hover, setHover] = useState(false);
  return (
    <div onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ background: 'hsl(var(--paper))', borderRadius: 'var(--radius)',
        boxShadow: hover && hoverable ? '0 8px 28px -6px rgba(0,0,0,0.22)' : 'var(--shadow-card)',
        cursor: onClick ? 'pointer' : 'default', transition: 'box-shadow .18s', ...style }}>
      {children}
    </div>
  );
}

// ── Avatar + stack ────────────────────────────────────────────────────────
const AV_COLORS = ['#3A7BBD', '#C77B33', '#4B9168', '#B14A45', '#5A6577'];
function Avatar({ initials, i = 0, size = 26, ring = 'hsl(var(--paper))' }) {
  return (
    <span style={{ width: size, height: size, borderRadius: 999, background: AV_COLORS[i % AV_COLORS.length],
      border: `2px solid ${ring}`, color: '#fff', fontFamily: 'var(--font-sans)', fontWeight: 800,
      fontSize: size * 0.38, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      {initials}
    </span>
  );
}
function AvatarStack({ people, size = 26 }) {
  return (
    <div style={{ display: 'flex' }}>
      {people.map((p, i) => (
        <span key={i} style={{ marginLeft: i ? -7 : 0 }}><Avatar initials={p} i={i} size={size} /></span>
      ))}
    </div>
  );
}

// ── Route timeline (connected dots, first accented) ───────────────────────
function RouteTimeline({ count = 4 }) {
  const n = Math.min(Math.max(count, 3), 6);
  return (
    <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0' }} aria-hidden>
      <div style={{ position: 'absolute', left: 6, right: 6, top: '50%', transform: 'translateY(-50%)', height: 1, background: 'hsl(var(--ink) / 0.2)' }} />
      {Array.from({ length: n }).map((_, i) => (
        <span key={i} style={{ position: 'relative', zIndex: 1, width: 11, height: 11, borderRadius: 999,
          background: i === 0 ? 'hsl(var(--ember))' : 'hsl(var(--ink) / 0.45)' }} />
      ))}
    </div>
  );
}

// ── Chip (filter / toggle pill) ───────────────────────────────────────────
function Chip({ children, active, accent, onClick }) {
  const style = active
    ? (accent ? { background: 'hsl(var(--ember))', color: '#fff' } : { background: 'hsl(var(--ink))', color: 'hsl(var(--bg))' })
    : { background: 'transparent', color: 'hsl(var(--muted-ink))', border: '1px solid hsl(var(--border))' };
  return (
    <button onClick={onClick} style={{ padding: '7px 14px', borderRadius: 999, fontFamily: 'var(--font-sans)',
      fontWeight: 800, fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', cursor: 'pointer',
      border: 'none', transition: 'all .15s', whiteSpace: 'nowrap', ...style }}>{children}</button>
  );
}

Object.assign(window, {
  Icon, useLucide, DotsLogo, HopArc, Kicker, Btn, Card, Avatar, AvatarStack, RouteTimeline, Chip,
});
