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 ap-gate-rich">
      <span className="ap-gate-ico" aria-hidden="true">👤</span>
      <h2>Your account</h2>
      <p>Log in to manage your profile and password, mint agent keys, and view your showcases.</p>
      <div className="ap-gate-cta"><button className="gm-cta-btn gm-cta-primary" onClick={() => setRoute('signin')}>Log in / Sign up</button></div>
    </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('legion')}>My Legion</button>
            <button className="px-action" onClick={() => setRoute('mansion')}>My 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>
  );
}
