// wh-perfiles-section.jsx - extracted PerfilesSection

(() => {

const { useState, useEffect } = React;
const {
  Avatar,
  Badge,
  SecHead,
  FormField,
  FormFeedbackGroup,
  apiFetch,
  sbClient,
} = window;

const ROLE_LABEL = { super_admin: 'Super Admin', admin: 'Administrador', agente: 'Agente' };
const ROLE_COLOR = { super_admin: 'brand', admin: 'teal', agente: 'gray' };

function PerfilesSection({ user, onProfileUpdate }) {
  const [tab, setTab] = useState('profile');
  const [name, setName] = useState(user?.full_name || '');
  const [oldPass, setOldPass] = useState('');
  const [newPass, setNewPass] = useState('');
  const [newPass2, setNewPass2] = useState('');
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState('');
  const [err, setErr] = useState('');

  useEffect(() => {
    setName(user?.full_name || '');
  }, [user]);

  const switchTab = (nextTab) => {
    setTab(nextTab);
    setMsg('');
    setErr('');
  };

  const saveName = async () => {
    setBusy(true);
    setMsg('');
    setErr('');
    try {
      const res = await apiFetch('/api/me/profile', { method: 'PATCH', body: JSON.stringify({ full_name: name }) });
      if (!res.ok) {
        const e = await res.json();
        setErr(e.error);
        return;
      }
      onProfileUpdate({ full_name: name });
      setMsg('Nombre actualizado correctamente.');
    } catch {
      setErr('Error al guardar.');
    } finally {
      setBusy(false);
    }
  };

  const changePass = async () => {
    if (newPass.length < 6) {
      setErr('Mínimo 6 caracteres.');
      return;
    }
    if (newPass !== newPass2) {
      setErr('Las contraseñas no coinciden.');
      return;
    }
    setBusy(true);
    setMsg('');
    setErr('');
    try {
      const { error: authErr } = await sbClient.auth.signInWithPassword({ email: user.email, password: oldPass });
      if (authErr) {
        setErr('Contraseña actual incorrecta.');
        return;
      }
      const res = await apiFetch('/api/me/password', { method: 'PATCH', body: JSON.stringify({ password: newPass }) });
      if (!res.ok) {
        const e = await res.json();
        setErr(e.error);
        return;
      }
      setMsg('Contraseña cambiada correctamente.');
      setOldPass('');
      setNewPass('');
      setNewPass2('');
    } catch {
      setErr('Error al cambiar contraseña.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div>
      <SecHead eyebrow="Cuenta" title="Perfiles" />

      <div style={{ maxWidth: 560 }}>
        <div className="card card-pad" style={{ marginBottom: 16 }}>
          <div className="flex-r" style={{ gap: 16, alignItems: 'center' }}>
            <Avatar name={user?.full_name || user?.email || 'U'} size="md" style={{ width: 52, height: 52, fontSize: 20 }} />
            <div>
              <div style={{ fontWeight: 800, fontSize: 16 }}>{user?.full_name || '—'}</div>
              <div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 6 }}>{user?.email}</div>
              <Badge color={ROLE_COLOR[user?.role] || 'gray'}>{ROLE_LABEL[user?.role] || user?.role}</Badge>
            </div>
          </div>
        </div>

        <div className="card card-pad">
          <div style={{ display: 'flex', gap: 8, marginBottom: 20, borderBottom: '1px solid var(--border)', paddingBottom: 12 }}>
            {[['profile', 'Datos de perfil'], ['password', 'Cambiar contraseña']].map(([k, l]) => (
              <button key={k} className={`btn btn-sm ${tab === k ? 'btn-primary' : 'btn-ghost'}`} onClick={() => switchTab(k)}>
                {l}
              </button>
            ))}
          </div>

          {tab === 'profile' && (
            <div className="stack">
              <FormField label="Nombre completo">
                <input className="inp" value={name} onChange={(e) => setName(e.target.value)} />
              </FormField>
              <FormField label="Email">
                <input className="inp" value={user?.email || ''} disabled style={{ opacity: 0.6 }} />
              </FormField>
              <FormFeedbackGroup message={msg} error={err} />
              <div className="flex-r" style={{ justifyContent: 'flex-end' }}>
                <button className="btn btn-primary" onClick={saveName} disabled={busy || !name.trim()}>
                  {busy ? 'Guardando…' : 'Guardar cambios'}
                </button>
              </div>
            </div>
          )}

          {tab === 'password' && (
            <div className="stack">
              <FormField label="Contraseña actual">
                <input className="inp" type="password" placeholder="••••••••" value={oldPass} onChange={(e) => setOldPass(e.target.value)} />
              </FormField>
              <FormField label="Nueva contraseña">
                <input className="inp" type="password" placeholder="mín. 6 caracteres" value={newPass} onChange={(e) => setNewPass(e.target.value)} />
              </FormField>
              <FormField label="Repetir nueva contraseña">
                <input className="inp" type="password" placeholder="••••••••" value={newPass2} onChange={(e) => setNewPass2(e.target.value)} />
              </FormField>
              <FormFeedbackGroup message={msg} error={err} />
              <div className="flex-r" style={{ justifyContent: 'flex-end' }}>
                <button className="btn btn-primary" onClick={changePass} disabled={busy || !oldPass || newPass.length < 6 || !newPass2}>
                  {busy ? 'Cambiando…' : 'Cambiar contraseña'}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PerfilesSection });

})();
