// ─────────────────────────────────────────────
// DO_Profile.jsx  (V7)
// Single-view profile modal — no tabs
// Fields: First, Last, Email, Alt Email, Password, 2FA Phone
// ─────────────────────────────────────────────

const API_BASE_PROF = window.API_BASE || '';

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

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

function DOProfile({ user, jwt, appId, onClose, onUserUpdate }) {
  const [first,     setFirst]     = React.useState(user?.first || user?.user_first || '');
  const [last,      setLast]      = React.useState(user?.last  || user?.user_last  || '');
  const [email,     setEmail]     = React.useState(user?.email || user?.user_email || '');
  const [emailAlt,  setEmailAlt]  = React.useState('');
  const [phone,     setPhone]     = React.useState(user?.phone || user?.user_phone || '');
  const [pwCurrent, setPwCurrent] = React.useState('');
  const [pwNew,     setPwNew]     = React.useState('');
  const [pwConfirm, setPwConfirm] = React.useState('');
  const [saving,    setSaving]    = React.useState(false);
  const [msg,       setMsg]       = React.useState(null);
  const [showPw,    setShowPw]    = React.useState(false);

  React.useEffect(() => {
    if (!jwt) return;
    doProfileGet('profile/me', jwt)
      .then(d => {
        if (d.status !== 'ok') return;
        if (d.first     !== undefined) setFirst(d.first     || '');
        if (d.last      !== undefined) setLast(d.last       || '');
        if (d.email     !== undefined) setEmail(d.email     || '');
        if (d.email_alt !== undefined) setEmailAlt(d.email_alt || '');
        if (d.phone     !== undefined) setPhone(d.phone     || '');
      })
      .catch(() => {});
  }, [jwt]);

  function flash(text, isError) {
    setMsg({ text, isError });
    setTimeout(() => setMsg(null), 3500);
  }

  async function save() {
    setSaving(true);
    try {
      const r1 = await doProfilePost('profile/name', {
        app: appId, first, last, email_alt: emailAlt, phone,
      }, jwt);
      if (r1.status !== 'ok') throw new Error(r1.message);

      if (pwNew) {
        if (pwNew !== pwConfirm) throw new Error('New passwords do not match');
        if (!pwCurrent)          throw new Error('Current password is required');
        const r2 = await doProfilePost('profile/password', {
          app: appId, current: pwCurrent, password: pwNew,
        }, jwt);
        if (r2.status !== 'ok') throw new Error(r2.message);
        setPwCurrent(''); setPwNew(''); setPwConfirm(''); setShowPw(false);
      }

      onUserUpdate && onUserUpdate({ ...user, first, last, email });
      flash('✓ Profile saved', false);
    } catch(err) {
      flash(err.message, true);
    }
    setSaving(false);
  }

  const initials = `${(first||'').charAt(0)}${(last||'').charAt(0)}`.toUpperCase() || '?';
  const theme    = window.__DO_THEME__ || {};
  const navBg    = theme.nav_bg    || '#0f2744';
  const navColor = theme.nav_color || '#ffffff';

  const lbl  = text => <label style={SP_PROF.lbl}>{text}</label>;
  const inp  = (val, set, props={}) => (
    <input value={val} onChange={e => set(e.target.value)}
      style={SP_PROF.inp} {...props} />
  );

  return (
    <div style={SP_PROF.overlay}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={SP_PROF.modal}>

        {/* Header */}
        <div style={{ ...SP_PROF.header, background:navBg, color:navColor }}>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <div style={{ ...SP_PROF.avatar, background:navColor+'33', color:navColor }}>
              {initials}
            </div>
            <div>
              <div style={{ fontWeight:700, fontSize:16 }}>{first} {last}</div>
              <div style={{ fontSize:12, opacity:0.75 }}>{email}</div>
            </div>
          </div>
          <button onClick={onClose}
            style={{ background:'none', border:'none', fontSize:20, cursor:'pointer',
                     color:navColor, opacity:0.8, lineHeight:1, padding:0 }}>✕</button>
        </div>

        {/* Body */}
        <div style={SP_PROF.body}>

          <div style={SP_PROF.row2}>
            <div style={SP_PROF.field}>{lbl('First Name')}{inp(first, setFirst, { placeholder:'First' })}</div>
            <div style={SP_PROF.field}>{lbl('Last Name')}{inp(last, setLast, { placeholder:'Last' })}</div>
          </div>

          <div style={SP_PROF.field}>
            {lbl('Primary Email')}
            <input value={email} readOnly
              style={{ ...SP_PROF.inp, background:'#f8fafc', color:'#94a3b8', cursor:'default' }} />
          </div>

          <div style={SP_PROF.field}>
            {lbl('Alternate Email')}
            {inp(emailAlt, setEmailAlt, { placeholder:'optional backup email' })}
          </div>

          <div style={SP_PROF.divider} />

          {/* Password */}
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between',
                        marginBottom:10 }}>
            <div style={SP_PROF.sectionHdr}>Change Password</div>
            <button onClick={() => setShowPw(p => !p)}
              style={{ background:'none', border:'none', fontSize:12, color:'#2563eb',
                       cursor:'pointer', fontFamily:'inherit' }}>
              {showPw ? 'Cancel' : 'Change'}
            </button>
          </div>

          {showPw && <>
            <div style={SP_PROF.field}>
              {lbl('Current Password')}
              {inp(pwCurrent, setPwCurrent, { type:'password', placeholder:'Current password' })}
            </div>
            <div style={SP_PROF.row2}>
              <div style={SP_PROF.field}>
                {lbl('New Password')}
                {inp(pwNew, setPwNew, { type:'password', placeholder:'New password' })}
              </div>
              <div style={SP_PROF.field}>
                {lbl('Confirm New')}
                {inp(pwConfirm, setPwConfirm, { type:'password', placeholder:'Confirm password' })}
              </div>
            </div>
          </>}

          <div style={SP_PROF.divider} />

          {/* 2FA Phone */}
          <div style={SP_PROF.field}>
            {lbl('2FA Phone Number')}
            {inp(phone, setPhone, { placeholder:'+1 555 000 0000' })}
            <div style={{ fontSize:11, color:'#94a3b8', marginTop:4 }}>
              Used for two-factor authentication SMS codes
            </div>
          </div>

          {msg && (
            <div style={{ padding:'10px 12px', borderRadius:6, fontSize:13, marginTop:4,
                          background: msg.isError ? '#fef2f2' : '#f0fdf4',
                          color:      msg.isError ? '#991b1b' : '#166534',
                          border:`1px solid ${msg.isError ? '#fecaca' : '#bbf7d0'}` }}>
              {msg.text}
            </div>
          )}

          <button onClick={save} disabled={saving}
            style={{ ...SP_PROF.saveBtn, background:navBg, color:navColor }}>
            {saving ? 'Saving…' : 'Save Profile'}
          </button>
        </div>
      </div>
    </div>
  );
}

