// Login — wires to POST /api/v2/auth/login.
// Poster pane shows live integration status so the screen isn't static.

function Login({ onLogin }) {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [forgotLoading, setForgotLoading] = React.useState(false);
  const [integrations, setIntegrations] = React.useState(null);

  // Public-ish health info to tell the staff the floor is up.
  React.useEffect(() => {
    fetch('/api/v2/health').catch(() => {});
  }, []);

  async function submit(e) {
    e.preventDefault();
    setErr(''); setInfo(''); setLoading(true);
    try {
      const data = await api.login(email.trim(), password);
      window.CURRENT_USER = {
        ...data.user,
        initials: initialsOf(data.user.name || data.user.email),
        color: colorFor(data.user.email || data.user.name || ''),
      };
      // Fire-and-forget: pull integration status once we have a token
      api.get('/api/v2/system/integrations-status')
        .then(s => setIntegrations(s?.integrations || []))
        .catch(() => {});
      onLogin(data.user);
    } catch (e) {
      setErr(e.message || 'Sign-in failed');
    } finally {
      setLoading(false);
    }
  }

  async function requestReset() {
    setErr(''); setInfo('');
    const em = email.trim();
    if (!em) {
      setErr('Enter your email above, then click Forgot password.');
      return;
    }
    setForgotLoading(true);
    try {
      await api.post('/api/v2/auth/forgot-password', { email: em }, { auth: false });
      setInfo('Reset request sent. The admin will forward the link to you via Telegram.');
    } catch (e) {
      setErr(e.message || 'Could not send reset request.');
    } finally {
      setForgotLoading(false);
    }
  }

  const liveIntegrations = integrations || [];
  const allGreen = liveIntegrations.length === 0 || liveIntegrations
    .filter(i => !i.coming_soon)
    .every(i => !!i.configured);
  const liveLabel = liveIntegrations.length === 0
    ? 'GHL · Telegram · Tommy'
    : liveIntegrations.filter(i => !i.coming_soon && i.configured).map(i => i.name.split(' ')[0]).join(' · ') || 'config missing';

  const nowStamp = new Date().toISOString().slice(0,10);

  return (
    <div className="login-root">
      <div className="login-poster">
        <div className="poster-head">
          <div><span className="dot" />RAW Athletic Club · Staff</div>
          <div>EST. <b>2021</b> · SF</div>
        </div>

        <div className="poster-mark">
          <h1 className="poster-wordmark" aria-label="RAW" style={{margin:0, lineHeight:0}}>
            <img
              src="/app/brand/logos/wordmark-white.svg"
              alt="RAW"
              style={{display:'block', width:'100%', maxWidth:520, height:'auto', userSelect:'none'}}
            />
          </h1>
          <div className="tagline">
            <span className="bar" />
            No filler · Train raw
          </div>
        </div>

        <div className="poster-foot">
          <div>
            <span className="label">Build</span>
            <b>v2.1.0</b><br/>
            {nowStamp}
          </div>
          <div>
            <span className="label">Region</span>
            <b>us-east-1</b><br/>
            RDS · healthy
          </div>
          <div>
            <span className="label">Integrations</span>
            <b>{liveLabel}</b><br/>
            {allGreen ? 'all green' : 'check system'}
          </div>
        </div>
      </div>

      <div className="login-form-pane">
        <div className="login-form-mark" aria-hidden="true">
          <img src="/app/brand/logos/wordmark-red.svg" alt="" />
        </div>
        <div className="eyebrow">— Staff access</div>
        <h1>Sign in.</h1>
        <p className="lede">Dashboard, Tommy approvals, and members. Use your club email.</p>

        <form onSubmit={submit}>
          <label className="field">
            <span className="flbl">Email</span>
            <input
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              autoComplete="email"
              placeholder="you@rawathletic.club"
              required
            />
          </label>
          <label className="field">
            <span className="flbl">Password</span>
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              autoComplete="current-password"
              required
            />
          </label>
          {err && (
            <div style={{
              padding:'10px 12px', marginBottom:16,
              background:'var(--warn-soft)', color:'var(--warn)',
              border:'1px solid transparent', borderRadius:4,
              fontSize:13,
            }}>{err}</div>
          )}
          {info && (
            <div style={{
              padding:'10px 12px', marginBottom:16,
              background:'var(--green-soft)', color:'var(--green)',
              border:'1px solid transparent', borderRadius:4,
              fontSize:13,
            }}>{info}</div>
          )}
          <div className="row">
            <label style={{display:'inline-flex', alignItems:'center', gap:8}}>
              <input type="checkbox" defaultChecked /> Keep me signed in
            </label>
            <a href="#" onClick={e => { e.preventDefault(); requestReset(); }} style={forgotLoading ? {pointerEvents:'none', opacity:0.6} : undefined}>
              {forgotLoading ? 'Sending…' : 'Forgot password'}
            </a>
          </div>
          <button type="submit" className="btn primary" disabled={loading}>
            {loading ? 'Signing in…' : 'Sign in'}
          </button>
        </form>
      </div>
    </div>
  );
}

