// VibraMatch — shared UI primitives
// Avatar, AvatarStack, Chip, Badge, IconButton, Button, Tabs, BottomNav, AppHeader

// ────────────────────────────────────────────────────────────────
// Avatar — initials-based with deterministic background tint
// ────────────────────────────────────────────────────────────────
const AVATAR_BG = ['#0B0F1A','#3D6FB2','#1FAA5A','#C97557','#6F4FB2','#E59A1E','#4F8C5A','#E03857'];
function hashIdx(s, n) {
  let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  return h % n;
}
function initials(name) {
  return name.split(/\s+/).filter(Boolean).slice(0,2).map(w => w[0]?.toUpperCase() || '').join('');
}
function Avatar({ name = '', size = 36, ring = false, ringColor = 'var(--lime)' }) {
  const bg = AVATAR_BG[hashIdx(name, AVATAR_BG.length)];
  return (
    <div style={{
      width: size, height: size, borderRadius: 999, background: bg, color: '#fff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      fontWeight: 700, fontSize: size * 0.36, letterSpacing: '-0.01em',
      boxShadow: ring ? `0 0 0 2.5px ${ringColor}, 0 0 0 4px var(--surface)` : 'none',
    }}>{initials(name) || '·'}</div>
  );
}

function AvatarStack({ names = [], max = 4, size = 28, overlap = 9, ringBg = 'var(--surface)' }) {
  const show = names.slice(0, max);
  const extra = names.length - show.length;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center' }}>
      {show.map((n, i) => (
        <div key={i} style={{ marginLeft: i === 0 ? 0 : -overlap, boxShadow: `0 0 0 2px ${ringBg}`, borderRadius: 999 }}>
          <Avatar name={n} size={size} />
        </div>
      ))}
      {extra > 0 && (
        <div style={{
          marginLeft: -overlap, boxShadow: `0 0 0 2px ${ringBg}`,
          width: size, height: size, borderRadius: 999, background: 'var(--surface-3)', color: 'var(--ink-2)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: size * 0.34, fontWeight: 700,
        }}>+{extra}</div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// Chip / Badge
// ────────────────────────────────────────────────────────────────
function Chip({ children, leading, tone = 'default', size = 'md', style = {} }) {
  const tones = {
    default: { bg: 'var(--surface-3)', fg: 'var(--ink-2)' },
    ink: { bg: 'var(--ink)', fg: '#fff' },
    lime: { bg: 'var(--lime)', fg: 'var(--on-lime)' },
    soft: { bg: 'var(--lime-soft)', fg: 'var(--ink)' },
    line: { bg: 'transparent', fg: 'var(--ink-2)', border: '1px solid var(--line-strong)' },
  };
  const t = tones[tone];
  const sz = size === 'sm' ? { px: 8, py: 3, fs: 11 } : size === 'lg' ? { px: 14, py: 8, fs: 14 } : { px: 10, py: 5, fs: 12.5 };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      background: t.bg, color: t.fg, border: t.border || 'none',
      padding: `${sz.py}px ${sz.px}px`, borderRadius: 999,
      fontSize: sz.fs, fontWeight: 600, letterSpacing: '-0.005em',
      whiteSpace: 'nowrap', ...style,
    }}>{leading}{children}</span>
  );
}

function LevelBadge({ value, size = 'md' }) {
  const sz = size === 'sm' ? 22 : 28;
  return (
    <div style={{
      width: sz, height: sz, borderRadius: 999, background: 'var(--ink)', color: 'var(--lime)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: sz === 22 ? 10.5 : 12.5, fontWeight: 800, letterSpacing: '-0.02em',
      fontVariantNumeric: 'tabular-nums',
    }}>{value}</div>
  );
}

// ────────────────────────────────────────────────────────────────
// Buttons
// ────────────────────────────────────────────────────────────────
function Button({ children, variant = 'primary', size = 'md', leading, trailing, full, style = {}, ...rest }) {
  const variants = {
    primary: { bg: 'var(--lime)', fg: 'var(--on-lime)', sh: '0 1px 0 rgba(0,0,0,0.04), 0 4px 14px rgba(180,220,34,0.35)' },
    ink: { bg: 'var(--ink)', fg: '#fff', sh: 'var(--sh-2)' },
    surface: { bg: 'var(--surface)', fg: 'var(--ink)', sh: 'var(--sh-1)', border: '1px solid var(--line)' },
    ghost: { bg: 'transparent', fg: 'var(--ink)', sh: 'none' },
  };
  const sz = size === 'sm' ? { h: 36, px: 14, fs: 13, r: 12 }
           : size === 'lg' ? { h: 56, px: 22, fs: 16, r: 18 }
           : { h: 46, px: 18, fs: 14.5, r: 14 };
  const v = variants[variant];
  return (
    <button {...rest} style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      height: sz.h, padding: `0 ${sz.px}px`, borderRadius: sz.r,
      background: v.bg, color: v.fg, border: v.border || 'none', boxShadow: v.sh,
      fontSize: sz.fs, fontWeight: 700, letterSpacing: '-0.01em',
      cursor: 'pointer', width: full ? '100%' : 'auto', ...style,
    }}>
      {leading}{children}{trailing}
    </button>
  );
}

