const { useState: useStateAP, useRef: useRefAP } = React;

function AdminProfile({ user, onUserUpdate, onPhotoChange }) {

  // ── Perfil básico ──────────────────────────────────────────────────────────
  const [nombre, setNombre] = useStateAP(user.nombre);
  const [email,  setEmail]  = useStateAP(user.email);
  const [profileSaved, setProfileSaved] = useStateAP(false);

  // ── Foto ──────────────────────────────────────────────────────────────────
  const fileRef = useRefAP(null);
  const [photo, setPhoto] = useStateAP(function () { return getStudentPhoto(user.id); });

  // ── Contraseña ────────────────────────────────────────────────────────────
  const [currentPw,   setCurrentPw]   = useStateAP('');
  const [newPw,       setNewPw]       = useStateAP('');
  const [confirmPw,   setConfirmPw]   = useStateAP('');
  const [pwError,     setPwError]     = useStateAP('');
  const [pwSaved,     setPwSaved]     = useStateAP(false);
  const [showCurrent, setShowCurrent] = useStateAP(false);
  const [showNew,     setShowNew]     = useStateAP(false);
  const [showConfirm, setShowConfirm] = useStateAP(false);

  // ── Mensaje de bienvenida ─────────────────────────────────────────────────
  const [welcomeMsg, setWelcomeMsg] = useStateAP(function () { return getLoginMessage(); });
  const [msgSaved,   setMsgSaved]   = useStateAP(false);

  // ── Handlers ──────────────────────────────────────────────────────────────
  function handlePhotoUpload(e) {
    var file = e.target.files[0];
    if (!file) return;
    e.target.value = '';
    var reader = new FileReader();
    reader.onload = function (ev) {
      var dataUrl = ev.target.result;
      saveStudentPhoto(user.id, dataUrl);
      setPhoto(dataUrl);
      if (onPhotoChange) onPhotoChange();
    };
    reader.readAsDataURL(file);
  }

  function handleRemovePhoto() {
    saveStudentPhoto(user.id, '');
    setPhoto(null);
    if (onPhotoChange) onPhotoChange();
  }

  function handleSaveProfile() {
    var trimNombre = nombre.trim();
    var trimEmail  = email.trim();
    if (!trimNombre || !trimEmail) return;
    var users   = getUsers();
    var updated = users.map(function (u) {
      return u.id === user.id ? Object.assign({}, u, { nombre: trimNombre, email: trimEmail }) : u;
    });
    saveUsers(updated);
    var updatedUser = updated.find(function (u) { return u.id === user.id; });
    try { localStorage.setItem('sst_session', JSON.stringify(updatedUser)); } catch (e) {}
    if (typeof window.sbUpdateProfile === 'function') window.sbUpdateProfile(user.id, { nombre: trimNombre, email: trimEmail });
    if (onUserUpdate) onUserUpdate(updatedUser);
    setProfileSaved(true);
    setTimeout(function () { setProfileSaved(false); }, 2500);
  }

  function handleSavePassword() {
    setPwError('');
    if (newPw.length < 8) {
      setPwError('La nueva contraseña debe tener al menos 8 caracteres');
      return;
    }
    if (newPw !== confirmPw) {
      setPwError('Las contraseñas no coinciden');
      return;
    }
    if (typeof window.sbSignIn === 'function') {
      window.sbSignIn(user.email, currentPw).then(function (res) {
        if (res.error) { setPwError('La contraseña actual es incorrecta'); return; }
        doSavePassword();
      });
      return;
    }
    var users     = getUsers();
    var adminUser = users.find(function (u) { return u.id === user.id; });
    if (!adminUser || adminUser.password !== currentPw) {
      setPwError('La contraseña actual es incorrecta');
      return;
    }
    doSavePassword();
  }

  function doSavePassword() {
    var updated = users.map(function (u) {
      return u.id === user.id ? Object.assign({}, u, { password: newPw }) : u;
    });
    saveUsers(updated);
    if (typeof window.sbUpdatePassword === 'function') window.sbUpdatePassword(user.id, newPw);
    setCurrentPw(''); setNewPw(''); setConfirmPw('');
    setPwSaved(true);
    setTimeout(function () { setPwSaved(false); }, 2500);
  }

  function handleSaveMessage() {
    var msg = welcomeMsg.trim() || 'Ingresa con tus credenciales para continuar.';
    saveLoginMessage(msg);
    setWelcomeMsg(msg);
    setMsgSaved(true);
    setTimeout(function () { setMsgSaved(false); }, 2500);
  }

  // ── Estilos ───────────────────────────────────────────────────────────────
  var adminProfileInp = {
    width: '100%', padding: '11px 14px', border: '1.5px solid #e5e7eb',
    borderRadius: 8, fontSize: 13, fontFamily: 'inherit', outline: 'none',
    color: '#1e293b', background: 'white', boxSizing: 'border-box', transition: 'border-color .15s'
  };
  var adminProfileLbl = {
    display: 'block', fontSize: 10, fontWeight: 700, color: '#6b7280',
    marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.07em'
  };
  var adminProfileCard = {
    background: 'white', borderRadius: 14, border: '1px solid #e5e7eb',
    padding: '24px 28px', marginBottom: 20
  };
  var adminProfileSecTitle = {
    fontSize: 14, fontWeight: 800, color: '#1c79b4',
    margin: '0 0 18px', paddingBottom: 14, borderBottom: '1px solid #f1f5f9'
  };

  function adminProfileSaveBtn(saved) {
    return {
      padding: '11px 22px', background: saved ? '#22c55e' : '#1c79b4',
      color: 'white', border: 'none', borderRadius: 9, fontSize: 13,
      fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
      transition: 'background .3s', display: 'inline-flex', alignItems: 'center', gap: 7
    };
  }

  var pwMismatch = confirmPw.length > 0 && newPw.length > 0 && confirmPw !== newPw;
  var initials = nombre
    ? nombre.trim().split(/\s+/).slice(0, 2).map(function (w) { return w[0]; }).join('').toUpperCase()
    : '?';

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <div style={{ maxWidth: 680 }}>

      {/* Header de página */}
      <div style={{ marginBottom: 26 }}>
        <h2 style={{ fontSize: 22, fontWeight: 900, color: '#1e293b', margin: '0 0 4px' }}>Mi Perfil</h2>
        <p style={{ fontSize: 13, color: '#9ca3af', margin: 0 }}>
          Gestiona tu información personal y la configuración de la plataforma
        </p>
      </div>

      {/* ── Información personal ────────────────────────────────────────── */}
      <div style={adminProfileCard}>
        <h3 style={adminProfileSecTitle}>Información personal</h3>

        {/* Bloque de foto */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 24, padding: '16px 18px', background: '#f8fafc', borderRadius: 10 }}>
          <div style={{ position: 'relative', flexShrink: 0 }}>
            {photo
              ? <img src={photo} alt={nombre} style={{ width: 76, height: 76, borderRadius: '50%', objectFit: 'cover', border: '3px solid #e2e8f0' }} />
              : <div style={{ width: 76, height: 76, borderRadius: '50%', background: '#1c79b4', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '3px solid #e2e8f0', fontSize: 26, fontWeight: 700, color: '#c4b400', letterSpacing: '0.02em' }}>
                  {initials}
                </div>
            }
            <button
              onClick={function () { fileRef.current && fileRef.current.click(); }}
              title="Cambiar foto"
              style={{ position: 'absolute', bottom: 0, right: 0, width: 26, height: 26, borderRadius: '50%', background: '#1c79b4', border: '2.5px solid white', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontSize: 12, padding: 0, lineHeight: 1 }}
            >✎</button>
          </div>

          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#1e293b', marginBottom: 2 }}>{nombre || 'Administrador'}</div>
            <div style={{ fontSize: 11, color: '#9ca3af', marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Administrador ASSYST</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button
                onClick={function () { fileRef.current && fileRef.current.click(); }}
                style={{ padding: '6px 14px', background: '#1c79b4', color: 'white', border: 'none', borderRadius: 7, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
              >Subir foto</button>
              {photo && (
                <button
                  onClick={handleRemovePhoto}
                  style={{ padding: '6px 14px', background: '#fef2f2', color: '#dc2626', border: '1px solid #fca5a5', borderRadius: 7, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
                >Eliminar foto</button>
              )}
            </div>
          </div>
          <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handlePhotoUpload} />
        </div>

        {/* Nombre + correo */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
          <div>
            <label style={adminProfileLbl}>Nombre completo</label>
            <input
              value={nombre}
              onChange={function (e) { setNombre(e.target.value); }}
              style={adminProfileInp}
              placeholder="Nombre completo"
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>
          <div>
            <label style={adminProfileLbl}>Correo electrónico</label>
            <input
              type="email"
              value={email}
              onChange={function (e) { setEmail(e.target.value); }}
              style={adminProfileInp}
              placeholder="correo@empresa.com"
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>
        </div>

        <button onClick={handleSaveProfile} style={adminProfileSaveBtn(profileSaved)}>
          {profileSaved
            ? <><span>✓</span><span>Cambios guardados</span></>
            : 'Guardar información'}
        </button>
      </div>

      {/* ── Cambiar contraseña ──────────────────────────────────────────── */}
      <div style={adminProfileCard}>
        <h3 style={adminProfileSecTitle}>Cambiar contraseña</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 420 }}>

          {/* Contraseña actual */}
          <div>
            <label style={adminProfileLbl}>Contraseña actual</label>
            <div style={{ position: 'relative' }}>
              <input
                type={showCurrent ? 'text' : 'password'}
                value={currentPw}
                onChange={function (e) { setCurrentPw(e.target.value); setPwError(''); }}
                style={Object.assign({}, adminProfileInp, { paddingRight: 42 })}
                placeholder="••••••••"
                onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
              />
              <button
                onClick={function () { setShowCurrent(function (v) { return !v; }); }}
                style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: '#9ca3af', fontSize: 15, padding: 0, lineHeight: 1 }}
              >{showCurrent ? '🙈' : '👁'}</button>
            </div>
          </div>

          {/* Nueva contraseña */}
          <div>
            <label style={adminProfileLbl}>Nueva contraseña</label>
            <div style={{ position: 'relative' }}>
              <input
                type={showNew ? 'text' : 'password'}
                value={newPw}
                onChange={function (e) { setNewPw(e.target.value); setPwError(''); }}
                style={Object.assign({}, adminProfileInp, { paddingRight: 42 })}
                placeholder="Mínimo 8 caracteres"
                onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
              />
              <button
                onClick={function () { setShowNew(function (v) { return !v; }); }}
                style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: '#9ca3af', fontSize: 15, padding: 0, lineHeight: 1 }}
              >{showNew ? '🙈' : '👁'}</button>
            </div>
            {newPw.length > 0 && newPw.length < 8 && (
              <div style={{ fontSize: 11, color: '#d97706', marginTop: 5, display: 'flex', alignItems: 'center', gap: 4 }}>
                <span>⚠</span> Mínimo 8 caracteres ({newPw.length}/8)
              </div>
            )}
          </div>

          {/* Confirmar contraseña */}
          <div>
            <label style={adminProfileLbl}>Confirmar nueva contraseña</label>
            <div style={{ position: 'relative' }}>
              <input
                type={showConfirm ? 'text' : 'password'}
                value={confirmPw}
                onChange={function (e) { setConfirmPw(e.target.value); setPwError(''); }}
                style={Object.assign({}, adminProfileInp, { paddingRight: 42 })}
                placeholder="••••••••"
                onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                onBlur={function (e) { e.target.style.borderColor = pwMismatch ? '#fca5a5' : '#e5e7eb'; }}
              />
              <button
                onClick={function () { setShowConfirm(function (v) { return !v; }); }}
                style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: '#9ca3af', fontSize: 15, padding: 0, lineHeight: 1 }}
              >{showConfirm ? '🙈' : '👁'}</button>
            </div>
            {pwMismatch && (
              <div style={{ fontSize: 11, color: '#dc2626', marginTop: 5, display: 'flex', alignItems: 'center', gap: 4 }}>
                <span>✕</span> Las contraseñas no coinciden
              </div>
            )}
          </div>
        </div>

        {/* Error global */}
        {pwError && (
          <div style={{ marginTop: 14, padding: '10px 14px', background: '#fef2f2', border: '1px solid #fca5a5', borderRadius: 8, color: '#dc2626', fontSize: 13, maxWidth: 420, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>✕</span> {pwError}
          </div>
        )}

        <button onClick={handleSavePassword} style={Object.assign({}, adminProfileSaveBtn(pwSaved), { marginTop: 18 })}>
          {pwSaved
            ? <><span>✓</span><span>Contraseña actualizada</span></>
            : 'Guardar nueva contraseña'}
        </button>
      </div>

      {/* ── Configuración de plataforma ─────────────────────────────────── */}
      <div style={adminProfileCard}>
        <h3 style={adminProfileSecTitle}>Configuración de la plataforma</h3>
        <div style={{ marginBottom: 16 }}>
          <label style={adminProfileLbl}>Mensaje de bienvenida en login</label>
          <textarea
            value={welcomeMsg}
            onChange={function (e) { setWelcomeMsg(e.target.value); }}
            rows={3}
            style={Object.assign({}, adminProfileInp, { resize: 'vertical', lineHeight: 1.6, minHeight: 78 })}
            placeholder="Ej: Nos alegra tenerte de vuelta. Ingresa con tus credenciales para continuar tu entrenamiento."
            onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
            onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
          />
          <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 5 }}>
            Aparece debajo del título "Bienvenido" en la pantalla de inicio de sesión.
          </div>
        </div>
        <button onClick={handleSaveMessage} style={adminProfileSaveBtn(msgSaved)}>
          {msgSaved
            ? <><span>✓</span><span>Mensaje guardado</span></>
            : 'Guardar mensaje'}
        </button>
      </div>

    </div>
  );
}

window.AdminProfile = AdminProfile;
