/* Personal account settings — port of billing-account.jsx AccountSettingsScreen.
   Per-user preferences (vs Settings which is workspace-level).
   Wires to /api/auth/me; password change endpoint isn't implemented yet. */

function AccountScreen() {
  const me = Auth.getUser() || {};
  const [currentPw, setCurrentPw] = useState('');
  const [newPw, setNewPw]         = useState('');
  const [pwBusy, setPwBusy]       = useState(false);
  const [pwErr, setPwErr]         = useState(null);

  /* 2FA setup state — three steps:
     1. idle: show "Set up 2FA" button
     2. setup: backend returned secret + URI → show QR + verify input
     3. enabled: show backup codes (one-time) + disable button
     If user already has 2FA enabled (totp_enabled in JWT), skip to (3). */
  const [twofa, setTwofa] = useState({
    step: me.totp_enabled ? 'enabled' : 'idle',
    secret: null,
    uri: null,
    code: '',
    busy: false,
    err: null,
    backupCodes: null,
  });

  async function start2fa() {
    setTwofa((t) => ({ ...t, busy: true, err: null }));
    try {
      const res = await apiFetch('/api/auth/2fa/setup', { method: 'POST', body: JSON.stringify({}) });
      setTwofa((t) => ({ ...t, step: 'setup', secret: res.secret, uri: res.uri, busy: false }));
    } catch (err) {
      setTwofa((t) => ({ ...t, busy: false, err: err.message }));
    }
  }
  async function verify2fa() {
    setTwofa((t) => ({ ...t, busy: true, err: null }));
    try {
      const res = await apiFetch('/api/auth/2fa/verify', {
        method: 'POST',
        body: JSON.stringify({ code: twofa.code }),
      });
      setTwofa((t) => ({
        ...t,
        step: 'enabled',
        backupCodes: res.backup_codes || [],
        busy: false,
        code: '',
      }));
      window.toast && window.toast.success('Two-factor enabled — save your backup codes!');
      /* Update local user record so the chrome reflects the change. */
      const u = Auth.getUser();
      if (u) Auth.setSession(Auth.getToken(), { ...u, totp_enabled: true });
    } catch (err) {
      setTwofa((t) => ({ ...t, busy: false, err: err.message }));
    }
  }
  async function disable2fa() {
    const code = window.prompt('Enter your current 6-digit authenticator code to disable 2FA:');
    if (!code) return;
    setTwofa((t) => ({ ...t, busy: true, err: null }));
    try {
      await apiFetch('/api/auth/2fa/disable', {
        method: 'POST',
        body: JSON.stringify({ code: code.replace(/\s/g, '') }),
      });
      setTwofa({ step: 'idle', secret: null, uri: null, code: '', busy: false, err: null, backupCodes: null });
      const u = Auth.getUser();
      if (u) Auth.setSession(Auth.getToken(), { ...u, totp_enabled: false });
      window.toast && window.toast.success('Two-factor disabled');
    } catch (err) {
      setTwofa((t) => ({ ...t, busy: false, err: err.message }));
    }
  }

  async function changePassword() {
    setPwErr(null);
    if (!currentPw || !newPw) {
      setPwErr('Both current and new passwords are required.');
      return;
    }
    if (newPw.length < 8) {
      setPwErr('New password must be at least 8 characters.');
      return;
    }
    setPwBusy(true);
    try {
      await apiFetch('/api/auth/me/password', {
        method: 'POST',
        body: JSON.stringify({ current_password: currentPw, new_password: newPw }),
      });
      setCurrentPw(''); setNewPw('');
      window.toast && window.toast.success('Password updated');
    } catch (err) {
      setPwErr(err.message || 'Password change failed');
    } finally {
      setPwBusy(false);
    }
  }

  return (
    <div className="aq-content">
      <div className="aq-content-inner" style={{ maxWidth: 800 }}>
        <header style={{ marginBottom: 24 }}>
          <div className="aq-eyebrow">
            <span>Slate</span>
            <span className="aq-sep">·</span>
            <span>Personal account</span>
          </div>
          <h1 style={{
            fontFamily: 'var(--aq-ff-display)', fontSize: 26, fontWeight: 500,
            letterSpacing: '-0.012em', color: 'var(--aq-text)', margin: '4px 0 4px',
          }}>Account</h1>
          <p style={{ fontSize: 13, color: 'var(--aq-text-faint)', margin: 0 }}>
            Personal credentials and devices. Workspace-level settings live in Settings.
          </p>
        </header>

        <section className="x-card" style={{ padding: 22, marginBottom: 16 }}>
          <h2 style={{
            margin: '0 0 4px', fontFamily: 'var(--aq-ff-display)',
            fontSize: 14, fontWeight: 500, color: 'var(--aq-text)',
          }}>Identity</h2>
          <p style={{ margin: '0 0 18px', fontSize: 12, color: 'var(--aq-text-faint)' }}>
            Used for sign-in and audit trail.
          </p>
          <div className="x-form-field">
            <div className="x-form-label">Display name</div>
            <div className="x-form-control"><input className="x-input" defaultValue={me.name || ''} /></div>
          </div>
          <div className="x-form-field">
            <div className="x-form-label">Email</div>
            <div className="x-form-control"><input className="x-input" defaultValue={me.email || ''} disabled /></div>
          </div>
          <div className="x-form-field">
            <div className="x-form-label">User ID</div>
            <div className="x-form-control"><input className="x-input" defaultValue={me.id || ''} disabled style={{ fontFamily: 'var(--aq-ff-mono)', fontSize: 11 }} /></div>
          </div>
        </section>

        <section className="x-card" style={{ padding: 22, marginBottom: 16 }}>
          <h2 style={{
            margin: '0 0 4px', fontFamily: 'var(--aq-ff-display)',
            fontSize: 14, fontWeight: 500, color: 'var(--aq-text)',
          }}>Password & two-factor</h2>
          <p style={{ margin: '0 0 18px', fontSize: 12, color: 'var(--aq-text-faint)' }}>
            Change your password. Two-factor setup is coming next.
          </p>
          <div className="x-form-field">
            <div className="x-form-label">Current password</div>
            <div className="x-form-control">
              <input
                className="x-input"
                type="password"
                value={currentPw}
                onChange={(e) => setCurrentPw(e.target.value)}
                placeholder="Enter your current password"
              />
            </div>
          </div>
          <div className="x-form-field">
            <div className="x-form-label">New password</div>
            <div className="x-form-control">
              <input
                className="x-input"
                type="password"
                value={newPw}
                onChange={(e) => setNewPw(e.target.value)}
                placeholder="At least 8 characters"
              />
            </div>
          </div>
          {pwErr && (
            <div style={{
              margin: '0 0 12px', padding: '8px 12px', borderRadius: 6,
              background: 'color-mix(in srgb, var(--aq-danger) 12%, transparent)',
              color: 'var(--aq-danger)', fontSize: 12,
            }}>{pwErr}</div>
          )}
          <div className="x-form-field">
            <div className="x-form-label"></div>
            <div className="x-form-control">
              <button
                className="x-btn"
                onClick={changePassword}
                disabled={pwBusy || !currentPw || !newPw}
              >{pwBusy ? 'Updating…' : 'Update password'}</button>
            </div>
          </div>
          <div className="x-form-field">
            <div className="x-form-label">Two-factor</div>
            <div className="x-form-control" style={{ flexDirection: 'column', alignItems: 'flex-start', gap: 12 }}>
              {twofa.step === 'idle' && (
                <button
                  className="x-btn"
                  onClick={start2fa}
                  disabled={twofa.busy}
                ><Icon name="check" size={12} />{twofa.busy ? 'Generating…' : 'Set up authenticator app'}</button>
              )}

              {twofa.step === 'setup' && (
                <div style={{
                  padding: 14, borderRadius: 8, background: 'var(--aq-surface-2)',
                  border: '1px solid var(--aq-line)',
                  display: 'flex', flexDirection: 'column', gap: 12,
                  width: '100%', maxWidth: 420,
                }}>
                  <div style={{ fontSize: 12.5, color: 'var(--aq-text)' }}>
                    Open your authenticator app (1Password, Authy, Google Authenticator) and scan this QR — or paste the secret manually.
                  </div>
                  <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                    {twofa.uri && (
                      <img
                        src={`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(twofa.uri)}&size=160x160&margin=8&bgcolor=ffffff`}
                        alt="2FA QR code"
                        width={160}
                        height={160}
                        style={{ borderRadius: 6, background: '#fff', flexShrink: 0 }}
                      />
                    )}
                    <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                      <div style={{
                        fontFamily: 'var(--aq-ff-mono)', fontSize: 11.5,
                        padding: '6px 8px', borderRadius: 5,
                        background: 'var(--aq-surface)', border: '1px solid var(--aq-line)',
                        wordBreak: 'break-all', userSelect: 'all',
                      }}>{twofa.secret}</div>
                      <div style={{ fontSize: 11, color: 'var(--aq-text-faint)' }}>
                        Manual entry secret — copy/paste if you can't scan.
                      </div>
                    </div>
                  </div>
                  <input
                    className="x-input"
                    value={twofa.code}
                    onChange={(e) => setTwofa((t) => ({ ...t, code: e.target.value }))}
                    placeholder="6-digit code from your app"
                    style={{ width: '100%' }}
                  />
                  {twofa.err && (
                    <div style={{
                      padding: '6px 10px', borderRadius: 5,
                      background: 'color-mix(in srgb, var(--aq-danger) 12%, transparent)',
                      color: 'var(--aq-danger)', fontSize: 11.5,
                    }}>{twofa.err}</div>
                  )}
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button
                      onClick={() => setTwofa({ step: 'idle', secret: null, uri: null, code: '', busy: false, err: null, backupCodes: null })}
                      disabled={twofa.busy}
                      style={{
                        padding: '6px 12px', fontSize: 12,
                        background: 'transparent', border: '1px solid var(--aq-line)',
                        color: 'var(--aq-text-dim)', borderRadius: 7, cursor: 'pointer',
                      }}
                    >Cancel</button>
                    <button
                      onClick={verify2fa}
                      className="aq-btn-primary"
                      disabled={twofa.busy || !twofa.code}
                    >{twofa.busy ? 'Verifying…' : 'Verify & enable'}</button>
                  </div>
                </div>
              )}

              {twofa.step === 'enabled' && (
                <div style={{
                  padding: 14, borderRadius: 8, background: 'var(--aq-surface-2)',
                  border: '1px solid var(--aq-line)',
                  display: 'flex', flexDirection: 'column', gap: 10,
                  width: '100%', maxWidth: 420,
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{
                      width: 8, height: 8, borderRadius: '50%',
                      background: 'var(--aq-success)',
                      boxShadow: '0 0 8px var(--aq-success)',
                    }} />
                    <div style={{ fontSize: 13, color: 'var(--aq-text)' }}>
                      Two-factor is enabled
                    </div>
                  </div>
                  {twofa.backupCodes && twofa.backupCodes.length > 0 && (
                    <>
                      <div style={{
                        fontFamily: 'var(--aq-ff-mono)', fontSize: 9.5,
                        letterSpacing: '0.08em', textTransform: 'uppercase',
                        color: 'var(--aq-warn)',
                      }}>One-time backup codes — save these now</div>
                      <div style={{
                        padding: '8px 10px', borderRadius: 5,
                        background: 'var(--aq-surface)',
                        border: '1px solid var(--aq-line)',
                        fontFamily: 'var(--aq-ff-mono)', fontSize: 12,
                        display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 4,
                        userSelect: 'all',
                      }}>
                        {twofa.backupCodes.map((c) => <span key={c}>{c}</span>)}
                      </div>
                      <button
                        onClick={() => {
                          try { navigator.clipboard.writeText(twofa.backupCodes.join('\n')); window.toast && window.toast.success('Backup codes copied'); }
                          catch (_) {}
                        }}
                        style={{
                          padding: '6px 10px', fontSize: 11.5,
                          background: 'transparent', border: '1px solid var(--aq-line)',
                          color: 'var(--aq-text-dim)', borderRadius: 6,
                          cursor: 'pointer', alignSelf: 'flex-start',
                        }}
                      >Copy all</button>
                    </>
                  )}
                  <button
                    onClick={disable2fa}
                    disabled={twofa.busy}
                    style={{
                      padding: '6px 12px', fontSize: 12,
                      background: 'transparent', border: '1px solid var(--aq-line)',
                      color: 'var(--aq-danger)', borderRadius: 7,
                      cursor: 'pointer', alignSelf: 'flex-start',
                    }}
                  >{twofa.busy ? 'Disabling…' : 'Disable two-factor'}</button>
                  {twofa.err && (
                    <div style={{
                      padding: '6px 10px', borderRadius: 5,
                      background: 'color-mix(in srgb, var(--aq-danger) 12%, transparent)',
                      color: 'var(--aq-danger)', fontSize: 11.5,
                    }}>{twofa.err}</div>
                  )}
                </div>
              )}
            </div>
          </div>
        </section>

        <section className="x-card" style={{ padding: 22, marginBottom: 16 }}>
          <h2 style={{
            margin: '0 0 4px', fontFamily: 'var(--aq-ff-display)',
            fontSize: 14, fontWeight: 500, color: 'var(--aq-text)',
          }}>Sessions</h2>
          <p style={{ margin: '0 0 18px', fontSize: 12, color: 'var(--aq-text-faint)' }}>
            Active sign-ins. JWT expires in 24 hours.
          </p>
          <div className="x-session-row">
            <div className="x-session-icon"><Icon name="cpu" /></div>
            <div>
              <div className="x-session-name">
                This browser
                <span style={{
                  fontSize: 10, fontFamily: 'var(--aq-ff-mono)', color: 'var(--aq-success)',
                  background: 'color-mix(in srgb, var(--aq-success) 14%, transparent)',
                  padding: '1px 6px', borderRadius: 4, marginLeft: 6,
                }}>CURRENT</span>
              </div>
              <div className="x-session-meta">Signed in just now</div>
            </div>
            <button
              className="x-btn sm is-danger"
              onClick={() => {
                // See sidebar.jsx TopbarAvatar for rationale: clear local
                // state first, fire-and-forget the server cookie clear so
                // the redirect is instant even on a slow network, and use
                // location.replace so the back button can't return to a
                // signed-in view.
                Auth.clear();
                try { fetch('/api/auth/logout', { method: 'POST', credentials: 'include', keepalive: true }).catch(() => {}); }
                catch (_) {}
                window.location.replace('/cms/#login');
              }}
            >Sign out</button>
          </div>
        </section>
      </div>
    </div>
  );
}

window.AccountScreen = AccountScreen;