function IconButton({ icon, size = 40, variant = 'surface', style = {}, ...rest }) {
  const variants = {
    surface: { bg: 'var(--surface)', fg: 'var(--ink)', border: '1px solid var(--line)' },
    ghost: { bg: 'transparent', fg: 'var(--ink-2)', border: 'none' },
    ink: { bg: 'var(--ink)', fg: '#fff', border: 'none' },
    lime: { bg: 'var(--lime)', fg: 'var(--on-lime)', border: 'none' },
    soft: { bg: 'var(--surface-3)', fg: 'var(--ink)', border: 'none' },
  };
  const v = variants[variant];
  return (
    <button {...rest} style={{
      width: size, height: size, borderRadius: 999,
      background: v.bg, color: v.fg, border: v.border,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      cursor: 'pointer', flexShrink: 0, ...style,
    }}>{icon}</button>
  );
}

// ────────────────────────────────────────────────────────────────
// Tabs (segmented) — pill style
// ────────────────────────────────────────────────────────────────
function Tabs({ items, value, onChange, variant = 'pill' }) {
  if (variant === 'underline') {
    return (
      <div style={{ display: 'flex', gap: 22, padding: '0 20px', borderBottom: '1px solid var(--line)' }}>
        {items.map(it => {
          const k = typeof it === 'string' ? it : it.key;
          const label = typeof it === 'string' ? it : it.label;
          const active = k === value;
          return (
            <button key={k} onClick={() => onChange?.(k)} style={{
              padding: '14px 0 12px', background: 'none', border: 'none',
              color: active ? 'var(--ink)' : 'var(--ink-3)',
              fontWeight: active ? 700 : 600, fontSize: 14.5, letterSpacing: '-0.01em',
              borderBottom: active ? '2px solid var(--ink)' : '2px solid transparent',
              marginBottom: -1, cursor: 'pointer',
            }}>{label}</button>
          );
        })}
      </div>
    );
  }
  return (
    <div style={{
      display: 'inline-flex', padding: 4, gap: 2,
      background: 'var(--surface-3)', borderRadius: 999,
    }}>
      {items.map(it => {
        const k = typeof it === 'string' ? it : it.key;
        const label = typeof it === 'string' ? it : it.label;
        const count = typeof it === 'string' ? null : it.count;
        const active = k === value;
        return (
          <button key={k} onClick={() => onChange?.(k)} style={{
            padding: '8px 14px', borderRadius: 999,
            background: active ? 'var(--surface)' : 'transparent',
            color: active ? 'var(--ink)' : 'var(--ink-3)',
            border: 'none', fontWeight: active ? 700 : 600, fontSize: 13.5,
            boxShadow: active ? '0 1px 2px rgba(11,15,26,0.08)' : 'none',
            cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
            letterSpacing: '-0.005em',
          }}>
            {label}
            {count != null && (
              <span style={{
                fontSize: 11, padding: '1px 6px', borderRadius: 999,
                background: active ? 'var(--ink)' : 'var(--line)',
                color: active ? 'var(--lime)' : 'var(--ink-3)',
                fontVariantNumeric: 'tabular-nums',
              }}>{count}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// Bottom navigation — navy pill with lime active
// ────────────────────────────────────────────────────────────────
function BottomNav({ value = 'groups', onChange, variant = 'pill', badges = {} }) {
  // Matches real app: 3 tabs — My Groups, Matches, Profile
  const items = [
    { k: 'groups', label: 'Groups', icon: I.groups },
    { k: 'matches', label: 'Matches', icon: I.racket },
    { k: 'profile', label: 'You', icon: I.profile },
  ];
  if (variant === 'bar') {
    return (
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: 'var(--surface)', borderTop: '1px solid var(--line)',
        padding: '8px 8px 28px',
        display: 'flex', justifyContent: 'space-around', alignItems: 'center',
      }}>
        {items.map(it => {
          const IconC = it.icon;
          const active = value === it.k;
          const badge = badges[it.k];
          return (
            <button key={it.k} onClick={() => onChange?.(it.k)} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
              padding: '6px 14px', background: 'none', border: 'none',
              color: active ? 'var(--ink)' : 'var(--ink-4)', cursor: 'pointer', position: 'relative',
            }}>
              <div style={{ position: 'relative' }}>
                <IconC size={24} sw={active ? 2.2 : 1.7}/>
                {badge > 0 && (
                  <span style={{
                    position: 'absolute', top: -4, right: -8,
                    minWidth: 16, height: 16, padding: '0 4px', borderRadius: 999,
                    background: 'var(--lime)', color: 'var(--on-lime)',
                    fontSize: 9.5, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    border: '2px solid var(--surface)',
                  }}>{badge}</span>
                )}
              </div>
              <span style={{ fontSize: 10.5, fontWeight: active ? 700 : 600 }}>{it.label}</span>
            </button>
          );
        })}
      </div>
    );
  }
  // floating pill (navy w/ lime active)
  return (
    <div style={{
      position: 'absolute', left: 16, right: 16, bottom: 18, zIndex: 5,
      background: 'var(--ink)', borderRadius: 999,
      padding: 6, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      boxShadow: '0 12px 32px rgba(11,15,26,0.25), 0 2px 6px rgba(11,15,26,0.1)',
    }}>
      {items.map(it => {
        const IconC = it.icon;
        const active = value === it.k;
        const badge = badges[it.k];
        return (
          <button key={it.k} onClick={() => onChange?.(it.k)} style={{
            height: 44, padding: active ? '0 16px' : '0 14px', borderRadius: 999,
            background: active ? 'var(--lime)' : 'transparent', border: 'none',
            color: active ? 'var(--on-lime)' : 'rgba(255,255,255,0.65)',
            display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
            fontWeight: 700, fontSize: 13.5, letterSpacing: '-0.005em',
            transition: 'all .2s', position: 'relative',
          }}>
            <div style={{ position: 'relative' }}>
              <IconC size={20} sw={active ? 2.4 : 1.9}/>
              {badge > 0 && !active && (
                <span style={{
                  position: 'absolute', top: -3, right: -6,
                  minWidth: 14, height: 14, padding: '0 3px', borderRadius: 999,
                  background: 'var(--lime)', color: 'var(--on-lime)',
                  fontSize: 9, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                }}>{badge}</span>
              )}
            </div>
            {active && <span>{it.label}</span>}
            {active && badge > 0 && (
              <span style={{
                minWidth: 18, height: 18, padding: '0 5px', borderRadius: 999,
                background: 'var(--on-lime)', color: 'var(--lime)',
                fontSize: 10.5, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                marginLeft: 2,
              }}>{badge}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// Court tile — used as photo placeholder for groups
// ────────────────────────────────────────────────────────────────
function CourtTile({ tint = 'grass', children, height = 120, radius = 'var(--r-md)', style = {} }) {
  const tints = {
    grass: 'linear-gradient(135deg, #5B9F65 0%, #3D7548 100%)',
    clay: 'linear-gradient(135deg, #D88A6A 0%, #B0573E 100%)',
    blue: 'linear-gradient(135deg, #5689D4 0%, #2F5EAA 100%)',
    indoor: 'linear-gradient(135deg, #8467D4 0%, #5538A8 100%)',
    night: 'linear-gradient(135deg, #2A3142 0%, #0B0F1A 100%)',
    teal: 'linear-gradient(135deg, #4CB3A7 0%, #2A7F77 100%)',
  };
  return (
    <div className="vm-court" style={{
      height, borderRadius: radius, position: 'relative',
      '--court-tint': tints[tint] || tints.grass, ...style,
    }}>
      <div style={{
        position: 'absolute', inset: 0, padding: 14,
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
      }}>{children}</div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// AppHeader — greeting + actions (used across screens)
// ────────────────────────────────────────────────────────────────
function AppHeader({ greeting, name, onSearch, dark = false, action }) {
  return (
    <div style={{ padding: '8px 20px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
      <Avatar name={name} size={42} ring />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="vm-sm" style={{ fontWeight: 500 }}>{greeting}</div>
        <div className="vm-h4" style={{ fontWeight: 700, lineHeight: 1.1 }}>{name}</div>
      </div>
      {action || (
        <>
          <IconButton icon={<I.search size={20}/>} variant="surface" />
          <IconButton icon={<I.bell size={20}/>} variant="surface" />
        </>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// Stat — compact metric block
// ────────────────────────────────────────────────────────────────
function Stat({ label, value, trend, tone = 'default' }) {
  const tones = {
    default: { bg: 'var(--surface-2)', fg: 'var(--ink)' },
    ink: { bg: 'var(--ink)', fg: '#fff' },
    lime: { bg: 'var(--lime)', fg: 'var(--on-lime)' },
  };
  const t = tones[tone];
  return (
    <div style={{
      flex: 1, background: t.bg, color: t.fg, borderRadius: 'var(--r-md)',
      padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.7, letterSpacing: '0.02em', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <div className="vm-num" style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>{value}</div>
        {trend && <div style={{ fontSize: 11, fontWeight: 700, opacity: 0.7 }}>{trend}</div>}
      </div>
    </div>
  );
}

Object.assign(window, {
  Avatar, AvatarStack, Chip, LevelBadge, Button, IconButton, Tabs,
  BottomNav, CourtTile, AppHeader, Stat,
});