function ResetPassword({ token, onDone }) {
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [done, setDone] = React.useState(false);

  async function submit(e) {
    e.preventDefault();
    setErr('');
    if (!token) { setErr('Missing reset token. Ask the admin for a new link.'); return; }
    if (password.length < 8) { setErr('Password must be at least 8 characters.'); return; }
    if (password !== confirm) { setErr('Passwords do not match.'); return; }
    setLoading(true);
    try {
      await api.post('/api/v2/auth/reset-password', { token, password }, { auth: false });
      setDone(true);
      setTimeout(() => {
        window.history.replaceState({}, '', '/');
        onDone && onDone();
      }, 1600);
    } catch (e) {
      setErr(e.message || 'Reset failed. The link may be invalid or expired.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="login-root">
      <div className="login-poster">
        <div className="poster-head">
          <div><span className="dot" />RAW Athletic Club · Staff</div>
          <div>EST. <b>2021</b> · SF</div>
        </div>
        <div className="poster-mark">
          <h1 className="poster-wordmark" aria-label="RAW" style={{margin:0, lineHeight:0}}>
            <img
              src="/app/brand/logos/wordmark-white.svg"
              alt="RAW"
              style={{width:'100%', maxWidth:520, height:'auto', display:'block'}}
            />
          </h1>
          <div className="tagline">
            <span className="bar" />
            Reset access · Secure handshake
          </div>
        </div>
        <div className="poster-foot">
          <div><span className="label">Token</span><b>2 hour window</b></div>
          <div><span className="label">Request</span><b>Forgot-password</b></div>
          <div><span className="label">Channel</span><b>Telegram admin</b></div>
        </div>
      </div>

      <div className="login-form-pane">
        <div className="login-form-mark" aria-hidden="true">
          <img src="/app/brand/logos/wordmark-red.svg" alt="" />
        </div>
        <div className="eyebrow">— Reset password</div>
        <h1>{done ? 'You’re all set.' : 'Set a new password.'}</h1>
        <p className="lede">
          {done
            ? 'Password updated. Taking you back to sign-in…'
            : 'Pick something you’ll remember. Min 8 characters. The link expires 2 hours after it was requested.'}
        </p>

        {!done && (
          <form onSubmit={submit}>
            <label className="field">
              <span className="flbl">New password</span>
              <input
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                autoFocus
                required
                minLength={8}
                disabled={loading}
              />
            </label>
            <label className="field">
              <span className="flbl">Confirm password</span>
              <input
                type="password"
                value={confirm}
                onChange={e => setConfirm(e.target.value)}
                required
                minLength={8}
                disabled={loading}
              />
            </label>

            {err && (
              <div style={{color:'var(--warn)', fontSize:13, marginBottom:16, padding:'8px 12px', background:'var(--warn-soft)', borderRadius:4}}>
                {err}
              </div>
            )}

            <button type="submit" className="btn primary" disabled={loading}>
              {loading ? 'Updating…' : 'Set new password'}
            </button>
          </form>
        )}

        <div className="sub-link">
          Already reset? <a href="#" onClick={e => {
            e.preventDefault();
            window.history.replaceState({}, '', '/');
            onDone && onDone();
          }}>Back to sign-in →</a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Login, ResetPassword });
