// Tokens / primitives reused across the kit. Attached to window at bottom.
// Icon renders as a stable React-owned <span> wrapper; Lucide mutates the inner
// <i> into an <svg> in place, but React never needs to reconcile that inner node.

// Add animation keyframes
if (!document.getElementById('status-animations')) {
  const style = document.createElement('style');
  style.id = 'status-animations';
  style.textContent = `
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    .icon-rotating {
      animation: spin 1s linear infinite;
    }
  `;
  document.head.appendChild(style);
}

const Icon = ({ name, size = 16, color, strokeWidth = 1.5 }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current || !window.lucide) return;
    ref.current.innerHTML = `<i data-lucide="${name}"></i>`;
    window.lucide.createIcons({ nameAttr: 'data-lucide', attrs: { 'stroke-width': strokeWidth, width: size, height: size } });
  }, [name, size, strokeWidth]);
  return <span ref={ref} aria-hidden style={{
    width: size, height: size, display: 'inline-flex', alignItems: 'center',
    justifyContent: 'center', color, flexShrink: 0,
  }} />;
};

const SectionLabel = ({ children }) => (
  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--teal-ink)' }}>{children}</div>
);

const FieldLabel = ({ children }) => (
  <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)', display: 'flex', alignItems: 'center', gap: 6 }}>
    <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--green)' }} />
    {children}
  </div>
);

const Card = ({ children, style, variant, ...rest }) => {
  const variants = {
    default: { boxShadow: 'var(--shadow-sm)', borderRadius: 14 },
    elevated: { boxShadow: 'var(--shadow-lg)', borderRadius: 14 },
    flat: { boxShadow: 'none', borderRadius: 14 },
  };
  const v = variants[variant] || variants.default;
  return (
    <div {...rest} style={{
      background: 'var(--bg-card)', border: '1px solid var(--border)',
      padding: '20px 22px', ...v, ...style,
    }}>{children}</div>
  );
};

const SectionCard = ({ title, subtitle, action, children, pad = true }) => (
  <Card style={{ padding: pad ? '20px 22px' : 0 }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: children ? 18 : 0 }}>
      <div>
        <SectionLabel>{title}</SectionLabel>
        {subtitle && <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 4 }}>{subtitle}</div>}
      </div>
      {action}
    </div>
    {children}
  </Card>
);

const Button = ({ variant = 'primary-green', icon, children, onClick, style, disabled, size = 'md' }) => {
  const sizes = {
    sm: { padding: '6px 12px', fontSize: 12 },
    md: { padding: '10px 16px', fontSize: 13 },
    lg: { padding: '12px 20px', fontSize: 14, borderRadius: 12 },
  };
  const base = {
    display: 'inline-flex', alignItems: 'center', gap: 8,
    borderRadius: 10, fontWeight: 600, border: '1px solid transparent',
    cursor: disabled ? 'not-allowed' : 'pointer', lineHeight: 1,
    transition: 'transform 150ms ease-out, background 150ms', fontFamily: 'var(--font-sans)',
    opacity: disabled ? 0.5 : 1,
    ...sizes[size],
  };
  const variants = {
    'primary-green': { background: 'var(--green)', color: '#fff', boxShadow: 'inset 0 1px 0 rgba(255,255,255,.25)' },
    'primary-teal':  { background: 'var(--teal)', color: '#fff', boxShadow: 'inset 0 1px 0 rgba(255,255,255,.25)' },
    'tinted-teal':   { background: 'var(--teal-50)', color: 'var(--teal-ink)', borderColor: 'var(--teal-100)' },
    'tinted-green':  { background: 'var(--green-50)', color: 'var(--green-deep)', borderColor: 'var(--green-100)' },
    'tinted-orange': { background: 'var(--orange-50)', color: 'var(--orange-ink)', borderColor: 'var(--orange-100)' },
    'tinted-pink':   { background: 'var(--pink-50)', color: 'var(--pink-ink)', borderColor: 'var(--pink-100)' },
    'ghost':         { background: '#fff', color: 'var(--fg-2)', borderColor: 'var(--border)' },
    'ghost-pink':    { background: 'transparent', color: 'var(--pink-ink)', borderColor: 'var(--pink-100)' },
  };
  return (
    <button onClick={onClick} disabled={disabled} style={{ ...base, ...variants[variant], ...style }}
      onMouseDown={e => e.currentTarget.style.transform = 'scale(.98)'}
      onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
      {icon && <Icon name={icon} size={15} />}{children}
    </button>
  );
};

