import React, { useState } from 'react';
import { api } from './api.js';
import { KeysCard } from './AgentPlatform.jsx';
import { toast } from './toast.js';

function avatarStyle(name) { let h = 0; for (const ch of String(name)) h = (h * 31 + ch.charCodeAt(0)) >>> 0; const a = h % 360, b = (a + 70 + h % 90) % 360; return { background: `linear-gradient(135deg, hsl(${a} 68% 46%), hsl(${b} 64% 32%))` }; }

export default function Account({ auth, setRoute }) {
  const [cur, setCur] = useState('');
  const [nw, setNw] = useState('');
  const [err, setErr] = useState('');
  if (!auth.ready) return <div className="ap"><p>Loading…</p></div>;
  if (!auth.user) return <div className="ap ap-gate"><h2>Account</h2><p>Log in to manage your account.</p><button className="px-action" onClick={() => setRoute('signin')}>Go to Login</button></div>;
  const u = auth.user;
  const changePw = async (e) => {
    e.preventDefault(); setErr('');
    try { await api('/auth/password', { method: 'POST', body: { currentPassword: cur, newPassword: nw } }); setCur(''); setNw(''); toast('Password updated ✓'); }
    catch (e2) { setErr(e2.message); }
  };
  return (
    <div className="ap acct">
      <div className="ap-head"><h2>Account</h2></div>
      <div className="acct-grid">
        <div className="acct-card acct-profile">
          <span className="ap-avatar acct-avatar" style={avatarStyle(u.handle)}>{u.handle.slice(0, 2).toUpperCase()}</span>
          <h3>{u.handle}</h3>
          <p className="acct-email">{u.email}</p>
          <span className={`acct-role acct-role-${u.role}`}>{u.role}</span>
          <div className="acct-links">
            <button className="px-action" onClick={() => setRoute('booth')}>My Booth</button>
            <button className="px-action" onClick={() => setRoute('mansion')}>Mansion</button>
            <button className="px-action" onClick={() => auth.logout()}>Log out</button>
          </div>
        </div>
        <div className="acct-card">
          <h4 className="ap-h4">Change password</h4>
          <form className="acct-form" onSubmit={changePw}>
            <input type="password" placeholder="current password" value={cur} onChange={(e) => setCur(e.target.value)} required />
            <input type="password" placeholder="new password (min 6)" value={nw} onChange={(e) => setNw(e.target.value)} required minLength={6} />
            {err && <p className="px-auth-err">{err}</p>}
            <button className="px-action px-auth-submit" type="submit">Update password</button>
          </form>
        </div>
      </div>
      <KeysCard />
    </div>
  );
}
