// Sign-in + sign-up with email/password via Supabase auth.
// Toggle between "Sign in" and "Create account" modes in-place.

function SignInScreen({ palette }) {
  const [mode, setMode] = React.useState('signin');  // 'signin' | 'signup'
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [notice, setNotice] = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    if (!window.sb) {
      setError('Supabase client not initialized. Check config.js.');
      return;
    }
    setError(null); setNotice(null); setBusy(true);
    try {
      if (mode === 'signup') {
        const { data, error } = await window.sb.auth.signUp({ email, password });
        if (error) throw error;
        if (!data.session) {
          // Email confirmation is on; no session returned.
          setNotice('Check your email to confirm your account, then sign in.');
          setMode('signin');
          setPassword('');
        }
      } else {
        const { error } = await window.sb.auth.signInWithPassword({ email, password });
        if (error) throw error;
      }
    } catch (err) {
      setError(err.message || String(err));
    } finally {
      setBusy(false);
    }
  };

  const toggleMode = () => {
    setError(null); setNotice(null);
    setMode(m => m === 'signin' ? 'signup' : 'signin');
  };

  const isSignup = mode === 'signup';

  return (
    <div style={{
      padding: '0 0 40px',
      minHeight: '100%',
      display: 'flex', flexDirection: 'column',
      background: 'var(--bg)',
    }}>
      {/* Top: brand */}
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        padding: '80px 32px 0', textAlign: 'center',
      }}>
        <div style={{
          width: 76, height: 76, borderRadius: 22,
          background: palette.accent,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: `0 8px 24px ${palette.accent}40`,
          marginBottom: 28,
        }}>
          <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
            <rect x="7" y="11" width="22" height="22" rx="3" fill="#fff" opacity="0.18"/>
            <rect x="11" y="7" width="22" height="22" rx="3" fill="#fff"/>
            <circle cx="17" cy="16" r="1.6" fill={palette.accent}/>
            <circle cx="27" cy="16" r="1.6" fill={palette.accent}/>
            <circle cx="22" cy="22" r="1.6" fill={palette.accent}/>
            <circle cx="17" cy="27" r="1.6" fill={palette.accent}/>
            <circle cx="27" cy="27" r="1.6" fill={palette.accent}/>
          </svg>
        </div>

        <div style={{
          fontSize: 34, fontWeight: 700, color: 'var(--text-1)',
          letterSpacing: -0.8, lineHeight: 1.1,
        }}>Sugar Tracker</div>
        <div style={{
          fontSize: 16, color: 'var(--text-2)', marginTop: 10,
          maxWidth: 280, lineHeight: 1.45,
        }}>{isSignup
          ? 'Create an account to start tracking added and natural sugar.'
          : 'Sign in to see your sugar intake and history.'}</div>
      </div>

      {/* Bottom: form */}
      <form onSubmit={submit} style={{ padding: '24px 24px 16px' }}>
        <label style={fieldLabel}>Email</label>
        <input
          type="email"
          value={email}
          onChange={e => setEmail(e.target.value)}
          autoComplete="email"
          required
          style={fieldInput}
        />

        <label style={{ ...fieldLabel, marginTop: 12 }}>Password</label>
        <input
          type="password"
          value={password}
          onChange={e => setPassword(e.target.value)}
          autoComplete={isSignup ? 'new-password' : 'current-password'}
          minLength={6}
          required
          style={fieldInput}
        />

        {error && (
          <div style={{
            marginTop: 12, padding: '10px 12px', borderRadius: 10,
            background: palette.red + '14', color: palette.red,
            fontSize: 13, lineHeight: 1.4,
          }}>{error}</div>
        )}
        {notice && (
          <div style={{
            marginTop: 12, padding: '10px 12px', borderRadius: 10,
            background: palette.green + '14', color: palette.green,
            fontSize: 13, lineHeight: 1.4,
          }}>{notice}</div>
        )}

        <button
          type="submit"
          disabled={busy}
          style={{
            marginTop: 16,
            width: '100%', padding: '14px 16px', borderRadius: 14,
            background: palette.accent, color: '#fff',
            border: 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            fontFamily: 'inherit', fontSize: 16, fontWeight: 600,
            cursor: busy ? 'default' : 'pointer',
            opacity: busy ? 0.7 : 1,
          }}
        >
          {busy && (
            <span style={{
              width: 16, height: 16, borderRadius: 999,
              border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff',
              animation: 'spin 0.8s linear infinite',
            }}/>
          )}
          {busy
            ? (isSignup ? 'Creating account…' : 'Signing in…')
            : (isSignup ? 'Create account' : 'Sign in')}
        </button>

        <div style={{
          marginTop: 14, fontSize: 13, color: 'var(--text-2)', textAlign: 'center',
        }}>
          {isSignup ? 'Already have an account?' : "Don't have an account?"}
          {' '}
          <button type="button" onClick={toggleMode} style={{
            background: 'none', border: 'none', padding: 0,
            color: palette.accent, fontFamily: 'inherit', fontSize: 13,
            fontWeight: 600, cursor: 'pointer',
          }}>
            {isSignup ? 'Sign in' : 'Create one'}
          </button>
        </div>
      </form>

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

const fieldLabel = {
  display: 'block',
  fontSize: 11, fontWeight: 600, letterSpacing: 0.4,
  color: 'var(--text-2)', textTransform: 'uppercase',
  marginBottom: 6,
};

const fieldInput = {
  width: '100%', padding: '12px 14px', borderRadius: 12,
  background: 'var(--surface-1)', color: 'var(--text-1)',
  border: '1px solid var(--border)',
  fontFamily: 'inherit', fontSize: 16, outline: 'none',
  boxSizing: 'border-box',
};

window.SignInScreen = SignInScreen;