const IconButton = ({ icon, variant, onClick, disabled, title, className }) => {
  const variants = {
    default: { background: '#fff', borderColor: 'var(--border)', color: 'var(--fg-2)' },
    pink:    { background: 'var(--pink-50)', borderColor: 'var(--pink-100)', color: 'var(--pink-ink)' },
    teal:    { background: 'var(--teal-50)', borderColor: 'var(--teal-100)', color: 'var(--teal-ink)' },
    green:   { background: 'var(--green-50)', borderColor: 'var(--green-100)', color: 'var(--green-deep)' },
    orange:  { background: 'var(--orange-50,#FFF7ED)', borderColor: 'var(--orange-100,#FED7AA)', color: 'var(--orange,#F97316)' },
  }[variant || 'default'];
  return (
    <button onClick={onClick} disabled={disabled} title={title} style={{
      width: 32, height: 32, borderRadius: 8, border: '1px solid', display: 'inline-flex',
      alignItems: 'center', justifyContent: 'center', cursor: disabled ? 'not-allowed' : 'pointer',
      opacity: disabled ? 0.5 : 1, ...variants,
    }}><Icon name={icon} size={15} className={className} /></button>
  );
};

const StatusPill = ({ status, size = 'md' }) => {
  const statusConfig = {
    // Success states (green)
    SIGNIN_SUCCESS: { bg: '#D1FAE5', fg: '#065F46', icon: 'check-circle' },
    OTP_RECEIVED: { bg: '#D1FAE5', fg: '#065F46', icon: 'check-circle' },
    OTP_VERIFIED: { bg: '#D1FAE5', fg: '#065F46', icon: 'check-circle' },
    RESERVE_SUCCESS: { bg: '#D1FAE5', fg: '#065F46', icon: 'check-circle' },
    PAYMENT_SUCCESS: { bg: '#D1FAE5', fg: '#065F46', icon: 'check-circle' },

    // Retry/warning states (orange)
    OTP_FINDING: { bg: '#FEF3C7', fg: '#92400E', icon: 'clock', rotating: true },
    RESERVE_RETRYING: { bg: '#FEF3C7', fg: '#92400E', icon: 'refresh-cw', rotating: true },

    // Legacy states
    RUNNING: { bg: '#D1FAE5', fg: '#065F46', icon: 'play' },
    IDLE:    { bg: '#FEF3C7', fg: '#92400E', icon: 'pause' },
    STOPPED: { bg: '#E6EAF0', fg: '#6B7280', icon: 'stop-circle' },
    CANCEL:  { bg: '#FECACA', fg: '#7F1D1D', icon: 'x-circle' },

    // User roles
    Admin:    { bg: '#FBD5DF', fg: '#E02560', icon: 'shield-check' },
    Operator: { bg: '#EAF8FC', fg: '#2CB8D8', icon: 'user-check' },
    Viewer:   { bg: '#E6EAF0', fg: '#708098', icon: 'eye' },
  };

  const config = statusConfig[status] || { bg: '#F3F4F6', fg: '#6B7280', icon: 'help-circle' };
  const sizes = { sm: { padding: '4px 10px', fontSize: 10, gap: 4, iconSize: 12 }, md: { padding: '8px 12px', fontSize: 11, gap: 6, iconSize: 14 } };
  const s = sizes[size];

  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: s.gap, padding: s.padding, borderRadius: 8,
      fontSize: s.fontSize, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
      background: config.bg, color: config.fg, lineHeight: 1,
    }}>
      <span className={config.rotating ? 'icon-rotating' : ''}>
        <Icon name={config.icon} size={s.iconSize} color={config.fg} />
      </span>
      {status}
    </span>
  );
};

