/**
 * Account widget — renders the topbar email pill as a dropdown trigger and
 * mounts an Account Settings modal that handles change-password and
 * recovery-email management.
 *
 * Two pieces:
 *   <AccountWidget /> — drop-in replacement for the topbar email/sign-out span
 *   AccountModal      — the modal it opens (kept private to this file)
 *
 * Talks to the same API the rest of the dashboard uses, picking up
 * window.__GE_API_BASE__ + the bearer in localStorage.apiKey.
 */
function AccountWidget() {
  const [open, setOpen] = React.useState(false);
  const [modalOpen, setModalOpen] = React.useState(false);
  const email = (typeof localStorage !== 'undefined' && localStorage.getItem('userEmail')) || '';
  const ref = React.useRef(null);

  React.useEffect(() => {
    function onClick(e) {
      if (!ref.current) return;
      if (!ref.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  if (!email) return null;

  return (
    <div ref={ref} style={{position:'relative'}}>
      <span className="range-pill" style={{cursor:'pointer'}}
            onClick={() => setOpen(o => !o)}>
        {email}{' '}<Icon name="chev" size={11}/>
      </span>
      {open && (
        <div className="panel" style={{
          position:'absolute', top:'calc(100% + 6px)', right:0, minWidth:220,
          padding:0, zIndex:50, boxShadow:'0 8px 32px rgba(0,0,0,0.12)',
        }}>
          <div style={{padding:'12px 14px', borderBottom:'1px solid var(--border-light)'}}>
            <div className="mono-label" style={{fontSize:9, marginBottom:4}}>Signed in as</div>
            <div style={{fontSize:13, color:'var(--text)', wordBreak:'break-all'}}>{email}</div>
          </div>
          <button className="account-menu-item"
                  onClick={() => { setOpen(false); setModalOpen(true); }}>
            Account settings
          </button>
          <button className="account-menu-item"
                  onClick={() => window.__GE_SIGN_OUT__ && window.__GE_SIGN_OUT__()}>
            Sign out
          </button>
        </div>
      )}
      {modalOpen && <AccountModal email={email} onClose={() => setModalOpen(false)}/>}
    </div>
  );
}

function AccountModal({ email, onClose }) {
  const apiBase = typeof window.__GE_API_BASE__ === 'string'
    ? window.__GE_API_BASE__
    : (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' ? 'http://localhost:3001' : '');
  const token = (typeof localStorage !== 'undefined' && localStorage.getItem('apiKey')) || '';

  const [recoveryEmail, setRecoveryEmail] = React.useState('');
  const [recoveryLoaded, setRecoveryLoaded] = React.useState(false);
  const [recoveryMsg, setRecoveryMsg] = React.useState(null);
  const [recoverySaving, setRecoverySaving] = React.useState(false);

  const [currentPwd, setCurrentPwd] = React.useState('');
  const [newPwd, setNewPwd] = React.useState('');
  const [confirmPwd, setConfirmPwd] = React.useState('');
  const [pwdMsg, setPwdMsg] = React.useState(null);
  const [pwdSaving, setPwdSaving] = React.useState(false);
  const [showCurrent, setShowCurrent] = React.useState(false);
  const [showNew, setShowNew] = React.useState(false);
  const [showConfirm, setShowConfirm] = React.useState(false);

  React.useEffect(() => {
    fetch(apiBase + '/api/auth/recovery-email', { headers: { Authorization: `Bearer ${token}` } })
      .then(r => r.ok ? r.json() : { recovery_email: null })
      .then(d => { setRecoveryEmail(d.recovery_email || ''); setRecoveryLoaded(true); })
      .catch(() => setRecoveryLoaded(true));
  }, []);

  async function saveRecoveryEmail(e) {
    e.preventDefault();
    setRecoveryMsg(null);
    setRecoverySaving(true);
    try {
      const res = await fetch(apiBase + '/api/auth/recovery-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ recovery_email: recoveryEmail.trim() || null }),
      });
      const d = await res.json();
      if (!res.ok) throw new Error(d.error || 'Save failed');
      setRecoveryMsg({ kind: 'ok', text: 'Recovery email saved.' });
    } catch (err) {
      setRecoveryMsg({ kind: 'err', text: err.message });
    } finally {
      setRecoverySaving(false);
    }
  }

  async function changePassword(e) {
    e.preventDefault();
    setPwdMsg(null);
    if (newPwd.length < 8) {
      setPwdMsg({ kind:'err', text:'New password must be at least 8 characters.' });
      return;
    }
    if (newPwd !== confirmPwd) {
      setPwdMsg({ kind:'err', text:'New password and confirmation do not match.' });
      return;
    }
    setPwdSaving(true);
    try {
      const res = await fetch(apiBase + '/api/auth/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ current_password: currentPwd, new_password: newPwd }),
      });
      const d = await res.json();
      if (!res.ok) throw new Error(d.error || 'Change failed');
      setPwdMsg({ kind:'ok', text:'Password changed. Use the new password next sign-in.' });
      setCurrentPwd(''); setNewPwd(''); setConfirmPwd('');
    } catch (err) {
      setPwdMsg({ kind:'err', text: err.message });
    } finally {
      setPwdSaving(false);
    }
  }

  return (
    <div className="account-modal-backdrop" onClick={onClose}>
      <div className="account-modal" onClick={e => e.stopPropagation()}>
        <div className="account-modal-head">
          <h3>Account settings</h3>
          <button className="icon-btn" onClick={onClose} aria-label="Close">
            <Icon name="x" size={14}/>
          </button>
        </div>

        <div className="account-modal-body">
          <div style={{marginBottom:8}}>
            <div className="mono-label" style={{fontSize:9, marginBottom:3}}>Signed in as</div>
            <div style={{fontSize:13, color:'var(--text)'}}>{email}</div>
          </div>

          <hr style={{border:0, borderTop:'1px solid var(--border-light)', margin:'18px 0'}}/>

          <form onSubmit={saveRecoveryEmail}>
            <h4 style={{margin:'0 0 4px', fontSize:13}}>Recovery email</h4>
            <div style={{fontSize:12, color:'var(--text-muted)', marginBottom:10, lineHeight:1.5}}>
              We send password reset links to this address. Use a real inbox you can access.
            </div>
            <input type="email" value={recoveryEmail}
                   onChange={e => setRecoveryEmail(e.target.value)}
                   disabled={!recoveryLoaded}
                   placeholder="you@example.com"
                   className="account-input"/>
            {recoveryMsg && (
              <div className={`account-msg ${recoveryMsg.kind}`}>{recoveryMsg.text}</div>
            )}
            <button type="submit" className="btn btn-secondary" disabled={recoverySaving} style={{marginTop:10}}>
              {recoverySaving ? 'Saving…' : 'Save recovery email'}
            </button>
          </form>

          <hr style={{border:0, borderTop:'1px solid var(--border-light)', margin:'22px 0 18px'}}/>

          <form onSubmit={changePassword}>
            <h4 style={{margin:'0 0 4px', fontSize:13}}>Change password</h4>
            <div style={{fontSize:12, color:'var(--text-muted)', marginBottom:10, lineHeight:1.5}}>
              Minimum 8 characters. You'll stay signed in after changing.
            </div>
            <label className="account-label">Current password</label>
            <div className="account-input-wrap">
              <input type={showCurrent ? 'text' : 'password'} value={currentPwd}
                     onChange={e => setCurrentPwd(e.target.value)}
                     autoComplete="current-password" className="account-input"/>
              <button type="button" className="password-toggle-btn"
                      onClick={() => setShowCurrent(s => !s)}
                      aria-label={showCurrent ? 'Hide password' : 'Show password'}
                      aria-pressed={showCurrent}>
                <Icon name={showCurrent ? 'eyeOff' : 'eye'} size={16}/>
              </button>
            </div>
            <label className="account-label">New password</label>
            <div className="account-input-wrap">
              <input type={showNew ? 'text' : 'password'} value={newPwd}
                     onChange={e => setNewPwd(e.target.value)}
                     autoComplete="new-password" className="account-input"/>
              <button type="button" className="password-toggle-btn"
                      onClick={() => setShowNew(s => !s)}
                      aria-label={showNew ? 'Hide password' : 'Show password'}
                      aria-pressed={showNew}>
                <Icon name={showNew ? 'eyeOff' : 'eye'} size={16}/>
              </button>
            </div>
            <label className="account-label">Confirm new password</label>
            <div className="account-input-wrap">
              <input type={showConfirm ? 'text' : 'password'} value={confirmPwd}
                     onChange={e => setConfirmPwd(e.target.value)}
                     autoComplete="new-password" className="account-input"/>
              <button type="button" className="password-toggle-btn"
                      onClick={() => setShowConfirm(s => !s)}
                      aria-label={showConfirm ? 'Hide password' : 'Show password'}
                      aria-pressed={showConfirm}>
                <Icon name={showConfirm ? 'eyeOff' : 'eye'} size={16}/>
              </button>
            </div>
            {pwdMsg && (
              <div className={`account-msg ${pwdMsg.kind}`}>{pwdMsg.text}</div>
            )}
            <button type="submit" className="btn btn-secondary"
                    disabled={pwdSaving || !currentPwd || !newPwd || !confirmPwd}
                    style={{marginTop:10}}>
              {pwdSaving ? 'Changing…' : 'Change password'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

window.AccountWidget = AccountWidget;
