// MedBridge — primitive UI components.
// Buttons, Chips, Badges, Tags. Consumes MB tokens.

const { useState } = React;

// ─── Buttons ───────────────────────────────────────────────────
function Button({ children, kind = 'primary', size = 'md', tone, leading, trailing, disabled, full, onClick, style = {} }) {
  const t = tone || MB.brand;
  const sz = { sm: { h: 32, px: 12, fs: 14 }, md: { h: 44, px: 16, fs: 15 }, lg: { h: 52, px: 20, fs: 16 } }[size];
  const variants = {
    primary:   { bg: t[600] || MB.brand[700], fg: MB.ink.onColor, bd: 'transparent' },
    secondary: { bg: MB.surface.raised,        fg: MB.ink.primary, bd: MB.line.border },
    soft:      { bg: t[100] || MB.brand[100], fg: t[700] || MB.brand[700], bd: 'transparent' },
    ghost:     { bg: 'transparent',            fg: MB.ink.primary, bd: 'transparent' },
    danger:    { bg: MB.danger[600],           fg: MB.ink.onColor, bd: 'transparent' },
  };
  const v = variants[kind];
  return (
    <button onClick={onClick} disabled={disabled} style={{
      height: sz.h, padding: `0 ${sz.px}px`, borderRadius: 12,
      background: disabled ? '#E9ECF1' : v.bg, color: disabled ? MB.ink.tertiary : v.fg,
      border: `1px solid ${v.bd}`, fontFamily: MB.font, fontSize: sz.fs, fontWeight: 600,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      cursor: disabled ? 'not-allowed' : 'pointer', width: full ? '100%' : undefined,
      transition: `all ${MB.motion.base}ms ${MB.motion.ease}`, letterSpacing: -0.1,
      ...style,
    }}>
      {leading}{children}{trailing}
    </button>
  );
}

// ─── Chip / Tag ────────────────────────────────────────────────
function Chip({ children, tone = 'neutral', strong, leading, size = 'md', style = {} }) {
  const tones = {
    neutral:    { bg: MB.surface.canvas2, fg: MB.ink.secondary, bd: MB.line.hair },
    vertretung: { bg: MB.vertretung[50], fg: MB.vertretung[700], bd: MB.vertretung[100] },
    ausbildung: { bg: MB.ausbildung[50], fg: MB.ausbildung[700], bd: MB.ausbildung[100] },
    brand:      { bg: MB.brand[50], fg: MB.brand[700], bd: MB.brand[100] },
    success:    { bg: MB.success[100], fg: MB.success[700], bd: 'transparent' },
    warning:    { bg: MB.warning[100], fg: MB.warning[700], bd: 'transparent' },
    danger:     { bg: MB.danger[100], fg: MB.danger[700], bd: 'transparent' },
  };
  const c = tones[tone] || tones.neutral;
  const sz = { sm: { h: 22, px: 8, fs: 12 }, md: { h: 26, px: 10, fs: 13 }, lg: { h: 32, px: 12, fs: 14 } }[size];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      height: sz.h, padding: `0 ${sz.px}px`, borderRadius: 999,
      background: strong ? (tone === 'vertretung' ? MB.vertretung[600] : tone === 'ausbildung' ? MB.ausbildung[600] : MB.brand[600]) : c.bg,
      color: strong ? MB.ink.onColor : c.fg,
      border: strong ? 'none' : `1px solid ${c.bd}`,
      fontFamily: MB.font, fontSize: sz.fs, fontWeight: 600,
      letterSpacing: -0.05, whiteSpace: 'nowrap', lineHeight: 1, ...style,
    }}>
      {leading}{children}
    </span>
  );
}

// Angebotstyp pill — the structural one. Vertretung or Ausbildung, with icon.
function TypePill({ type, subtype, strong, size = 'md' }) {
  const isV = type === 'Vertretung';
  return (
    <Chip tone={isV ? 'vertretung' : 'ausbildung'} strong={strong} size={size}
      leading={<Icon name={isV ? 'stethoscope' : 'graduation'} size={size === 'sm' ? 12 : 14} />}>
      {subtype || type}
    </Chip>
  );
}

// ─── Badge ─────────────────────────────────────────────────────
function VerifiedBadge({ size = 16 }) {
  return (
    <span title="Verifiziert via ID Austria" style={{ display: 'inline-flex', color: MB.brand[600] }}>
      <Icon name="badge-check" size={size} />
    </span>
  );
}

function UrgencyStrip({ days, tone }) {
  // sits at the top of an urgent card. Tone matches the listing's Angebotstyp.
  const t = tone === 'Vertretung' ? MB.vertretung : MB.ausbildung;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      padding: '6px 12px', background: t[50],
      borderBottom: `1px solid ${t[100]}`, color: t[700],
      fontFamily: MB.font, fontSize: 13, fontWeight: 600, letterSpacing: -0.05,
    }}>
      <Icon name="alert" size={14} />
      <span>Dringend · {days === 0 ? 'beginnt heute' : `in ${days} Tag${days === 1 ? '' : 'en'}`}</span>
    </div>
  );
}