const Input = ({ label, value, onChange, placeholder, icon, suffix, mono, type = 'text', required, valueColor }) => {
  const [focused, setFocused] = React.useState(false);
  const [showPassword, setShowPassword] = React.useState(false);
  const isPassword = type === 'password';
  const inputType = isPassword && showPassword ? 'text' : type;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {label && <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)', display: 'flex', alignItems: 'center', gap: 6 }}>
        {required && <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--green)' }} />}
        {label}
      </div>}
      <div style={{
        height: 40, display: 'flex', alignItems: 'center', gap: 8, padding: '0 12px',
        background: '#fff', border: `1px solid ${focused ? 'var(--teal)' : 'var(--border)'}`,
        borderRadius: 10, boxShadow: focused ? 'var(--shadow-focus-teal)' : 'none',
        transition: 'box-shadow 150ms, border-color 150ms',
      }}>
        {icon && <Icon name={icon} size={15} color="var(--fg-3)" />}
        <input type={inputType} value={value ?? ''} placeholder={placeholder} onChange={e => onChange?.(e.target.value)}
          onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
          style={{ flex: 1, border: 0, outline: 0, background: 'transparent', fontFamily: mono ? 'var(--font-mono)' : 'var(--font-sans)', fontSize: 13, color: valueColor || 'var(--fg-1)', minWidth: 0 }} />
        {isPassword ? (
          <button type="button" onClick={() => setShowPassword(!showPassword)} style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center'
          }}>
            <Icon name={showPassword ? 'eye-off' : 'eye'} size={14} color="var(--fg-3)" />
          </button>
        ) : suffix}
      </div>
    </div>
  );
};

