/* global React */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ------------ Status Bar ------------
function StatusBar({ tone = 'dark', hideTime = false, time = '20:45' }) {
  // tone: 'dark' (white text on dark) | 'light' (black text on light)
  const stroke = tone === 'light' ? '#111' : '#fff';
  return (
    <div className={`status-bar ${tone}`}>
      <div className="mono" style={{ fontSize: 15, fontWeight: 600, letterSpacing: '0.02em' }}>
        {hideTime ? '' : time}
      </div>
      <div className="right">
        {/* signal */}
        <svg width="18" height="11" viewBox="0 0 18 11" fill="none">
          {[3, 5, 7, 9].map((h, i) => (
            <rect key={i} x={i * 4} y={11 - h} width="3" height={h} rx="0.5" fill={stroke} />
          ))}
        </svg>
        {/* wifi */}
        <svg width="16" height="11" viewBox="0 0 16 11" fill="none">
          <path d="M8 9.5a1.2 1.2 0 100-2.4 1.2 1.2 0 000 2.4z" fill={stroke} />
          <path d="M3.2 5.6a7 7 0 019.6 0" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" fill="none" />
          <path d="M1 3.2a10.5 10.5 0 0114 0" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" fill="none" />
        </svg>
        {/* battery */}
        <svg width="26" height="12" viewBox="0 0 26 12" fill="none">
          <rect x="0.6" y="0.6" width="22" height="10.8" rx="2.4" stroke={stroke} strokeWidth="1" fill="none" opacity="0.5" />
          <rect x="2.2" y="2.2" width="18" height="7.6" rx="1.4" fill={stroke} />
          <rect x="23.5" y="4" width="1.6" height="4" rx="0.8" fill={stroke} opacity="0.5" />
        </svg>
      </div>
    </div>
  );
}

// ------------ Logo wordmark ------------
function Wordmark({ size = 18, tone = 'light' }) {
  const c = tone === 'light' ? '#fff' : '#111';
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      color: c, fontFamily: 'var(--display)',
      fontSize: size, letterSpacing: '0.02em',
      textTransform: 'uppercase',
    }}>
      {/* tiny flag-flash mark */}
      <svg width={size * 0.9} height={size * 0.9} viewBox="0 0 24 24" fill="none">
        <path d="M5 3v18M5 4c5 -2 8 2 13 0v9c-5 2 -8 -2 -13 0" stroke={c} strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round" fill="none" />
      </svg>
      <span>TEAM SPARK</span>
    </div>
  );
}

// ------------ Onboarding dot-grid visuals ------------
function StadiumGrid({ variant = 0, accent = '#FFB300' }) {
  // Abstract grid of dots simulating a stadium of phone lights
  const cols = 24, rows = 14;
  const dots = useMemo(() => {
    const arr = [];
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        arr.push({ r, c, seed: (r * 31 + c * 17) % 100 / 100 });
      }
    }
    return arr;
  }, []);

  const [phase, setPhase] = useState(0);
  useEffect(() => {
    if (variant !== 1) return;
    const t = setInterval(() => setPhase((p) => (p + 1) % 2), 700);
    return () => clearInterval(t);
  }, [variant]);

  return (
    <div style={{
      position: 'relative',
      width: '100%', height: '100%',
      display: 'grid',
      gridTemplateColumns: `repeat(${cols}, 1fr)`,
      gridTemplateRows: `repeat(${rows}, 1fr)`,
      gap: 4,
      padding: 18,
      perspective: 600,
    }}>
      {dots.map((d, i) => {
        // chance of being lit depends on variant
        let lit = false;
        let color = '#383d42';
        if (variant === 0) {
          // scattered random highlights
          lit = d.seed > 0.78;
          color = d.seed > 0.92 ? accent : (d.seed > 0.86 ? '#fff' : color);
        } else if (variant === 1) {
          // synchronized pulse — all "on" in same phase
          lit = (d.r + d.c + phase) % 2 === 0 ? true : d.seed > 0.6;
          color = ((d.r + d.c + phase) % 2 === 0) ? accent : '#42464c';
        } else if (variant === 2) {
          // battery — half lit, gradient bottom-up
          const t = 1 - d.r / rows;
          lit = t > 0.4;
          color = t > 0.7 ? accent : (t > 0.5 ? '#357545' : '#383d42');
        }
        const size = 4 + (d.seed * 2);
        return (
          <div key={i} style={{
            width: size, height: size,
            borderRadius: '50%',
            background: lit ? color : '#2f3338',
            opacity: lit ? 1 : 0.4,
            boxShadow: lit ? `0 0 ${6 + d.seed * 6}px ${color}` : 'none',
            transition: 'all 700ms cubic-bezier(.4,0,.2,1)',
            justifySelf: 'center', alignSelf: 'center',
          }} />
        );
      })}
      {/* horizon line — suggests stadium tier */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: '55%', height: 1,
        background: 'linear-gradient(90deg, transparent, rgba(115,122,130,0.4), transparent)',
        pointerEvents: 'none',
      }} />
    </div>
  );
}

// ------------ Pill Button ------------
function PrimaryButton({ children, onClick, disabled, style, color = '#fff', textColor = '#111' }) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      style={{
        width: '100%',
        height: 56,
        background: disabled ? '#42464c' : color,
        color: disabled ? '#737a82' : textColor,
        borderRadius: 16,
        fontFamily: 'var(--sans)',
        fontWeight: 700,
        fontSize: 16,
        letterSpacing: '0.02em',
        textTransform: 'uppercase',
        cursor: disabled ? 'not-allowed' : 'pointer',
        transition: 'transform .15s ease, opacity .15s',
        ...style,
      }}
      onPointerDown={(e) => !disabled && (e.currentTarget.style.transform = 'scale(0.98)')}
      onPointerUp={(e) => (e.currentTarget.style.transform = 'scale(1)')}
      onPointerLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}
    >
      {children}
    </button>
  );
}

// ------------ Text field ------------
function TextField({ label, value, onChange, type = 'text', placeholder, error, autoFocus }) {
  const [focused, setFocused] = useState(false);
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{
        fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em',
        color: error ? 'var(--danger)' : 'var(--ink-3)',
        fontWeight: 600,
      }}>
        {label}
      </span>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        autoFocus={autoFocus}
        autoCapitalize="none"
        autoCorrect="off"
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          height: 52,
          padding: '0 16px',
          background: 'var(--bg-2)',
          border: `1.5px solid ${error ? 'var(--danger)' : (focused ? 'var(--ink)' : 'var(--line)')}`,
          borderRadius: 14,
          color: 'var(--ink)',
          fontSize: 16,
          width: '100%',
          fontFamily: 'var(--sans)',
          transition: 'border-color .15s',
        }}
      />
      {error && (
        <span style={{
          fontSize: 12, color: 'var(--danger)', fontWeight: 600,
          fontFamily: 'var(--sans)',
        }}>
          {error}
        </span>
      )}
    </label>
  );
}

Object.assign(window, {
  StatusBar, Wordmark, StadiumGrid, PrimaryButton, TextField,
});