// ─── Avatar ────────────────────────────────────────────────────
function Avatar({ name = '', size = 40, verified, color }) {
  const initials = name.split(/\s+/).map(s => s[0]).filter(Boolean).slice(0, 2).join('').toUpperCase() || '·';
  // deterministic muted color from name
  const hues = ['#5B6F8A','#7A5C8E','#5C7E8A','#6B7C50','#7B6648','#558578'];
  const bg = color || hues[name.charCodeAt(0) % hues.length] || hues[0];
  return (
    <span style={{ position: 'relative', display: 'inline-flex' }}>
      <span style={{
        width: size, height: size, borderRadius: 999, background: bg, color: '#fff',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: MB.font, fontWeight: 600, fontSize: size * 0.4,
        boxShadow: verified ? `0 0 0 2px ${MB.surface.raised}, 0 0 0 3.5px ${MB.brand[600]}` : 'none',
      }}>{initials}</span>
      {verified && (
        <span style={{ position: 'absolute', right: -2, bottom: -2, background: MB.surface.raised, borderRadius: 999, display: 'inline-flex' }}>
          <Icon name="badge-check" size={Math.max(14, size * 0.36)} color={MB.brand[600]} />
        </span>
      )}
    </span>
  );
}

// ─── Fact tile (icon + label + value) ───────────────────────────
function FactTile({ icon, label, value, elevated, tone }) {
  return (
    <div style={{
      background: elevated ? (tone === 'ausbildung' ? MB.ausbildung[50] : MB.surface.raised) : MB.surface.raised,
      border: `1px solid ${elevated && tone === 'ausbildung' ? MB.ausbildung[100] : MB.line.hair}`,
      borderRadius: 12, padding: '12px 14px', display: 'flex', gap: 12, alignItems: 'flex-start',
    }}>
      <span style={{ color: elevated && tone === 'ausbildung' ? MB.ausbildung[700] : MB.ink.tertiary, marginTop: 1 }}>
        <Icon name={icon} size={18} />
      </span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: 0.2, color: MB.ink.tertiary, textTransform: 'uppercase' }}>{label}</div>
        <div style={{ fontSize: 15, fontWeight: 600, color: MB.ink.primary, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      </div>
    </div>
  );
}

// Career stage chip — informational, never colored by Angebotstyp
function CareerChip({ stage, size = 'md' }) {
  const meta = MB.career[stage] || { short: stage };
  const icon = stage === 'KPJ' ? 'graduation' :
               stage === 'AssistAM' || stage === 'AssistSF' ? 'stethoscope' :
               stage === 'Niedergelassen' ? 'shield' : 'users';
  return (
    <Chip tone="neutral" size={size} leading={<Icon name={icon} size={size === 'sm' ? 12 : 14} />}>
      {meta.short}
    </Chip>
  );
}

// ─── Segmented control ─────────────────────────────────────────
function Segmented({ options, value, onChange, size = 'md' }) {
  const sz = { sm: 30, md: 36, lg: 44 }[size];
  return (
    <div style={{
      display: 'inline-flex', background: MB.surface.canvas2, padding: 3,
      borderRadius: 10, gap: 2, border: `1px solid ${MB.line.hair}`,
    }}>
      {options.map(o => {
        const active = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            height: sz, padding: '0 14px', borderRadius: 8, border: 'none',
            background: active ? MB.surface.raised : 'transparent',
            color: active ? MB.ink.primary : MB.ink.secondary,
            fontFamily: MB.font, fontSize: 14, fontWeight: 600, cursor: 'pointer',
            boxShadow: active ? MB.shadow.card : 'none',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            transition: `all ${MB.motion.fast}ms ${MB.motion.ease}`, letterSpacing: -0.1,
          }}>
            {o.icon && <Icon name={o.icon} size={14} />}{o.label}
          </button>
        );
      })}
    </div>
  );
}

// ─── Input ─────────────────────────────────────────────────────
function Input({ placeholder, value, onChange, leading, trailing, type = 'text', style = {} }) {
  return (
    <div className="mb-input" style={{
      display: 'flex', alignItems: 'center', gap: 10, height: 48, padding: '0 14px',
      background: MB.surface.raised, border: `1px solid ${MB.line.border}`,
      borderRadius: 10, ...style,
    }}>
      {leading && <span style={{ color: MB.ink.tertiary }}>{leading}</span>}
      <input type={type} placeholder={placeholder} value={value} onChange={onChange} style={{
        flex: 1, border: 'none', outline: 'none', background: 'transparent',
        fontFamily: MB.font, fontSize: 16, color: MB.ink.primary,
      }} />
      {trailing && <span style={{ color: MB.ink.tertiary }}>{trailing}</span>}
    </div>
  );
}

// ─── Section header within a screen ────────────────────────────
function SectionTitle({ children, action, onActionClick, style = {} }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 20px', marginBottom: 12, ...style }}>
      <h3 style={{ fontFamily: MB.font, fontSize: 17, fontWeight: 700, color: MB.ink.primary, margin: 0, letterSpacing: -0.2 }}>{children}</h3>
      {action && <span onClick={onActionClick} style={{ fontFamily: MB.font, fontSize: 14, fontWeight: 600, color: MB.brand[600], cursor: 'pointer' }}>{action}</span>}
    </div>
  );
}

Object.assign(window, { Button, Chip, TypePill, VerifiedBadge, UrgencyStrip, Avatar, FactTile, CareerChip, Segmented, Input, SectionTitle });