const Select = ({ label, value, placeholder, required, options = [], onChange }) => {
  const [open, setOpen] = React.useState(false);
  const [focused, setFocused] = React.useState(false);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, position: 'relative' }}>
      {label && <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-label)', display: 'flex', alignItems: 'center', gap: 6 }}>
        {required && <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--green)' }} />}
        {label}
      </div>}
      <div style={{
        height: 40, display: 'flex', alignItems: 'center', gap: 8, padding: '0 12px',
        background: '#fff', border: `1px solid ${focused || open ? 'var(--teal)' : 'var(--border)'}`,
        borderRadius: 10, boxShadow: focused || open ? 'var(--shadow-focus-teal)' : 'none',
        transition: 'box-shadow 150ms, border-color 150ms', cursor: 'pointer', position: 'relative'
      }} onClick={() => setOpen(!open)} onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}>
        <input type="text" value={value || ''} placeholder={placeholder} readOnly
          style={{ flex: 1, border: 0, outline: 0, background: 'transparent', fontSize: 13, color: value ? 'var(--fg-1)' : 'var(--fg-4)', cursor: 'pointer' }} />
        <Icon name={open ? 'chevron-up' : 'chevron-down'} size={14} color="var(--fg-3)" />
      </div>
      {open && options.length > 0 && (
        <div style={{
          position: 'absolute', top: '100%', left: 0, right: 0, background: '#fff', border: '1px solid var(--border)',
          borderRadius: 10, boxShadow: 'var(--shadow-lg)', zIndex: 10, marginTop: 8, maxHeight: 200, overflowY: 'auto'
        }}>
          {options.map((opt, i) => (
            <div key={i} onClick={() => { onChange?.(opt); setOpen(false); }}
              style={{
                padding: '10px 12px', cursor: 'pointer', borderBottom: i < options.length - 1 ? '1px solid var(--border-soft)' : 'none',
                background: value === opt ? 'var(--teal-50)' : 'transparent', color: value === opt ? 'var(--teal)' : 'var(--fg-1)',
                fontSize: 13, fontWeight: value === opt ? 600 : 500, transition: 'background 150ms'
              }}
              onMouseEnter={e => e.target.style.background = value === opt ? 'var(--teal-50)' : 'var(--bg-muted)'}
              onMouseLeave={e => e.target.style.background = value === opt ? 'var(--teal-50)' : 'transparent'}
            >
              {opt}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const ToggleBar = ({ icon, label, state, onToggle, color = 'teal' }) => {
  const on = state === 'ON';
  const colors = {
    teal: { on: { bg: 'var(--teal-50)', color: 'var(--teal-ink)' }, off: { bg: 'var(--bg-muted)', color: 'var(--fg-3)' } },
    blue: { on: { bg: 'var(--blue-50)', color: 'var(--blue)' }, off: { bg: 'var(--bg-muted)', color: 'var(--fg-3)' } },
  };
  const c = colors[color];
  const style = on ? c.on : c.off;
  return (
    <div onClick={onToggle} style={{
      flex: 1, height: 44, borderRadius: 10, display: 'flex', alignItems: 'center',
      justifyContent: 'space-between', padding: '0 14px', fontSize: 13, fontWeight: 600,
      background: style.bg, color: style.color,
      cursor: 'pointer', transition: 'background 150ms',
    }}>
      <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <Icon name={icon} size={16} />{label}
      </span>
      <span style={{ fontWeight: 700, letterSpacing: '0.08em', fontSize: 11 }}>{state}</span>
    </div>
  );
};

const Tabs = ({ options, value, onChange }) => (
  <div style={{ display: 'flex', background: 'var(--bg-muted)', borderRadius: 10, padding: 4, gap: 4 }}>
    {options.map(o => (
      <div key={o} onClick={() => onChange?.(o)} style={{
        flex: 1, height: 36, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
        color: value === o ? 'var(--teal-ink)' : 'var(--fg-3)',
        background: value === o ? 'var(--teal-50)' : 'transparent',
        cursor: 'pointer', transition: 'background 150ms',
      }}>{o}</div>
    ))}
  </div>
);

const ModalShell = ({ open, onClose, width = 520, icon, iconVariant = 'teal', title, subtitle, headerExtra, children, footer }) => {
  if (!open) return null;
  const iconColors = { teal: 'var(--teal)', green: 'var(--green)', pink: 'var(--pink)' };
  const iconBgs = { teal: 'var(--teal-50)', green: 'var(--green-50)', pink: 'var(--pink-50)' };
  return (
    <div className='modal-overlay' onClick={e => e.target === e.currentTarget && onClose?.()}>
      <Card style={{ width, maxHeight: '90vh', overflow: 'auto', padding: 0, display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border-soft)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', flex: 1, minWidth: 0 }}>
              {icon && <div style={{ width: 36, height: 36, borderRadius: 10, background: iconBgs[iconVariant], display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={icon} size={18} color={iconColors[iconVariant]} />
              </div>}
              <div style={{ flex: 1, minWidth: 0 }}>
                {title && <SectionLabel>{title}</SectionLabel>}
                {subtitle && <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>{subtitle}</div>}
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
              {headerExtra}
              <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center' }}>
                <Icon name='x' size={18} color='var(--fg-3)' />
              </button>
            </div>
          </div>
        </div>
        <div style={{ flex: 1, padding: '24px', overflow: 'auto' }}>{children}</div>
        {footer && <div style={{ padding: '16px 24px', borderTop: '1px solid var(--border-soft)', background: 'var(--bg-app-2)' }}>{footer}</div>}
      </Card>
    </div>
  );
};

const ModalFooter = ({ onClose, onConfirm, confirmLabel = 'Save', confirmIcon, confirmVariant = 'primary-green', cancelLabel = 'Cancel', disabled }) => (
  <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, width: '100%' }}>
    <Button variant='ghost' onClick={onClose}>{cancelLabel}</Button>
    <Button variant={confirmVariant} icon={confirmIcon} onClick={onConfirm} disabled={disabled}>{confirmLabel}</Button>
  </div>
);

const OtpInput = ({ value, onChange, onSubmit, size = 'md', autoFocus, placeholder = '000000' }) => {
  const sizes = { sm: { height: 28, fontSize: 14 }, md: { height: 48, fontSize: 20 } };
  const s = sizes[size];
  return (
    <input
      type='text'
      inputMode='numeric'
      value={value}
      onChange={e => onChange?.(e.target.value.replace(/\D/g, '').slice(0, 6))}
      onKeyDown={e => e.key === 'Enter' && onSubmit?.()}
      placeholder={placeholder}
      autoFocus={autoFocus}
      maxLength='6'
      style={{
        height: s.height, width: '100%', fontSize: s.fontSize, fontFamily: 'var(--font-mono)', fontWeight: 600,
        textAlign: 'center', border: `1px solid var(--border)`, borderRadius: 10,
        background: '#fff', color: 'var(--fg-1)', letterSpacing: 4,
        transition: 'box-shadow 150ms, border-color 150ms',
      }}
      onFocus={e => { e.target.style.borderColor = 'var(--teal)'; e.target.style.boxShadow = 'var(--shadow-focus-teal)'; }}
      onBlur={e => { e.target.style.borderColor = 'var(--border)'; e.target.style.boxShadow = 'none'; }}
    />
  );
};

const RoleSelector = ({ value, onChange, roles = ['superadmin', 'Operator'] }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <FieldLabel>Role</FieldLabel>
    <div style={{ display: 'flex', gap: 8 }}>
      {roles.map(role => {
        const label = role === 'superadmin' ? 'Admin' : role;
        return (
          <button key={role} onClick={() => onChange?.(role)} style={{
            flex: 1, height: 40, borderRadius: 10, fontSize: 12, fontWeight: 600, border: '1px solid',
            cursor: 'pointer', transition: 'background 150ms, border-color 150ms',
            background: value === role ? 'var(--teal-50)' : '#fff',
            color: value === role ? 'var(--teal-ink)' : 'var(--fg-2)',
            borderColor: value === role ? 'var(--teal-100)' : 'var(--border)',
          }}>{label}</button>
        );
      })}
    </div>
  </div>
);

const LimitSlider = ({ value, onChange, min = 0, max = 999, used, showUsage = true }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
    <FieldLabel>Profile Limit</FieldLabel>
    <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
      <input type='range' min={min} max={max} value={value} onChange={e => onChange?.(parseInt(e.target.value))} style={{ flex: 1 }} />
      <div style={{ fontSize: 14, fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--orange)', minWidth: 50, textAlign: 'right' }}>{value}</div>
    </div>
    {showUsage && used !== undefined && <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Currently using {used} of {value}</div>}
  </div>
);

const StatCard = ({ label, value, valueColor, icon, iconVariant = 'teal' }) => {
  const iconColors = { teal: 'var(--teal)', green: 'var(--green)', orange: 'var(--orange)', pink: 'var(--pink)' };
  const iconBgs = { teal: 'var(--teal-50)', green: 'var(--green-50)', orange: 'var(--orange-50)', pink: 'var(--pink-50)' };
  return (
    <Card style={{ position: 'relative', padding: '20px 20px' }}>
      {icon && <div style={{ position: 'absolute', top: 16, right: 16, width: 40, height: 40, borderRadius: 10, background: iconBgs[iconVariant], display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={18} color={iconColors[iconVariant]} />
      </div>}
      <SectionLabel>{label}</SectionLabel>
      <div style={{ fontSize: 28, fontFamily: 'var(--font-mono)', fontWeight: 700, marginTop: 12, color: valueColor || 'var(--fg-1)' }}>{value}</div>
    </Card>
  );
};

const EmptyState = ({ icon, title, subtitle, action }) => (
  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '60px 40px', textAlign: 'center' }}>
    {icon && <div style={{ marginBottom: 20 }}><Icon name={icon} size={48} color='var(--fg-3)' /></div>}
    <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--fg-1)', marginBottom: 8 }}>{title}</div>
    {subtitle && <div style={{ fontSize: 14, color: 'var(--fg-3)', marginBottom: 24 }}>{subtitle}</div>}
    {action && <div>{action}</div>}
  </div>
);

const InlineAlert = ({ variant = 'info', icon, children }) => {
  const variants = {
    info: { bg: 'var(--teal-50)', border: 'var(--teal-100)', color: 'var(--teal-ink)', icon: 'info' },
    success: { bg: 'var(--green-50)', border: 'var(--green-100)', color: 'var(--green-deep)', icon: 'check-circle' },
    warning: { bg: 'var(--orange-50)', border: 'var(--orange-100)', color: 'var(--orange-ink)', icon: 'alert-circle' },
    error: { bg: 'var(--pink-50)', border: 'var(--pink-100)', color: 'var(--pink-ink)', icon: 'x-circle' },
  };
  const v = variants[variant];
  return (
    <div style={{ display: 'flex', gap: 12, padding: '12px 14px', background: v.bg, border: `1px solid ${v.border}`, borderRadius: 10, color: v.color, fontSize: 13 }}>
      <Icon name={icon || v.icon} size={16} color={v.color} style={{ flexShrink: 0, marginTop: 1 }} />
      <div style={{ flex: 1 }}>{children}</div>
    </div>
  );
};

Object.assign(window, {
  Icon, SectionLabel, FieldLabel, Card, SectionCard, Button, IconButton,
  StatusPill, Input, Select, ToggleBar, Tabs,
  ModalShell, ModalFooter, OtpInput, RoleSelector, LimitSlider, StatCard, EmptyState, InlineAlert,
});