const SP_PROF = {
  overlay:    { position:'fixed', top:0, left:0, right:0, bottom:0, zIndex:1000,
                background:'rgba(0,0,0,0.5)', display:'flex', alignItems:'center',
                justifyContent:'center', fontFamily:"'Segoe UI', sans-serif" },
  modal:      { background:'#fff', borderRadius:12, width:'100%', maxWidth:460,
                maxHeight:'90vh', overflowY:'auto',
                boxShadow:'0 20px 60px rgba(0,0,0,0.3)' },
  header:     { display:'flex', alignItems:'center', justifyContent:'space-between',
                padding:'20px 24px', borderRadius:'12px 12px 0 0' },
  avatar:     { width:44, height:44, borderRadius:'50%', display:'flex',
                alignItems:'center', justifyContent:'center',
                fontSize:16, fontWeight:700, flexShrink:0 },
  body:       { padding:'24px' },
  row2:       { display:'flex', gap:12 },
  field:      { flex:1, marginBottom:14 },
  lbl:        { display:'block', fontSize:10, fontWeight:700, color:'#94a3b8',
                textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:5 },
  inp:        { width:'100%', padding:'9px 12px', border:'1.5px solid #e2e8f0',
                borderRadius:7, fontSize:13, fontFamily:'inherit', outline:'none',
                color:'#0f1923', boxSizing:'border-box', display:'block' },
  divider:    { height:1, background:'#f1f5f9', margin:'8px 0 16px' },
  sectionHdr: { fontSize:11, fontWeight:700, color:'#94a3b8',
                textTransform:'uppercase', letterSpacing:'0.06em' },
  saveBtn:    { width:'100%', padding:'12px', border:'none', borderRadius:8,
                fontSize:14, fontWeight:700, cursor:'pointer',
                fontFamily:'inherit', marginTop:8 },
};
