/* AuthKit.jsx — interactive form primitives for the Muna onboarding flow.
   Exports to window: TextField, SocialButton, OrDivider, PaperGrain,
   AppleGlyph, GoogleGlyph, validateEmail */

// ─── Paper grain — the ~3-5% texture permitted on splash + onboarding hero ──
function PaperGrain({ opacity = 0.05, on = true }) {
  if (!on) return null;
  return (
    <div aria-hidden="true" style={{
      position: 'absolute', inset: 0, pointerEvents: 'none', opacity,
      backgroundImage:
        'radial-gradient(circle at 18% 26%, #57534E 0 1px, transparent 1.4px), ' +
        'radial-gradient(circle at 64% 72%, #57534E 0 1px, transparent 1.4px), ' +
        'radial-gradient(circle at 88% 38%, #57534E 0 0.8px, transparent 1.2px)',
      backgroundSize: '11px 11px, 15px 15px, 9px 9px',
    }}/>
  );
}

// ─── Small inline glyphs ────────────────────────────────────────────────
function EyeGlyph({ off = false }) {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
      {off ? (
        <>
          <path d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 10 8 10 8a13.16 13.16 0 01-1.67 2.68"/>
          <path d="M6.61 6.61A13.5 13.5 0 002 12s3 8 10 8a9.7 9.7 0 005.39-1.61"/>
          <path d="M14.12 14.12A3 3 0 119.88 9.88"/>
          <path d="M2 2l20 20"/>
        </>
      ) : (
        <>
          <path d="M2 12s3-8 10-8 10 8 10 8-3 8-10 8-10-8-10-8z"/>
          <circle cx="12" cy="12" r="3"/>
        </>
      )}
    </svg>
  );
}

function AppleGlyph({ color = '#fff', size = 19 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} style={{ display: 'block', marginTop: -2 }}>
      <path d="M17.05 12.54c-.03-2.6 2.12-3.85 2.22-3.91-1.21-1.77-3.1-2.01-3.77-2.04-1.6-.16-3.13.94-3.94.94-.81 0-2.07-.92-3.4-.9-1.75.03-3.36 1.02-4.26 2.58-1.82 3.15-.47 7.82 1.31 10.38.87 1.25 1.9 2.66 3.26 2.61 1.31-.05 1.8-.85 3.39-.85 1.58 0 2.03.85 3.41.82 1.41-.02 2.3-1.28 3.16-2.54 1-1.46 1.41-2.87 1.43-2.94-.03-.01-2.74-1.05-2.77-4.16zM14.5 4.78c.72-.87 1.2-2.08 1.07-3.28-1.03.04-2.28.69-3.02 1.56-.66.77-1.24 2-1.09 3.18 1.15.09 2.32-.59 3.04-1.46z"/>
    </svg>
  );
}

function GoogleGlyph({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block' }}>
      <path fill="#4285F4" d="M22.5 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.9a5.04 5.04 0 01-2.19 3.31v2.76h3.55c2.08-1.92 3.24-4.74 3.24-8.08z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.55-2.76c-.98.66-2.24 1.06-3.73 1.06-2.87 0-5.3-1.94-6.16-4.55H2.16v2.85A11 11 0 0012 23z"/>
      <path fill="#FBBC05" d="M5.84 14.09a6.6 6.6 0 010-4.18V7.06H2.16a11 11 0 000 9.88l3.68-2.85z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 002.16 7.06l3.68 2.85C6.7 7.3 9.13 5.38 12 5.38z"/>
    </svg>
  );
}

// ─── Email validation ──────────────────────────────────────────────────
function validateEmail(v) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test((v || '').trim());
}

// ─── TextField — real, controlled input with focus + error states ───────
function TextField({
  label, type = 'text', value, onChange, placeholder, error, hint,
  autoComplete, name, trailing, onEnter, autoFocus = false,
}) {
  const [focused, setFocused] = React.useState(false);
  const [reveal, setReveal] = React.useState(false);
  const isPw = type === 'password';
  const inputType = isPw ? (reveal ? 'text' : 'password') : type;
  const border = error ? 'var(--clay-500)' : focused ? 'var(--amber-500)' : 'var(--border-default)';
  const bw = focused || error ? 2 : 1;
  const pad = 15 - (bw - 1);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <label style={{ font: 'var(--type-label)', color: 'var(--fg-2)' }}>{label}</label>
        {trailing}
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        background: '#fff', border: `${bw}px solid ${border}`,
        borderRadius: 'var(--radius-m)', padding: `${pad}px ${pad + 1}px`,
        boxShadow: focused ? 'var(--focus-ring)' : 'var(--shadow-xs)',
        transition: 'border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)',
      }}>
        <input
          type={inputType}
          name={name}
          value={value}
          autoComplete={autoComplete}
          autoFocus={autoFocus}
          placeholder={placeholder}
          onChange={e => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onKeyDown={e => { if (e.key === 'Enter' && onEnter) onEnter(); }}
          style={{
            flex: 1, minWidth: 0, border: 0, outline: 'none', background: 'transparent',
            font: 'var(--type-body)', color: 'var(--fg-1)', padding: 0,
          }}
        />
        {isPw && (
          <button type="button" onClick={() => setReveal(r => !r)}
            aria-label={reveal ? 'Hide password' : 'Show password'}
            style={{
              background: 'transparent', border: 0, cursor: 'pointer',
              color: 'var(--fg-3)', display: 'flex', padding: 2, flexShrink: 0,
            }}>
            <EyeGlyph off={reveal}/>
          </button>
        )}
      </div>
      {(hint || error) && (
        <div style={{ font: 'var(--type-body-s)', color: error ? 'var(--clay-500)' : 'var(--fg-3)', textWrap: 'pretty' }}>
          {error || hint}
        </div>
      )}
    </div>
  );
}

// ─── SocialButton — Apple (dark) / Google (white outline) ───────────────
function SocialButton({ provider = 'apple', label, onClick }) {
  const apple = provider === 'apple';
  const [pressed, setPressed] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      style={{
        width: '100%', height: 54, borderRadius: 'var(--radius-pill)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        font: 'var(--type-button)', cursor: 'pointer',
        background: apple ? 'var(--stone-800)' : '#fff',
        color: apple ? '#fff' : 'var(--fg-1)',
        border: apple ? '0' : '1.5px solid var(--border-default)',
        boxShadow: apple ? 'none' : 'var(--shadow-xs)',
        transform: pressed ? 'scale(0.985)' : 'scale(1)',
        transition: 'transform 80ms var(--ease-out)',
      }}>
      {apple ? <AppleGlyph/> : <GoogleGlyph/>}
      {label}
    </button>
  );
}

// ─── OrDivider ──────────────────────────────────────────────────────────
function OrDivider({ label = 'or' }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <div style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }}/>
      <div style={{ font: 'var(--type-caption)', color: 'var(--fg-3)', letterSpacing: 'var(--tracking-wide)', whiteSpace: 'nowrap', flexShrink: 0 }}>{label}</div>
      <div style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }}/>
    </div>
  );
}

Object.assign(window, { TextField, SocialButton, OrDivider, PaperGrain, AppleGlyph, GoogleGlyph, validateEmail, EyeGlyph });
