// Change Password Modal
const ChangePasswordModal = ({ onClose, onSuccess }) => {
  const [currentPassword, setCurrentPassword] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const handleSubmit = async () => {
    if (!currentPassword || !newPassword || !confirmPassword) { setError('All fields required'); return; }
    if (newPassword !== confirmPassword) { setError('Passwords do not match'); return; }
    if (newPassword.length < 8) { setError('Password must be at least 8 characters'); return; }
    if (currentPassword === newPassword) { setError('New password must be different'); return; }

    setLoading(true);
    setError('');
    try {
      const token = localStorage.getItem('auth_token');
      const res = await fetch(api.config.baseUrl + '/auth/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
        body: JSON.stringify({ currentPassword, newPassword })
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.message || 'Failed to change password');
        return;
      }
      onSuccess();
      onClose();
    } catch (err) {
      setError(err.message || 'Network error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'grid', placeItems: 'center', zIndex: 1000 }}>
      <div style={{ background: 'white', borderRadius: 12, padding: 32, maxWidth: 420, width: '90%', boxShadow: '0 20px 60px rgba(0,0,0,0.3)' }}>
        <h2 style={{ margin: '0 0 24px', fontSize: 22, fontWeight: 600 }}>Change Password</h2>

        {error && <div style={{ background: '#fee2e2', color: '#991b1b', padding: '12px 14px', borderRadius: 8, marginBottom: 16, fontSize: 13 }}>⚠️ {error}</div>}

        <label style={{ display: 'block', marginBottom: 8, fontSize: 13, fontWeight: 600 }}>Current Password</label>
        <input type="password" value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} placeholder="Enter current password" style={{ width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: 8, marginBottom: 16, boxSizing: 'border-box' }} disabled={loading} />

        <label style={{ display: 'block', marginBottom: 8, fontSize: 13, fontWeight: 600 }}>New Password</label>
        <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="Min 8 characters" style={{ width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: 8, marginBottom: 16, boxSizing: 'border-box' }} disabled={loading} />

        <label style={{ display: 'block', marginBottom: 8, fontSize: 13, fontWeight: 600 }}>Confirm Password</label>
        <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} placeholder="Min 8 characters" style={{ width: '100%', padding: '10px 12px', border: '1px solid #d1d5db', borderRadius: 8, marginBottom: 16, boxSizing: 'border-box' }} disabled={loading} />

        <div style={{ display: 'flex', gap: 12 }}>
          <button onClick={onClose} disabled={loading} style={{ flex: 1, padding: '10px 12px', background: 'transparent', border: '1px solid #d1d5db', borderRadius: 8, fontWeight: 600, cursor: 'pointer' }}>Cancel</button>
          <button onClick={handleSubmit} disabled={loading} style={{ flex: 1, padding: '10px 12px', background: '#5b5bd6', color: 'white', border: 'none', borderRadius: 8, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.7 : 1 }}>
            {loading ? 'Changing...' : 'Change Password'}
          </button>
        </div>
      </div>
    </div>
  );
};

// Profile screen
const ProfileScreen = ({ role, onChangeRole, employees, setEmployees, providers, setProviders, domains, servers, toast, initialTab, initialProviderKind, onTabConsumed, currentUser, onCurrentUserChange }) => {
  const [tab, setTab] = React.useState(initialTab || 'account');
  const [providerKindOverride, setProviderKindOverride] = React.useState(initialProviderKind || null);
  const [showChangePassword, setShowChangePassword] = React.useState(false);
  React.useEffect(() => {
    if (initialTab) {
      setTab(initialTab);
      if (initialProviderKind) setProviderKindOverride(initialProviderKind);
      onTabConsumed && onTabConsumed();
    }
  }, [initialTab, initialProviderKind]);

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Profile</h1>
          <div className="sub">Your account and team management</div>
        </div>
      </div>

      <div className="tabs">
        <button className={`tab ${tab === 'account' ? 'active' : ''}`} onClick={() => setTab('account')}>
          <Icon name="employee" size={14} stroke={2}/> Account
        </button>
        <button className={`tab ${tab === 'team' ? 'active' : ''}`} onClick={() => setTab('team')}>
          <Icon name="clients" size={14} stroke={2}/> Team Members
          <span className="count">{employees.length}</span>
        </button>
        <button className={`tab ${tab === 'providers' ? 'active' : ''}`} onClick={() => setTab('providers')}>
          <Icon name="globe" size={14} stroke={2}/> Providers
          <span className="count">{providers.filter(p => p.status === 'active').length}</span>
        </button>
      </div>

      {tab === 'account' && (
        <AccountTab
          currentUser={currentUser}
          onCurrentUserChange={onCurrentUserChange}
          onChangePassword={() => setShowChangePassword(true)}
          toast={toast}
        />
      )}
      {showChangePassword && <ChangePasswordModal onClose={() => setShowChangePassword(false)} onSuccess={() => toast('Password changed successfully', 'success')} />}
      {tab === 'team' && <TeamTab employees={employees} setEmployees={setEmployees} toast={toast} />}
      {tab === 'providers' && <ProvidersTab providers={providers} setProviders={setProviders} domains={domains} servers={servers} toast={toast} initialKind={providerKindOverride} />}
    </>
  );
};

