const { useState: useStateAB, useRef: useRefAB } = React;

function AdminBiblio() {
  const initial = getBioData();
  const [photo, setPhoto] = useStateAB(initial.photo);
  const [bioText, setBioText] = useStateAB(initial.text);
  const [photoMode, setPhotoMode] = useStateAB('idle'); // 'idle' | 'url'
  const [urlInput, setUrlInput] = useStateAB('');
  const [saved, setSaved] = useStateAB(false);
  const fileRef = useRefAB(null);

  function handleSave() {
    saveBioData({ photo: photo, text: bioText });
    setSaved(true);
    setTimeout(function () { setSaved(false); }, 2800);
  }

  function applyUrl() {
    var v = urlInput.trim();
    if (!v) return;
    setPhoto(v);
    setPhotoMode('idle');
    setUrlInput('');
  }

  function removePhoto() {
    setPhoto(null);
    setPhotoMode('idle');
    setUrlInput('');
  }

  function handleFile(e) {
    var file = e.target.files && e.target.files[0];
    if (!file) return;
    var reader = new FileReader();
    reader.onload = function (ev) {
      setPhoto(ev.target.result);
      setPhotoMode('idle');
    };
    reader.readAsDataURL(file);
    e.target.value = '';
  }

  return (
    <div style={{ maxWidth: 740, fontFamily: "'Montserrat', sans-serif" }}>
      <div style={{ marginBottom: 26 }}>
        <h2 style={{ margin: '0 0 5px', fontSize: 18, fontWeight: 800, color: '#1c79b4' }}>Bibliografía del Creador del Curso</h2>
        <p style={{ margin: 0, fontSize: 13, color: '#6b7280' }}>Configura la foto y el texto biográfico del creador del curso que verán los estudiantes al hacer clic en el panel lateral.</p>
      </div>

      {/* ── Foto ── */}
      <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e5e7eb', padding: '24px', marginBottom: 16 }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.09em', marginBottom: 18 }}>Foto del Creador del Curso</div>

        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 24, flexWrap: 'wrap' }}>
          {/* Preview circular */}
          <div style={{ flexShrink: 0, textAlign: 'center' }}>
            <div style={{
              width: 108, height: 108, borderRadius: '50%',
              border: '3px solid #c4b400',
              overflow: 'hidden', background: '#f1f5f9',
              margin: '0 auto 8px'
            }}>
              {photo ? (
                <img
                  src={photo}
                  alt="Autor"
                  style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top' }}
                />
              ) : (
                <div style={{ width: '100%', height: '100%', background: '#e5e7eb', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="58%" height="58%" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="12" cy="8" r="4" fill="#9ca3af" />
                    <path d="M4 20c0-4.418 3.582-8 8-8s8 3.582 8 8" fill="#9ca3af" />
                  </svg>
                </div>
              )}
            </div>
            <div style={{ fontSize: 10, color: '#9ca3af' }}>Vista previa</div>
          </div>

          {/* Controles */}
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
              <button
                onClick={function () { setPhotoMode(photoMode === 'url' ? 'idle' : 'url'); }}
                style={{
                  flex: 1, minWidth: 110, padding: '9px 12px', borderRadius: 8,
                  border: '2px solid ' + (photoMode === 'url' ? '#1c79b4' : '#e5e7eb'),
                  background: photoMode === 'url' ? '#eef6ff' : 'white',
                  color: photoMode === 'url' ? '#1c79b4' : '#6b7280',
                  fontSize: 12, fontWeight: 600, cursor: 'pointer',
                  fontFamily: 'inherit', transition: 'all .15s'
                }}
              >🔗 Pegar URL</button>
              <button
                onClick={function () { setPhotoMode('idle'); fileRef.current && fileRef.current.click(); }}
                style={{
                  flex: 1, minWidth: 110, padding: '9px 12px', borderRadius: 8,
                  border: '2px solid #e5e7eb',
                  background: 'white',
                  color: '#6b7280',
                  fontSize: 12, fontWeight: 600, cursor: 'pointer',
                  fontFamily: 'inherit', transition: 'all .15s'
                }}
                onMouseOver={function (e) { e.currentTarget.style.borderColor = '#1c79b4'; e.currentTarget.style.color = '#1c79b4'; }}
                onMouseOut={function (e) { e.currentTarget.style.borderColor = '#e5e7eb'; e.currentTarget.style.color = '#6b7280'; }}
              >📁 Subir imagen</button>
              {photo && (
                <button
                  onClick={removePhoto}
                  style={{
                    flex: 1, minWidth: 110, padding: '9px 12px', borderRadius: 8,
                    border: '2px solid #fca5a5',
                    background: 'white',
                    color: '#ef4444',
                    fontSize: 12, fontWeight: 600, cursor: 'pointer',
                    fontFamily: 'inherit', transition: 'all .15s'
                  }}
                  onMouseOver={function (e) { e.currentTarget.style.background = '#fef2f2'; e.currentTarget.style.borderColor = '#ef4444'; }}
                  onMouseOut={function (e) { e.currentTarget.style.background = 'white'; e.currentTarget.style.borderColor = '#fca5a5'; }}
                >🗑 Eliminar foto</button>
              )}
              <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleFile} />
            </div>

            {photoMode === 'url' && (
              <div style={{ display: 'flex', gap: 8 }}>
                <input
                  type="text"
                  value={urlInput}
                  onChange={function (e) { setUrlInput(e.target.value); }}
                  onKeyDown={function (e) { if (e.key === 'Enter') applyUrl(); }}
                  placeholder="https://ejemplo.com/foto.jpg"
                  style={{
                    flex: 1, padding: '10px 13px',
                    border: '1px solid #d1d5db', borderRadius: 8,
                    fontSize: 12, fontFamily: 'inherit', outline: 'none', color: '#374151'
                  }}
                  onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                  onBlur={function (e) { e.target.style.borderColor = '#d1d5db'; }}
                />
                <button
                  onClick={applyUrl}
                  style={{
                    padding: '10px 18px', background: '#1c79b4',
                    color: 'white', border: 'none', borderRadius: 8,
                    fontSize: 12, fontWeight: 700, cursor: 'pointer',
                    fontFamily: 'inherit', whiteSpace: 'nowrap'
                  }}
                >Aplicar</button>
              </div>
            )}

            {photoMode === 'idle' && (
              <div style={{ fontSize: 12, color: '#9ca3af', lineHeight: 1.5 }}>
                Sube una imagen desde tu equipo o pega una URL externa.<br />
                La foto se muestra recortada en círculo.
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ── Texto biográfico ── */}
      <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e5e7eb', padding: '24px', marginBottom: 20 }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.09em', marginBottom: 14 }}>Texto Biográfico</div>
        <textarea
          value={bioText}
          onChange={function (e) { setBioText(e.target.value); }}
          rows={11}
          placeholder="Escribe aquí la biografía completa del autor..."
          style={{
            width: '100%', padding: '14px',
            border: '1px solid #d1d5db', borderRadius: 10,
            fontSize: 13, fontFamily: 'inherit',
            lineHeight: 1.75, resize: 'vertical',
            outline: 'none', color: '#374151',
            boxSizing: 'border-box', display: 'block'
          }}
          onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
          onBlur={function (e) { e.target.style.borderColor = '#d1d5db'; }}
        />
        <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 7 }}>
          Usa doble salto de línea (Enter × 2) para separar párrafos.
        </div>
      </div>

      {/* ── Guardar ── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <button
          onClick={handleSave}
          style={{
            background: '#1c79b4', color: 'white',
            border: 'none', borderRadius: 10,
            padding: '13px 30px', fontSize: 13,
            fontWeight: 700, cursor: 'pointer',
            fontFamily: 'inherit', transition: 'background .15s'
          }}
          onMouseOver={function (e) { e.currentTarget.style.background = '#145580'; }}
          onMouseOut={function (e) { e.currentTarget.style.background = '#1c79b4'; }}
        >Guardar cambios</button>

        {saved && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 7,
            color: '#15803d', fontSize: 13, fontWeight: 600,
            animation: 'fadeIn .25s ease'
          }}>
            <span style={{
              width: 22, height: 22, background: '#22c55e', borderRadius: '50%',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'white', fontSize: 11, fontWeight: 900
            }}>✓</span>
            Cambios guardados correctamente
          </div>
        )}
      </div>
    </div>
  );
}

window.AdminBiblio = AdminBiblio;
