/* global React */
const { useState } = React;

// ============================================================================
// Eyebrow — mono uppercase microcaps
// ============================================================================
function Eyebrow({ children, color, style }) {
  return (
    <div style={{
      fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 500,
      letterSpacing: '0.14em', textTransform: 'uppercase',
      color: color || 'var(--fg-subtle)', ...style,
    }}>{children}</div>
  );
}

// ============================================================================
// Button
// ============================================================================
function Button({ kind = 'primary', size = 'md', children, onClick, style, disabled }) {
  const base = {
    fontFamily: 'var(--font-sans)', fontWeight: 500, borderRadius: 6,
    border: '1px solid transparent', cursor: disabled ? 'not-allowed' : 'pointer',
    lineHeight: 1, letterSpacing: '-0.005em',
    transition: 'background 120ms, opacity 120ms, border-color 120ms',
    opacity: disabled ? 0.4 : 1,
    display: 'inline-flex', alignItems: 'center', gap: 6,
  };
  const sizes = {
    sm: { fontSize: 12, padding: '6px 10px' },
    md: { fontSize: 13, padding: '8px 14px' },
    lg: { fontSize: 14, padding: '11px 18px' },
  };
  const kinds = {
    primary:   { background: 'var(--signal)', color: '#fff' },
    secondary: { background: '#fff', color: 'var(--fg)', borderColor: 'var(--border-strong)' },
    ghost:     { background: 'transparent', color: 'var(--fg)' },
    danger:    { background: '#fff', color: 'var(--danger)', borderColor: 'var(--danger)' },
  };
  return (
    <button disabled={disabled} style={{ ...base, ...sizes[size], ...kinds[kind], ...style }} onClick={onClick}>
      {children}
    </button>
  );
}

// ============================================================================
// Avatar — monogram circle with member color
// ============================================================================
function Avatar({ member, size = 32, ring = false }) {
  return (
    <div title={member.name} style={{
      width: size, height: size, borderRadius: 999,
      background: member.color, color: '#fff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-mono)', fontWeight: 600,
      fontSize: Math.round(size * 0.36), letterSpacing: '0.03em',
      boxShadow: ring ? `0 0 0 2px var(--bg), 0 0 0 4px ${member.color}` : 'none',
      flexShrink: 0,
    }}>{member.initials}</div>
  );
}

// ============================================================================
// Card — hairline-bordered container
// ============================================================================
function Card({ children, pad = 24, style, hover = false, onClick }) {
  const [h, setH] = useState(false);
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        background: 'var(--bg-raised)',
        border: `1px solid ${(hover && h) ? 'var(--border-strong)' : 'var(--border)'}`,
        borderRadius: 'var(--radius-2)',
        padding: pad,
        cursor: onClick ? 'pointer' : 'default',
        transition: 'border-color 120ms',
        ...style,
      }}
    >{children}</div>
  );
}

// ============================================================================
// Pill / chip — status indicator
// ============================================================================
function Pill({ children, color = 'var(--fg-muted)', bg = 'var(--ink-50)', dot, style }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 500,
      letterSpacing: '0.06em', textTransform: 'uppercase',
      padding: '3px 8px', borderRadius: 2, background: bg, color,
      whiteSpace: 'nowrap',
      ...style,
    }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: 999, background: dot, display: 'inline-block' }} />}
      {children}
    </span>
  );
}

// ============================================================================
// Day-type badge — uses DAY_TYPES dot color
// ============================================================================
function DayBadge({ type, style }) {
  const d = window.DAY_TYPES.find(x => x.id === type);
  if (!d) return null;
  return <Pill dot={d.dot} style={style}>{d.label}</Pill>;
}

// ============================================================================
// Progress bar — for goal / completion
// ============================================================================
function Progress({ value, max = 100, color = 'var(--signal)', height = 6 }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  return (
    <div style={{
      width: '100%', height, background: 'var(--ink-50)',
      borderRadius: 999, overflow: 'hidden',
    }}>
      <div style={{
        width: `${pct}%`, height: '100%', background: color,
        transition: 'width 320ms var(--ease-out)',
      }} />
    </div>
  );
}

// ============================================================================
// Stat — large tabular number with eyebrow + sub
// ============================================================================
function Stat({ label, value, unit, sub, deltaPct, dir = 'higher' }) {
  // dir tells us how to color delta — for "lower is better" tests, negative is good.
  let deltaColor = 'var(--fg-muted)';
  if (deltaPct != null) {
    const good = dir === 'lower' ? deltaPct < 0 : deltaPct > 0;
    deltaColor = good ? 'var(--success)' : (deltaPct === 0 ? 'var(--fg-muted)' : 'var(--danger)');
  }
  return (
    <div>
      <Eyebrow>{label}</Eyebrow>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 8,
        fontFamily: 'var(--font-sans)', fontWeight: 500,
        letterSpacing: '-0.02em', color: 'var(--fg)',
        fontVariantNumeric: 'tabular-nums',
      }}>
        <span style={{ fontSize: 32 }}>{value}</span>
        {unit && <span style={{ fontSize: 13, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>{unit}</span>}
      </div>
      {(sub || deltaPct != null) && (
        <div style={{
          marginTop: 6, display: 'flex', gap: 10,
          fontFamily: 'var(--font-mono)', fontSize: 11,
          color: 'var(--fg-muted)', fontVariantNumeric: 'tabular-nums',
        }}>
          {deltaPct != null && (
            <span style={{ color: deltaColor }}>
              {deltaPct > 0 ? '+' : ''}{deltaPct.toFixed(1)}%
            </span>
          )}
          {sub && <span>{sub}</span>}
        </div>
      )}
    </div>
  );
}