// ── Account tab ──────────────────────────────────────────────
const AccountTab = ({ currentUser, onCurrentUserChange, onChangePassword, toast }) => {
  const [name, setName] = React.useState(currentUser?.name || '');
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    setName(currentUser?.name || '');
  }, [currentUser?.name]);

  const handleUpdateProfile = async () => {
    if (!name.trim()) return;
    setSaving(true);
    try {
      const token = localStorage.getItem('auth_token');
      const res = await fetch(api.config.baseUrl + '/auth/profile', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
        body: JSON.stringify({ name: name.trim() })
      });
      if (!res.ok) {
        const data = await res.json();
        toast(data.message || 'Failed to update profile', 'danger');
        return;
      }
      const data = await res.json();
      if (onCurrentUserChange && data.user) onCurrentUserChange(data.user);
      toast('Profile updated', 'success');
    } catch (err) {
      toast(err.message || 'Network error', 'danger');
    } finally {
      setSaving(false);
    }
  };

  const initials = (currentUser?.name || 'U').split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();

  return (
    <div style={{ maxWidth: 520 }}>
      <div className="card">
        <div className="card-head"><h3>Account details</h3></div>
        <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, paddingBottom: 18, borderBottom: '1px solid var(--border)' }}>
            <div className="avatar admin" style={{ width: 64, height: 64, fontSize: 22, fontWeight: 500, fontFamily: 'var(--font-display)', flexShrink: 0 }}>
              {initials}
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 16 }}>{currentUser?.name || '—'}</div>
              <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginTop: 2 }}>
                <span className="badge brand"><Icon name="shield" size={10} stroke={2.2}/> {currentUser?.role || 'Admin'}</span>
              </div>
            </div>
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: 6, fontSize: 13, fontWeight: 600 }}>Full Name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Your name"
              style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 8, boxSizing: 'border-box', fontSize: 14, fontFamily: 'inherit' }}
              disabled={saving}
            />
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: 6, fontSize: 13, fontWeight: 600 }}>Email</label>
            <input
              type="email"
              value={currentUser?.email || ''}
              readOnly
              style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 8, boxSizing: 'border-box', fontSize: 14, fontFamily: 'var(--font-mono)', background: 'var(--bg-subtle)', color: 'var(--text-secondary)', cursor: 'default' }}
            />
          </div>

          <div style={{ display: 'flex', gap: 10, paddingTop: 4 }}>
            <button
              className="btn brand"
              onClick={handleUpdateProfile}
              disabled={saving || !name.trim() || name.trim() === currentUser?.name}
            >
              {saving ? 'Saving…' : 'Update Profile'}
            </button>
            <button className="btn" onClick={onChangePassword}>
              <Icon name="key" size={13}/> Change Password
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Team tab ─────────────────────────────────────────────────
const TeamTab = ({ employees, setEmployees, toast }) => {
  const [confirm, setConfirm] = React.useState(null);
  const adminsCount = employees.filter(e => e.role === 'Admin').length;
  const activeCount = employees.filter(e => e.status === 'active').length;

  return (
    <>
      <div className="stats" style={{ marginBottom: 18 }}>
        <div className="stat">
          <div className="stat-label">
            <span className="stat-icon"><Icon name="employee" size={13}/></span>
            Total members
          </div>
          <div className="stat-value">{employees.length}</div>
          <div className="stat-trend">{activeCount} active</div>
        </div>
        <div className="stat">
          <div className="stat-label">
            <span className="stat-icon"><Icon name="shield" size={13}/></span>
            Admins
          </div>
          <div className="stat-value">{adminsCount}</div>
          <div className="stat-trend">Full access</div>
        </div>
        <div className="stat">
          <div className="stat-label">
            <span className="stat-icon blue"><Icon name="employee" size={13}/></span>
            Employees
          </div>
          <div className="stat-value">{employees.length - adminsCount}</div>
          <div className="stat-trend">Edit needs approval</div>
        </div>
      </div>

      <div className="card">
        <div className="table-wrap">
          <table className="data">
            <thead>
              <tr>
                <th>Member</th>
                <th>Email</th>
                <th>Role</th>
                <th>Status</th>
                <th>Joined</th>
                <th>Last active</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {employees.map(e => (
                <tr key={e.id}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                      <Avatar name={e.name} size={28} />
                      <div className="cell-primary">{e.name}</div>
                    </div>
                  </td>
                  <td><span className="mono" style={{ fontSize: 12 }}>{e.email}</span></td>
                  <td>
                    {e.role === 'Admin' ? (
                      <span className="badge brand"><Icon name="shield" size={10} stroke={2.2}/> Admin</span>
                    ) : (
                      <span className="badge">Employee</span>
                    )}
                  </td>
                  <td>
                    {e.status === 'active'
                      ? <span className="badge green dot">Active</span>
                      : <span className="badge amber dot">Invited</span>}
                  </td>
                  <td className="mono" style={{ fontSize: 12 }}>{window.fmtDate(e.joined)}</td>
                  <td style={{ color: 'var(--text-muted)', fontSize: 12 }}>{e.last}</td>
                  <td>
                    <div className="row-actions">
                      <button className="btn sm ghost" title="Reset password"><Icon name="key" size={13}/></button>
                      <button className="btn sm ghost" title="Edit"><Icon name="edit" size={13}/></button>
                      <button className="btn sm ghost danger" title="Remove" onClick={() => setConfirm(e)}><Icon name="trash" size={13}/></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {confirm && (
        <Modal title={`Remove ${confirm.name}?`} sub="They will immediately lose access to the workspace." onClose={() => setConfirm(null)}
          footer={
            <>
              <button className="btn" onClick={() => setConfirm(null)}>Cancel</button>
              <button className="btn danger" onClick={() => {
                setEmployees(prev => prev.filter(x => x.id !== confirm.id));
                toast(`${confirm.name} removed`, 'danger');
                setConfirm(null);
              }}>
                <Icon name="trash" size={13}/> Remove member
              </button>
            </>
          }
        >
          <p style={{ margin: 0, fontSize: 13, color: 'var(--text-secondary)' }}>
            Their pending approval requests will be cancelled. This action can't be undone from the prototype.
          </p>
        </Modal>
      )}
    </>
  );
};

window.ProfileScreen = ProfileScreen;
