// ─────────────────────────────────────────────
// DO_AdminUsers.jsx  (V7)
// Admin-only modal to manage app users
// Roles: admin | user | guest
// ─────────────────────────────────────────────

const API_BASE_AU = window.API_BASE || '';

function DOAdminUsers({ appId, jwt, theme = {}, onClose }) {
  const [users,   setUsers]   = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [editing, setEditing] = React.useState(null); // null | 'new' | userId
  const [form,    setForm]    = React.useState({});
  const [saving,  setSaving]  = React.useState(false);
  const [msg,     setMsg]     = React.useState(null);
  const [confirm, setConfirm] = React.useState(null); // userId to delete

  const navBg    = theme.nav_bg    || '#0f2744';
  const navColor = theme.nav_color || '#ffffff';

  function authHeaders() {
    return { 'Content-Type':'application/json', 'Authorization':`Bearer ${jwt}` };
  }

  async function loadUsers() {
    setLoading(true);
    try {
      const r = await fetch(`${API_BASE_AU}/v6/auth/app-users?app=${appId}`,
        { headers: authHeaders() });
      const d = await r.json();
      if (d.status === 'ok') setUsers(d.users || []);
    } catch(e) {}
    setLoading(false);
  }

  React.useEffect(() => { loadUsers(); }, []);

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

  function startEdit(user) {
    setForm({ ...user });
    setEditing(user.userId);
  }

  function startNew() {
    setForm({ first:'', last:'', email:'', phone:'', role:'user', active:true });
    setEditing('new');
  }

  async function saveUser() {
    if (!form.email) { flash('Email is required', true); return; }
    setSaving(true);
    try {
      const r = await fetch(`${API_BASE_AU}/v6/auth/app-users/save`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({ app: appId,
          userId: editing === 'new' ? null : editing,
          ...form }),
      });
      const d = await r.json();
      if (d.status !== 'ok') throw new Error(d.message);
      flash(editing === 'new' ? '✓ User added' : '✓ Saved', false);
      setEditing(null);
      loadUsers();
    } catch(e) { flash(e.message, true); }
    setSaving(false);
  }

  async function toggleActive(user) {
    try {
      await fetch(`${API_BASE_AU}/v6/auth/app-users/toggle`, {
        method: 'POST', headers: authHeaders(),
        body: JSON.stringify({ app: appId, userId: user.userId, active: !user.active }),
      });
      loadUsers();
    } catch(e) {}
  }

  async function deleteUser(userId) {
    try {
      await fetch(`${API_BASE_AU}/v6/auth/app-users/delete`, {
        method: 'POST', headers: authHeaders(),
        body: JSON.stringify({ app: appId, userId }),
      });
      setConfirm(null);
      loadUsers();
    } catch(e) {}
  }

  async function sendInvite(user) {
    try {
      const r = await fetch(`${API_BASE_AU}/v6/auth/invite`, {
        method: 'POST', headers: authHeaders(),
        body: JSON.stringify({ app: appId, userId: user.userId, email: user.email }),
      });
      const d = await r.json();
      if (d.status !== 'ok') throw new Error(d.message);
      flash(`✓ Invite sent to ${user.email}`, false);
    } catch(e) { flash(e.message || 'Could not send invite', true); }
  }

  const f = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const roleBadge = (role) => ({
    admin: { bg:'#fef3c7', color:'#92400e', label:'Admin' },
    user:  { bg:'#eff6ff', color:'#1d4ed8', label:'User'  },
    guest: { bg:'#f0fdf4', color:'#166534', label:'Guest' },
  }[role] || { bg:'#f1f5f9', color:'#64748b', label: role });

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

        {/* Header */}
        <div style={{ ...SAU.header, background:navBg, color:navColor }}>
          <div>
            <div style={{ fontWeight:700, fontSize:17 }}>👥 App Users</div>
            <div style={{ fontSize:12, opacity:0.75 }}>{users.length} user{users.length !== 1 ? 's' : ''}</div>
          </div>
          <div style={{ display:'flex', gap:8, alignItems:'center' }}>
            <button onClick={startNew}
              style={{ padding:'7px 14px', background:navColor+'22', border:`1px solid ${navColor}44`,
                       color:navColor, borderRadius:6, fontSize:13, fontWeight:600,
                       cursor:'pointer', fontFamily:'inherit' }}>
              + Add User
            </button>
            <button onClick={onClose}
              style={{ background:'none', border:'none', color:navColor,
                       fontSize:20, cursor:'pointer', opacity:0.8, lineHeight:1 }}>✕</button>
          </div>
        </div>

        {/* Messages */}
        {msg && (
          <div style={{ padding:'10px 20px', fontSize:13,
                        background: msg.isError ? '#fef2f2' : '#f0fdf4',
                        color:      msg.isError ? '#991b1b' : '#166534',
                        borderBottom:'1px solid #e2e8f0' }}>
            {msg.text}
          </div>
        )}

        {/* Add / Edit form */}
        {editing && (
          <div style={SAU.formPanel}>
            <div style={{ fontWeight:700, fontSize:13, marginBottom:12, color:'#0f1923' }}>
              {editing === 'new' ? 'New User' : 'Edit User'}
            </div>
            <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
              <div style={{ flex:1, minWidth:120 }}>
                <div style={SAU.lbl}>First Name</div>
                <input value={form.first||''} onChange={e=>f('first',e.target.value)}
                  placeholder="First" style={SAU.inp} />
              </div>
              <div style={{ flex:1, minWidth:120 }}>
                <div style={SAU.lbl}>Last Name</div>
                <input value={form.last||''} onChange={e=>f('last',e.target.value)}
                  placeholder="Last" style={SAU.inp} />
              </div>
              <div style={{ flex:2, minWidth:200 }}>
                <div style={SAU.lbl}>Email</div>
                <input value={form.email||''} onChange={e=>f('email',e.target.value)}
                  placeholder="user@example.com" readOnly={editing !== 'new'}
                  style={{ ...SAU.inp, background: editing !== 'new' ? '#f8fafc' : '#fff',
                            color: editing !== 'new' ? '#94a3b8' : '#0f1923' }} />
              </div>
              <div style={{ flex:1, minWidth:130 }}>
                <div style={SAU.lbl}>Phone</div>
                <input value={form.phone||''} onChange={e=>f('phone',e.target.value)}
                  placeholder="+1 555 0000" style={SAU.inp} />
              </div>
              <div style={{ minWidth:110 }}>
                <div style={SAU.lbl}>Role</div>
                <select value={form.role||'user'} onChange={e=>f('role',e.target.value)}
                  style={{ ...SAU.inp, background:'#fff' }}>
                  <option value="admin">Admin</option>
                  <option value="user">User</option>
                  <option value="guest">Guest</option>
                </select>
              </div>
            </div>
            <div style={{ display:'flex', gap:8, marginTop:12 }}>
              <button onClick={saveUser} disabled={saving}
                style={{ ...SAU.btn, background:navBg, color:navColor }}>
                {saving ? 'Saving…' : editing === 'new' ? 'Add User' : 'Save'}
              </button>
              <button onClick={() => setEditing(null)}
                style={{ ...SAU.btn, background:'#f1f5f9', color:'#374151' }}>
                Cancel
              </button>
            </div>
          </div>
        )}

        {/* User list */}
        <div style={SAU.body}>
          {loading && (
            <div style={{ padding:'40px', textAlign:'center', color:'#94a3b8' }}>Loading…</div>
          )}
          {!loading && users.length === 0 && (
            <div style={{ padding:'40px', textAlign:'center', color:'#94a3b8' }}>
              No users yet — click + Add User to get started
            </div>
          )}
          {!loading && users.length > 0 && (
            <table style={SAU.table}>
              <thead>
                <tr>
                  {['Name','Email','Phone','Role','Status','Actions'].map(h => (
                    <th key={h} style={SAU.th}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {users.map(u => {
                  const rb = roleBadge(u.role);
                  return (
                    <tr key={u.userId} style={{ borderBottom:'1px solid #f1f5f9',
                                                opacity: u.active ? 1 : 0.5 }}>
                      <td style={SAU.td}>
                        <div style={{ fontWeight:600, fontSize:13 }}>
                          {u.first} {u.last}
                        </div>
                        {!u.hasPassword && (
                          <div style={{ fontSize:10, color:'#f59e0b' }}>No password set</div>
                        )}
                      </td>
                      <td style={SAU.td}>{u.email}</td>
                      <td style={SAU.td}>{u.phone || '—'}</td>
                      <td style={SAU.td}>
                        <span style={{ background:rb.bg, color:rb.color, padding:'2px 8px',
                                       borderRadius:12, fontSize:11, fontWeight:700 }}>
                          {rb.label}
                        </span>
                      </td>
                      <td style={SAU.td}>
                        <span style={{ fontSize:11, color: u.active ? '#16a34a' : '#94a3b8',
                                       fontWeight:600 }}>
                          {u.active ? '● Active' : '○ Inactive'}
                        </span>
                      </td>
                      <td style={{ ...SAU.td, whiteSpace:'nowrap' }}>
                        {/* Edit */}
                        <button onClick={() => startEdit(u)} title="Edit"
                          style={SAU.iconBtn}>✏️</button>
                        {/* Toggle active */}
                        <button onClick={() => toggleActive(u)}
                          title={u.active ? 'Deactivate' : 'Activate'}
                          style={SAU.iconBtn}>{u.active ? '⏸' : '▶'}</button>
                        {/* Send invite */}
                        <button onClick={() => sendInvite(u)} title="Send Invite"
                          style={SAU.iconBtn}>✉️</button>
                        {/* Delete */}
                        <button onClick={() => setConfirm(u.userId)}
                          title="Remove from app" style={{ ...SAU.iconBtn, color:'#dc2626' }}>🗑</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>

        {/* Confirm delete */}
        {confirm && (
          <div style={SAU.confirmOverlay}>
            <div style={SAU.confirmBox}>
              <div style={{ fontWeight:700, marginBottom:8 }}>Remove user from app?</div>
              <div style={{ fontSize:13, color:'#64748b', marginBottom:16 }}>
                This removes their access. Their account is not deleted.
              </div>
              <div style={{ display:'flex', gap:8 }}>
                <button onClick={() => deleteUser(confirm)}
                  style={{ ...SAU.btn, background:'#dc2626', color:'#fff' }}>Remove</button>
                <button onClick={() => setConfirm(null)}
                  style={{ ...SAU.btn, background:'#f1f5f9', color:'#374151' }}>Cancel</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

const SAU = {
  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:'95%', maxWidth:860,
                   maxHeight:'90vh', display:'flex', flexDirection:'column',
                   boxShadow:'0 20px 60px rgba(0,0,0,0.25)', overflow:'hidden' },
  header:        { display:'flex', alignItems:'center', justifyContent:'space-between',
                   padding:'18px 24px', flexShrink:0 },
  formPanel:     { padding:'16px 24px', background:'#f8fafc',
                   borderBottom:'1px solid #e2e8f0', flexShrink:0 },
  body:          { overflowY:'auto', flex:1 },
  table:         { width:'100%', borderCollapse:'collapse' },
  th:            { padding:'10px 14px', textAlign:'left', fontSize:11, fontWeight:700,
                   color:'#94a3b8', textTransform:'uppercase', letterSpacing:'0.05em',
                   background:'#f8fafc', borderBottom:'2px solid #e2e8f0' },
  td:            { padding:'10px 14px', fontSize:13, color:'#374151', verticalAlign:'middle' },
  lbl:           { fontSize:10, fontWeight:700, color:'#94a3b8', textTransform:'uppercase',
                   letterSpacing:'0.06em', marginBottom:4 },
  inp:           { width:'100%', padding:'8px 10px', border:'1.5px solid #e2e8f0',
                   borderRadius:6, fontSize:13, fontFamily:'inherit', outline:'none',
                   boxSizing:'border-box' },
  btn:           { padding:'8px 16px', border:'none', borderRadius:6, fontSize:13,
                   fontWeight:600, cursor:'pointer', fontFamily:'inherit' },
  iconBtn:       { background:'none', border:'none', cursor:'pointer', fontSize:15,
                   padding:'4px 6px', borderRadius:4, color:'#374151' },
  confirmOverlay:{ position:'absolute', top:0, left:0, right:0, bottom:0,
                   background:'rgba(0,0,0,0.4)', display:'flex',
                   alignItems:'center', justifyContent:'center' },
  confirmBox:    { background:'#fff', borderRadius:10, padding:'24px', maxWidth:340,
                   boxShadow:'0 8px 32px rgba(0,0,0,0.2)' },
};
