// ─────────────────────────────────────────────
// DO_Profile.jsx — User profile modal
// Change email, password, phone (2FA)
// Opened from nav bar user menu
// ─────────────────────────────────────────────

const API_BASE_P = window.API_BASE || '';

async function profilePost(endpoint, body, jwt) {
  const res = await fetch(`${API_BASE_P}/v6/auth/${endpoint}`, {
    method:  'POST',
    headers: {
      'Content-Type':  'application/json',
      'Authorization': `Bearer ${jwt}`,
    },
    body: JSON.stringify(body),
  });
  return res.json();
}

async function profileGet(endpoint, jwt) {
  const res = await fetch(`${API_BASE_P}/v6/auth/${endpoint}`, {
    method:  'GET',
    headers: { 'Authorization': `Bearer ${jwt}` },
  });
  return res.json();
}

function DOProfile({ user, jwt, appId, onClose, onUserUpdate }) {

  const [tab,          setTab]          = React.useState('profile');
  const [loading,      setLoading]      = React.useState(false);
  const [error,        setError]        = React.useState(null);
  const [success,      setSuccess]      = React.useState(null);
  const [userData,     setUserData]     = React.useState(user || {});

  // Fetch fresh user data on mount — JWT may be stale
  React.useEffect(() => {
    profileGet('profile/me', jwt)
      .then(data => {
        if (data.status === 'ok') {
          const u = {
            ...data.user,
            hasPassword: data.user.hasPassword === true || data.user.hasPassword === 1,
          };
          setUserData(u);
          setNewPhone(u.phone || '');
          setFirstName(u.first || '');
          setLastName(u.last  || '');
          setEmailAlt(u.emailAlt || '');
        }
      })
      .catch(() => {});
  }, []);

  // Profile fields
  const [firstName,    setFirstName]    = React.useState('');
  const [lastName,     setLastName]     = React.useState('');
  const [emailAlt,     setEmailAlt]     = React.useState('');

  // Password fields
  const [currentPw,    setCurrentPw]    = React.useState('');
  const [newPw,        setNewPw]        = React.useState('');
  const [confirmPw,    setConfirmPw]    = React.useState('');
  const [showPw,       setShowPw]       = React.useState(false);

  // Email fields
  const [newEmail,     setNewEmail]     = React.useState('');
  const [emailCode,    setEmailCode]    = React.useState('');
  const [emailStep,    setEmailStep]    = React.useState('input'); // input | verify

  // Phone fields
  const [newPhone,     setNewPhone]     = React.useState(''); // populated after fetch
  const [phoneCode,    setPhoneCode]    = React.useState('');
  const [phoneStep,    setPhoneStep]    = React.useState('input'); // input | verify

  const clear = () => { setError(null); setSuccess(null); };

  // Close on Escape
  React.useEffect(() => {
    const h = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  // ── Name/profile save ────────────────────────
  async function handleProfileSave() {
    clear();
    setLoading(true);
    try {
      const data = await profilePost('profile/name', {
        app: appId, first: firstName, last: lastName, emailAlt
      }, jwt);
      if (data.status !== 'ok') throw new Error(data.message);
      setSuccess('Profile updated');
      setUserData(prev => ({ ...prev, first: firstName, last: lastName,
        name: data.name, emailAlt }));
    } catch(e) { setError(e.message); }
    setLoading(false);
  }

  // ── Password change ───────────────────────
  async function handlePasswordSave() {
    clear();
    if (!newPw) return setError('Enter a new password');
    if (newPw.length < 8) return setError('Password must be at least 8 characters');
    if (newPw !== confirmPw) return setError('Passwords do not match');
    setLoading(true);
    try {
      const data = await profilePost('profile/password', {
        app: appId, currentPassword: currentPw, newPassword: newPw
      }, jwt);
      if (data.status !== 'ok') throw new Error(data.message);
      setSuccess('Password updated successfully');
      setCurrentPw(''); setNewPw(''); setConfirmPw('');
    } catch(e) { setError(e.message); }
    setLoading(false);
  }

  // ── Email change ──────────────────────────
  async function handleEmailSend() {
    clear();
    if (!newEmail || !newEmail.includes('@')) return setError('Enter a valid email address');
    setLoading(true);
    try {
      const data = await profilePost('profile/email/request', {
        app: appId, newEmail
      }, jwt);
      if (data.status !== 'ok') throw new Error(data.message);
      setEmailStep('verify');
      setSuccess(`Verification code sent to ${newEmail}`);
    } catch(e) { setError(e.message); }
    setLoading(false);
  }

  async function handleEmailVerify() {
    clear();
    if (!emailCode) return setError('Enter the verification code');
    setLoading(true);
    try {
      const data = await profilePost('profile/email/confirm', {
        app: appId, newEmail, code: emailCode
      }, jwt);
      if (data.status !== 'ok') throw new Error(data.message);
      setSuccess('Email address updated');
      setEmailStep('input');
      setEmailCode('');
      onUserUpdate && onUserUpdate({ ...user, email: newEmail });
    } catch(e) { setError(e.message); }
    setLoading(false);
  }

  // ── Phone change ──────────────────────────
  async function handlePhoneSend() {
    clear();
    if (!newPhone) return setError('Enter a phone number');
    setLoading(true);
    try {
      const data = await profilePost('profile/phone/request', {
        app: appId, newPhone
      }, jwt);
      if (data.status !== 'ok') throw new Error(data.message);
      setPhoneStep('verify');
      setSuccess(`Verification code sent to ${newPhone}`);
    } catch(e) { setError(e.message); }
    setLoading(false);
  }

  async function handlePhoneVerify() {
    clear();
    if (!phoneCode) return setError('Enter the verification code');
    setLoading(true);
    try {
      const data = await profilePost('profile/phone/confirm', {
        app: appId, newPhone, code: phoneCode
      }, jwt);
      if (data.status !== 'ok') throw new Error(data.message);
      setSuccess('Phone number updated');
      setPhoneStep('input');
      setPhoneCode('');
      onUserUpdate && onUserUpdate({ ...user, phone: newPhone });
    } catch(e) { setError(e.message); }
    setLoading(false);
  }

  const isMobile = window.innerWidth < 768;

  return (
    <>
      {/* Overlay */}
      <div style={SP.overlay} onClick={onClose} />

      {/* Panel */}
      <div style={{ ...SP.panel, ...(isMobile ? SP.panelMobile : {}) }}>

        {/* Header */}
        <div style={SP.header}>
          <div style={SP.headerLeft}>
            <div style={SP.avatar}>
              {(userData?.first || userData?.last)
                ? `${(userData.first||'')[0]||''}${(userData.last||'')[0]||''}`.toUpperCase() || 'U'
                : (userData?.email?.[0] || 'U').toUpperCase()
              }
            </div>
            <div>
              <div style={SP.userName}>
                {[userData?.first, userData?.last].filter(Boolean).join(' ') || userData?.email || 'User'}
              </div>
              <div style={SP.userEmail}>{userData?.email || ''}</div>
            </div>
          </div>
          <button style={SP.closeBtn} onClick={onClose}>✕</button>
        </div>

        {/* Tabs */}
        <div style={SP.tabs}>
          {[
            { id:'profile',  label:'Profile'  },
            { id:'password', label:'Password' },
            { id:'email',    label:'Email'    },
            { id:'phone',    label:'2FA Phone'},
          ].map(t => (
            <button
              key={t.id}
              style={{ ...SP.tab, ...(tab === t.id ? SP.tabActive : {}) }}
              onClick={() => { setTab(t.id); clear(); }}
            >{t.label}</button>
          ))}
        </div>

        {/* Messages */}
        {error   && <div style={SP.errorMsg}>⚠ {error}</div>}
        {success && <div style={SP.successMsg}>✓ {success}</div>}

        {/* ── Profile Tab ── */}
        {tab === 'profile' && (
          <div style={SP.body}>
            <div style={{ display:'flex', gap:12, marginBottom:14 }}>
              <div style={{ flex:1 }}>
                <label style={SP.label}>First Name</label>
                <input style={SP.input} type="text" value={firstName}
                  onChange={e => setFirstName(e.target.value)} placeholder="First" />
              </div>
              <div style={{ flex:1 }}>
                <label style={SP.label}>Last Name</label>
                <input style={SP.input} type="text" value={lastName}
                  onChange={e => setLastName(e.target.value)} placeholder="Last" />
              </div>
            </div>
            <Field label="Primary Email">
              <div style={{ ...SP.input, background:'#f8fafc', color:'#94a3b8' }}>
                {userData?.email}
              </div>
            </Field>
            <Field label="Alternate Email">
              <input style={SP.input} type="email" value={emailAlt}
                onChange={e => setEmailAlt(e.target.value)}
                placeholder="optional backup email" />
            </Field>
            <button style={SP.saveBtn} onClick={handleProfileSave} disabled={loading}>
              {loading ? 'Saving…' : 'Save Profile'}
            </button>
          </div>
        )}

        {/* ── Password Tab ── */}
        {tab === 'password' && (
          <div style={SP.body}>
            <div style={SP.hint}>
              {userData?.hasPassword
                ? 'Update your current password.'
                : 'You have no password set. Add one to enable password login.'
              }
            </div>

            <Field label="New Password">
              <PwInput value={newPw} onChange={setNewPw} show={showPw} placeholder="At least 8 characters" />
            </Field>
            <Field label="Confirm New Password">
              <PwInput value={confirmPw} onChange={setConfirmPw} show={showPw} placeholder="Repeat new password" />
            </Field>
            <label style={SP.checkRow}>
              <input type="checkbox" checked={showPw} onChange={e => setShowPw(e.target.checked)} />
              <span style={SP.checkLabel}>Show passwords</span>
            </label>
            <button style={SP.saveBtn} onClick={handlePasswordSave} disabled={loading}>
              {loading ? 'Saving…' : userData?.hasPassword ? 'Update Password' : 'Set Password'}
            </button>
          </div>
        )}

        {/* ── Email Tab ── */}
        {tab === 'email' && (
          <div style={SP.body}>
            <div style={SP.hint}>Current email: <strong>{userData?.email}</strong></div>
            {emailStep === 'input' && (
              <>
                <Field label="New Email Address">
                  <input
                    style={SP.input} type="email"
                    value={newEmail} onChange={e => setNewEmail(e.target.value)}
                    placeholder="new@example.com"
                  />
                </Field>
                <button style={SP.saveBtn} onClick={handleEmailSend} disabled={loading}>
                  {loading ? 'Sending…' : 'Send Verification Code'}
                </button>
              </>
            )}
            {emailStep === 'verify' && (
              <>
                <Field label="Verification Code">
                  <input
                    style={SP.input} type="text"
                    value={emailCode} onChange={e => setEmailCode(e.target.value)}
                    placeholder="6-digit code" maxLength={6}
                  />
                </Field>
                <div style={{ display:'flex', gap:8 }}>
                  <button style={SP.saveBtn} onClick={handleEmailVerify} disabled={loading}>
                    {loading ? 'Verifying…' : 'Confirm Email'}
                  </button>
                  <button style={SP.cancelBtn} onClick={() => { setEmailStep('input'); clear(); }}>
                    Back
                  </button>
                </div>
              </>
            )}
          </div>
        )}

        {/* ── Phone Tab ── */}
        {tab === 'phone' && (
          <div style={SP.body}>
            <div style={SP.hint}>
              {userData?.phone
                ? <>Current: <strong>{user.phone}</strong> — update to change your 2FA number.</>
                : 'Add a phone number to enable SMS two-factor authentication.'
              }
            </div>
            {phoneStep === 'input' && (
              <>
                <Field label="Phone Number">
                  <input
                    style={SP.input} type="tel"
                    value={newPhone} onChange={e => setNewPhone(e.target.value)}
                    placeholder="+1 555 000 0000"
                  />
                </Field>
                <button style={SP.saveBtn} onClick={handlePhoneSend} disabled={loading}>
                  {loading ? 'Sending…' : 'Send Verification Code'}
                </button>
                {userData?.phone && (
                  <button style={{ ...SP.cancelBtn, marginTop:8 }} onClick={async () => {
                    clear();
                    setLoading(true);
                    try {
                      const data = await profilePost('profile/phone/remove', { app: appId }, jwt);
                      if (data.status !== 'ok') throw new Error(data.message);
                      setSuccess('Phone number removed');
                      onUserUpdate && onUserUpdate({ ...user, phone: null });
                    } catch(e) { setError(e.message); }
                    setLoading(false);
                  }}>
                    Remove Phone Number
                  </button>
                )}
              </>
            )}
            {phoneStep === 'verify' && (
              <>
                <Field label="Verification Code">
                  <input
                    style={SP.input} type="text"
                    value={phoneCode} onChange={e => setPhoneCode(e.target.value)}
                    placeholder="6-digit code" maxLength={6}
                  />
                </Field>
                <div style={{ display:'flex', gap:8 }}>
                  <button style={SP.saveBtn} onClick={handlePhoneVerify} disabled={loading}>
                    {loading ? 'Verifying…' : 'Confirm Phone'}
                  </button>
                  <button style={SP.cancelBtn} onClick={() => { setPhoneStep('input'); clear(); }}>
                    Back
                  </button>
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </>
  );
}

// ── Small helpers ─────────────────────────────
function Field({ label, children }) {
  return (
    <div style={{ marginBottom:14 }}>
      <label style={SP.label}>{label}</label>
      {children}
    </div>
  );
}

function PwInput({ value, onChange, show, placeholder }) {
  return (
    <input
      style={SP.input}
      type={show ? 'text' : 'password'}
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
    />
  );
}

// ─────────────────────────────────────────────
// STYLES
// ─────────────────────────────────────────────
const SP = {
  overlay:     { position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:500 },
  panel:       { position:'fixed', top:'50%', left:'50%', transform:'translate(-50%,-50%)', background:'#fff', borderRadius:12, boxShadow:'0 20px 60px rgba(0,0,0,0.2)', zIndex:501, width:440, maxWidth:'95vw', maxHeight:'90vh', overflowY:'auto', fontFamily:"'Segoe UI',sans-serif" },
  panelMobile: { top:0, left:0, right:0, bottom:0, transform:'none', borderRadius:0, maxWidth:'100%', maxHeight:'100%', width:'100%' },
  header:      { display:'flex', alignItems:'center', justifyContent:'space-between', padding:'20px 20px 16px', borderBottom:'1px solid #f1f5f9' },
  headerLeft:  { display:'flex', alignItems:'center', gap:12 },
  avatar:      { width:44, height:44, borderRadius:'50%', background:'#2563a8', color:'#fff', fontSize:16, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 },
  userName:    { fontSize:15, fontWeight:700, color:'#0f172a' },
  userEmail:   { fontSize:12, color:'#94a3b8', marginTop:2 },
  closeBtn:    { background:'none', border:'none', fontSize:18, cursor:'pointer', color:'#94a3b8', padding:'4px 8px', borderRadius:4 },
  tabs:        { display:'flex', borderBottom:'1px solid #f1f5f9', padding:'0 20px' },
  tab:         { background:'none', border:'none', borderBottom:'2px solid transparent', padding:'10px 14px', fontSize:13, fontWeight:600, color:'#64748b', cursor:'pointer', fontFamily:'inherit', marginBottom:-1 },
  tabActive:   { color:'#2563a8', borderBottomColor:'#2563a8' },
  body:        { padding:'20px' },
  hint:        { fontSize:12, color:'#64748b', marginBottom:16, lineHeight:1.5 },
  label:       { display:'block', fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'#64748b', marginBottom:5 },
  input:       { width:'100%', boxSizing:'border-box', border:'1px solid #e2e8f0', borderRadius:6, padding:'8px 12px', fontSize:14, color:'#0f172a', outline:'none', fontFamily:'inherit' },
  checkRow:    { display:'flex', alignItems:'center', gap:8, cursor:'pointer', marginBottom:16 },
  checkLabel:  { fontSize:13, color:'#64748b' },
  saveBtn:     { background:'#2563a8', color:'#fff', border:'none', borderRadius:6, padding:'9px 20px', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit', width:'100%' },
  cancelBtn:   { background:'#f1f5f9', color:'#475569', border:'none', borderRadius:6, padding:'9px 16px', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit' },
  errorMsg:    { margin:'0 20px', padding:'10px 14px', background:'#fef2f2', color:'#991b1b', borderRadius:6, fontSize:13 },
  successMsg:  { margin:'0 20px', padding:'10px 14px', background:'#f0fdf4', color:'#166534', borderRadius:6, fontSize:13 },
};