// ============================================================================
// Section header — eyebrow + h-rule + (optional) action
// ============================================================================
function SectionHeader({ eyebrow, title, action, style }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16, ...style }}>
      <div>
        {eyebrow && <Eyebrow style={{ marginBottom: 6 }}>{eyebrow}</Eyebrow>}
        <h2 className="t-h3" style={{ margin: 0, fontSize: 22, fontWeight: 500, letterSpacing: '-0.015em' }}>{title}</h2>
      </div>
      {action}
    </div>
  );
}

// ============================================================================
// Toggle pill group — segmented control
// ============================================================================
function Segmented({ options, value, onChange, size = 'md' }) {
  const padding = size === 'sm' ? '4px 10px' : '6px 14px';
  const fontSize = size === 'sm' ? 11 : 12;
  return (
    <div style={{
      display: 'inline-flex',
      border: '1px solid var(--border)',
      borderRadius: 6, background: 'var(--bg-raised)',
      padding: 2,
    }}>
      {options.map(o => {
        const active = o.value === value;
        return (
          <button
            key={o.value}
            onClick={() => onChange(o.value)}
            style={{
              padding, fontSize, lineHeight: 1.2,
              fontFamily: 'var(--font-sans)', fontWeight: active ? 500 : 400,
              background: active ? 'var(--ink-950)' : 'transparent',
              color: active ? '#fff' : 'var(--fg-muted)',
              border: 'none', borderRadius: 4, cursor: 'pointer',
              transition: 'background 120ms, color 120ms',
            }}
          >{o.label}</button>
        );
      })}
    </div>
  );
}

// ============================================================================
// Tickbox — round signal-fill on check
// ============================================================================
function Tick({ checked, onChange, label, size = 22 }) {
  return (
    <button
      onClick={() => onChange(!checked)}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 10,
        background: 'transparent', border: 'none', cursor: 'pointer',
        padding: 0, color: 'var(--fg)', fontFamily: 'var(--font-sans)', fontSize: 13,
      }}
    >
      <span style={{
        width: size, height: size,
        border: `1.5px solid ${checked ? 'var(--signal)' : 'var(--border-strong)'}`,
        background: checked ? 'var(--signal)' : 'transparent',
        borderRadius: 4, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        transition: 'all 120ms var(--ease-standard)',
        flexShrink: 0,
      }}>
        {checked && (
          <svg width={size * 0.6} height={size * 0.6} viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12" />
          </svg>
        )}
      </span>
      {label && <span>{label}</span>}
    </button>
  );
}

// ============================================================================
// Sparkline — tiny inline trend
// ============================================================================
function Sparkline({ points, width = 100, height = 28, color = 'var(--signal)', dir = 'higher' }) {
  if (!points || points.length < 2) return <div style={{ width, height, background: 'var(--ink-25)', borderRadius: 2 }} />;
  const min = Math.min(...points);
  const max = Math.max(...points);
  const range = max - min || 1;
  const dx = width / (points.length - 1);
  const d = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${i * dx} ${height - ((p - min) / range) * height}`).join(' ');
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <path d={d} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
      <circle cx={width} cy={height - ((points[points.length - 1] - min) / range) * height} r="2.5" fill={color} />
    </svg>
  );
}

// ============================================================================
// Input
// ============================================================================
function Input({ value, onChange, placeholder, type = 'text', size = 'md', style, suffix }) {
  const padY = size === 'sm' ? 6 : 8;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      border: '1px solid var(--border-strong)', borderRadius: 4,
      background: 'var(--bg-raised)', padding: `${padY}px 10px`,
      transition: 'border-color 120ms, box-shadow 120ms',
      ...style,
    }}>
      <input
        type={type}
        value={value ?? ''}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          border: 'none', outline: 'none', background: 'transparent',
          fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg)',
          width: '100%', fontVariantNumeric: 'tabular-nums',
        }}
      />
      {suffix && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-subtle)', marginLeft: 6 }}>{suffix}</span>}
    </div>
  );
}

// Expose globally
Object.assign(window, {
  Eyebrow, Button, Avatar, Card, Pill, DayBadge, Progress, Stat,
  SectionHeader, Segmented, Tick, Sparkline, Input,
});
