const { useState: useStatePM, useEffect: useEffectPM, useRef: useRefPM } = React;

var SECTORES_PM = ['Construcción', 'Industrial', 'Salud', 'Logística', 'Servicios', 'Comercio', 'Otro'];
var COMO_ENTERO_PM = ['TikTok', 'Recomendación', 'Google', 'Otro'];

var FI_PM = {
  width: '100%',
  padding: '10px 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 LBL_PM = {
  display: 'block',
  fontSize: 10,
  fontWeight: 700,
  color: '#6b7280',
  marginBottom: 5,
  textTransform: 'uppercase',
  letterSpacing: '0.07em'
};

var SELECT_ARROW = 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%236b7280\' stroke-width=\'2.5\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3E%3Cpolyline points=\'6 9 12 15 18 9\'%3E%3C/polyline%3E%3C/svg%3E")';

function ProfileModal({ user, onClose, onPhotoChange }) {
  const [form, setForm] = useStatePM(function () {
    var stored = getProfileData(user.id);
    return Object.assign({
      documento: '',
      whatsapp: '',
      ciudad: '',
      empresa: user.empresa || '',
      cargo: user.cargo || '',
      sector: '',
      sectorOtro: '',
      anosExperiencia: '',
      tieneLicencia: '',
      comoSeEntero: '',
      comoSeEnteroOtro: ''
    }, stored);
  });
  const [saved, setSaved] = useStatePM(false);
  const fileRef = useRefPM(null);
  const [photo, setPhoto] = useStatePM(function () { return getStudentPhoto(user.id); });

  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 sf(k, v) {
    setForm(function (f) { return Object.assign({}, f, { [k]: v }); });
  }

  function handleSave() {
    saveProfileData(user.id, form);
    setSaved(true);
    setTimeout(function () { setSaved(false); }, 2500);
  }

  useEffectPM(function () {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    return function () { document.removeEventListener('keydown', onKey); };
  }, []);

  var selectStyle = Object.assign({}, FI_PM, {
    cursor: 'pointer',
    appearance: 'none',
    WebkitAppearance: 'none',
    backgroundImage: SELECT_ARROW,
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'right 14px center',
    paddingRight: 38
  });

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,61,94,.78)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={function (e) { e.stopPropagation(); }} style={{ background: 'white', borderRadius: 18, width: '100%', maxWidth: 640, maxHeight: '92vh', overflowY: 'auto', boxShadow: '0 32px 80px rgba(0,0,0,.32)', display: 'flex', flexDirection: 'column' }}>

        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '22px 28px', borderBottom: '1px solid #f1f5f9', flexShrink: 0, position: 'sticky', top: 0, background: 'white', zIndex: 1, borderRadius: '18px 18px 0 0' }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800, color: '#1c79b4' }}>Mi Perfil</h3>
            <p style={{ margin: '3px 0 0', fontSize: 12, color: '#9ca3af' }}>Completa tus datos para personalizar tu experiencia</p>
          </div>
          <button onClick={onClose} style={{ background: '#f1f5f9', border: 'none', width: 34, height: 34, borderRadius: 8, cursor: 'pointer', fontSize: 20, color: '#6b7280', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'inherit', lineHeight: 1 }}>×</button>
        </div>

        {/* Identity block */}
        <div style={{ padding: '20px 28px 4px', flexShrink: 0 }}>
          <div style={{ background: '#f8fafc', borderRadius: 12, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
            {/* Avatar con botón de subida */}
            <div style={{ position: 'relative', flexShrink: 0 }}>
              <StudentAvatar userId={user.id} userName={user.nombre} size={56} style={{ border: '2.5px solid #e2e8f0' }} />
              <button
                onClick={function () { fileRef.current && fileRef.current.click(); }}
                title="Cambiar foto"
                style={{ position: 'absolute', bottom: 0, right: 0, width: 22, height: 22, borderRadius: '50%', background: '#1c79b4', border: '2px solid white', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontSize: 11, padding: 0, lineHeight: 1 }}
              >✎</button>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 700, color: '#1e293b' }}>{user.nombre}</div>
              <div style={{ fontSize: 12, color: '#9ca3af', marginTop: 1 }}>{user.email}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                <button
                  onClick={function () { fileRef.current && fileRef.current.click(); }}
                  style={{ padding: '5px 12px', background: '#1c79b4', color: 'white', border: 'none', borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
                >Subir foto</button>
                {photo && (
                  <button
                    onClick={handleRemovePhoto}
                    style={{ padding: '5px 12px', background: '#fef2f2', color: '#dc2626', border: '1px solid #fca5a5', borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
                  >Eliminar</button>
                )}
              </div>
            </div>
            <div style={{ fontSize: 10, fontWeight: 700, color: '#1c79b4', background: 'rgba(28,121,180,.08)', padding: '4px 10px', borderRadius: 20, whiteSpace: 'nowrap', alignSelf: 'flex-start' }}>Estudiante</div>
          </div>
          <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handlePhotoUpload} />
        </div>

        {/* Form grid */}
        <div style={{ padding: '16px 28px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>

          {/* Documento */}
          <div>
            <label style={LBL_PM}>Número de documento</label>
            <input
              value={form.documento}
              onChange={function (e) { sf('documento', e.target.value); }}
              placeholder="Ej: 1023456789"
              style={FI_PM}
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>

          {/* WhatsApp */}
          <div>
            <label style={LBL_PM}>Número de WhatsApp</label>
            <input
              value={form.whatsapp}
              onChange={function (e) { sf('whatsapp', e.target.value); }}
              placeholder="Ej: 3101234567"
              style={FI_PM}
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>

          {/* Ciudad */}
          <div>
            <label style={LBL_PM}>Ciudad de residencia</label>
            <input
              value={form.ciudad}
              onChange={function (e) { sf('ciudad', e.target.value); }}
              placeholder="Ej: Bogotá D.C."
              style={FI_PM}
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>

          {/* Años experiencia */}
          <div>
            <label style={LBL_PM}>Años de experiencia en SST</label>
            <input
              type="number"
              min="0"
              max="50"
              value={form.anosExperiencia}
              onChange={function (e) { sf('anosExperiencia', e.target.value); }}
              placeholder="Ej: 3"
              style={FI_PM}
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>

          {/* Empresa */}
          <div>
            <label style={LBL_PM}>Empresa donde trabaja</label>
            <input
              value={form.empresa}
              onChange={function (e) { sf('empresa', e.target.value); }}
              placeholder="Nombre de la empresa"
              style={FI_PM}
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>

          {/* Cargo */}
          <div>
            <label style={LBL_PM}>Cargo / Posición</label>
            <input
              value={form.cargo}
              onChange={function (e) { sf('cargo', e.target.value); }}
              placeholder="Ej: Coordinador SST"
              style={FI_PM}
              onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
              onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
            />
          </div>

          {/* Sector — full width */}
          <div style={{ gridColumn: 'span 2' }}>
            <label style={LBL_PM}>Sector de la empresa</label>
            <select
              value={form.sector}
              onChange={function (e) { sf('sector', e.target.value); }}
              style={selectStyle}
            >
              <option value="">Seleccionar sector...</option>
              {SECTORES_PM.map(function (s) { return <option key={s} value={s}>{s}</option>; })}
            </select>
            {form.sector === 'Otro' && (
              <input
                value={form.sectorOtro || ''}
                onChange={function (e) { sf('sectorOtro', e.target.value); }}
                placeholder="Especifica el sector de tu empresa..."
                style={Object.assign({}, FI_PM, { marginTop: 8, borderColor: '#c4b400' })}
                onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                onBlur={function (e) { e.target.style.borderColor = '#c4b400'; }}
                autoFocus
              />
            )}
          </div>

          {/* Licencia SST */}
          <div>
            <label style={LBL_PM}>¿Tiene licencia SST vigente?</label>
            <div style={{ display: 'flex', gap: 8, marginTop: 2 }}>
              {[['si', 'Sí'], ['no', 'No']].map(function (opt) {
                var sel = form.tieneLicencia === opt[0];
                return (
                  <button
                    key={opt[0]}
                    onClick={function () { sf('tieneLicencia', opt[0]); }}
                    style={{
                      flex: 1,
                      padding: '10px',
                      borderRadius: 8,
                      border: '1.5px solid ' + (sel ? '#1c79b4' : '#e5e7eb'),
                      background: sel ? 'rgba(28,121,180,.07)' : 'white',
                      color: sel ? '#1c79b4' : '#6b7280',
                      fontWeight: sel ? 700 : 400,
                      fontSize: 13,
                      cursor: 'pointer',
                      fontFamily: 'inherit',
                      transition: 'all .15s'
                    }}
                  >
                    {opt[1]}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Cómo se enteró */}
          <div>
            <label style={LBL_PM}>¿Cómo se enteró del curso?</label>
            <select
              value={form.comoSeEntero}
              onChange={function (e) { sf('comoSeEntero', e.target.value); }}
              style={selectStyle}
            >
              <option value="">Seleccionar...</option>
              {COMO_ENTERO_PM.map(function (s) { return <option key={s} value={s}>{s}</option>; })}
            </select>
            {form.comoSeEntero === 'Otro' && (
              <input
                value={form.comoSeEnteroOtro || ''}
                onChange={function (e) { sf('comoSeEnteroOtro', e.target.value); }}
                placeholder="Especifica cómo te enteraste..."
                style={Object.assign({}, FI_PM, { marginTop: 8, borderColor: '#c4b400' })}
                onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                onBlur={function (e) { e.target.style.borderColor = '#c4b400'; }}
                autoFocus
              />
            )}
          </div>

        </div>

        {/* Footer */}
        <div style={{ padding: '4px 28px 24px', flexShrink: 0 }}>
          <button
            onClick={handleSave}
            style={{
              width: '100%',
              padding: '13px',
              background: saved ? '#22c55e' : '#1c79b4',
              color: 'white',
              border: 'none',
              borderRadius: 10,
              fontSize: 14,
              fontWeight: 700,
              cursor: 'pointer',
              fontFamily: 'inherit',
              transition: 'background .3s',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 8
            }}
          >
            {saved ? (
              <>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                ¡Cambios guardados!
              </>
            ) : 'Guardar cambios'}
          </button>
          <button
            onClick={function () { onClose(); setTimeout(function () { if (window.startTour) window.startTour(); }, 80); }}
            style={{
              width: '100%',
              marginTop: 10,
              padding: '11px',
              background: 'white',
              color: '#1c79b4',
              border: '1.5px solid #1c79b4',
              borderRadius: 10,
              fontSize: 13,
              fontWeight: 700,
              cursor: 'pointer',
              fontFamily: 'inherit',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 8,
              transition: 'background .15s',
            }}
            onMouseOver={function (e) { e.currentTarget.style.background = 'rgba(28,121,180,.05)'; }}
            onMouseOut={function (e) { e.currentTarget.style.background = 'white'; }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <line x1="12" y1="8" x2="12" y2="12"></line>
              <line x1="12" y1="16" x2="12.01" y2="16"></line>
            </svg>
            Ver tour de nuevo
          </button>
        </div>

      </div>
    </div>
  );
}

window.ProfileModal = ProfileModal;
