// ── Ajustes (/ajustes) ────────────────────────────────────────────────────────
// Página de ajustes en lista agrupada estilo iOS. Reutiliza lo que ya existe:
//   - edición de perfil (atlas.profile.launch.v1 → Coach)
//   - copia de seguridad (window.exportBackup / window.importBackup)
//   - preferencias de descanso/aviso (window.AtlasSettings → atlas.settings.v1)
//   - instalación PWA (window.AtlasPWA)
//   - enlaces legales (window.LegalLinksRow)
// No duplica lógica ni crea stores paralelos.

const SET = {
  page:'#FAFAF7', card:'#FFFFFF', ink:'#0F1A2E', body:'#2C3542', sub:'#5C6477',
  muted:'#8A8F9C', border:'rgba(15,26,46,0.10)', hair:'rgba(15,26,46,0.08)',
  blue:'#2563EB', danger:'#B42318', dangerBg:'rgba(180,35,24,0.06)',
};

const SET_EMAIL = 'atlasmethod.app@gmail.com';
function setMailto(subject, body) {
  let url = 'mailto:' + SET_EMAIL + '?subject=' + encodeURIComponent(subject);
  if (body) url += '&body=' + encodeURIComponent(body);
  return url;
}
function setAppVersion() {
  try { return window.ATLAS_APP_VERSION || '—'; } catch { return '—'; }
}

// ── Primitivas de lista ───────────────────────────────────────────────────────
function SetGroup({ title, children, footer }) {
  return (
    <div style={{ marginBottom: 26 }}>
      {title && (
        <div style={{ fontFamily:'ui-monospace,Menlo,monospace', fontSize:11, fontWeight:700, color:SET.sub, letterSpacing:0.6, textTransform:'uppercase', margin:'0 4px 10px' }}>
          {title}
        </div>
      )}
      <div style={{ background:SET.card, borderRadius:16, border:`1px solid ${SET.border}`, overflow:'hidden' }}>
        {React.Children.toArray(children).filter(Boolean).map((child, i) => (
          <div key={i} style={ i>0 ? { borderTop:`1px solid ${SET.hair}` } : undefined }>{child}</div>
        ))}
      </div>
      {footer && (
        <div style={{ fontFamily:'"Inter",system-ui', fontSize:12, color:SET.muted, lineHeight:1.5, margin:'8px 6px 0' }}>{footer}</div>
      )}
    </div>
  );
}

function SetChevron() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true" style={{ flexShrink:0, color:'#B7BDC8' }}>
      <path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// A tappable row. Renders <a> for href, <button> otherwise. `control` places a
// custom control on the right instead of a chevron (no navigation affordance).
function SetRow({ label, sub, href, onClick, danger, value, control, last }) {
  const isMobile = useIsMobile();
  const color = danger ? SET.danger : SET.ink;
  const inner = (
    <div style={{ display:'flex', gap:12, width:'100%',
      flexDirection: control && isMobile ? 'column' : 'row', alignItems: control && isMobile ? 'stretch' : 'center' }}>
      <div style={{ flex:1, minWidth:0, textAlign:'left' }}>
        <div style={{ fontFamily:'"Inter",system-ui', fontSize:15, fontWeight: danger ? 700 : 600, color, letterSpacing:-0.2 }}>{label}</div>
        {sub && <div style={{ fontFamily:'"Inter",system-ui', fontSize:12.5, color:SET.sub, lineHeight:1.45, marginTop:3 }}>{sub}</div>}
      </div>
      {control ? control : (
        <div style={{ display:'flex', alignItems:'center', gap:8, flexShrink:0 }}>
          {value && <span style={{ fontFamily:'"Inter",system-ui', fontSize:14, color:SET.sub }}>{value}</span>}
          {(href || onClick) && <SetChevron />}
        </div>
      )}
    </div>
  );
  const base = { display:'block', width:'100%', textAlign:'left', background:'transparent', border:'none',
    padding: isMobile ? '15px 16px' : '14px 18px', minHeight:52, cursor: (href||onClick) ? 'pointer' : 'default',
    textDecoration:'none', color:'inherit' };
  if (href) return <a href={href} className="wp-press" style={base}>{inner}</a>;
  if (onClick) return <button onClick={onClick} className="wp-press" style={base}>{inner}</button>;
  return <div style={base}>{inner}</div>;
}

// Segmented control (radiogroup) for the rest-end alert.
function SetSegmented({ options, value, onChange, ariaLabel }) {
  return (
    <div role="radiogroup" aria-label={ariaLabel}
      style={{ display:'flex', gap:4, background:'#EFEFEA', borderRadius:10, padding:3, flexShrink:0 }}>
      {options.map(opt => {
        const active = opt.value === value;
        return (
          <button key={opt.value} role="radio" aria-checked={active} onClick={() => onChange(opt.value)}
            style={{ flex:1, minWidth:72, minHeight:36, padding:'0 14px', borderRadius:8, border:'none', cursor:'pointer',
              background: active ? SET.blue : 'transparent', color: active ? '#fff' : SET.body,
              fontFamily:'"Inter",system-ui', fontSize:13.5, fontWeight:700, transition:'background .12s' }}>
            {opt.label}
          </button>
        );
      })}
    </div>
  );
}

// ── Página ────────────────────────────────────────────────────────────────────
function AjustesSection() {
  const isMobile = useIsMobile();
  const { navigate } = useRoute();

  const settings = (typeof AtlasSettings !== 'undefined') ? AtlasSettings : null;
  const [restDefault, setRestDefault] = React.useState(() => settings ? settings.get('restDefault') : '90s');
  const [restAlert,   setRestAlert]   = React.useState(() => settings ? settings.get('restAlert')   : 'sound');
  const [increments,  setIncrements]  = React.useState(() => settings ? settings.getIncrements() : { barUpper:2.5, barLower:5, dumbbell:2, machine:2.5 });
  const vibrateOk = settings ? settings.vibrateSupported() : false;
  const incrementOptions = settings ? settings.INCREMENT_OPTIONS : [];
  const [creditsOpen, setCreditsOpen] = React.useState(false);
  const imgCount = (typeof ExerciseImages !== 'undefined' && ExerciseImages.MAP)
    ? Object.values(ExerciseImages.MAP).filter(Boolean).length : 0;

  function changeIncrement(type, v) {
    if (!settings) return;
    settings.setIncrement(type, v);
    setIncrements(settings.getIncrements());
  }

  // Import flow (reusa window.importBackup — no se reescribe la lógica).
  const fileRef = React.useRef(null);
  const [confirm, setConfirm] = React.useState(null);
  const [error, setError]     = React.useState(null);
  const [wipeOpen, setWipeOpen] = React.useState(false);
  const [wipeText, setWipeText] = React.useState('');

  const standalone = React.useMemo(() => {
    try { return window.matchMedia && (window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true); }
    catch { return false; }
  }, []);

  function changeRestDefault(v) { setRestDefault(v); if (settings) settings.set('restDefault', v); }
  function changeRestAlert(v)   { setRestAlert(v);   if (settings) settings.set('restAlert', v); }

  function editProfile() {
    try { localStorage.setItem('atlas.profile.launch.v1', '1'); } catch {}
    navigate('/coach');
  }
  function handleExport() { if (typeof exportBackup !== 'undefined') exportBackup(); }
  function handleFile(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    e.target.value = '';
    if (typeof importBackup === 'undefined') return;
    importBackup(file, {
      onSummary: (lines, applyFn) => { setError(null); setConfirm({ summary: lines, applyFn }); },
      onError:   (msg)            => { setConfirm(null); setError(msg); },
    });
  }
  function wipeAll() {
    try {
      const keys = [];
      for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && k.indexOf('atlas.') === 0) keys.push(k); }
      keys.forEach(k => { try { localStorage.removeItem(k); } catch {} });
    } catch {}
    try { window.location.hash = '/'; } catch {}
    window.location.reload();
  }

  const restAlertOptions = [
    { value:'sound', label:'Sonido' },
    ...(vibrateOk ? [{ value:'vibration', label:'Vibración' }] : []),
    { value:'none', label:'Ninguno' },
  ];
  const restOptions = settings ? settings.REST_OPTIONS : [{ value:'90s', label:'90 s' }];

  // Plantillas de correo
  const bugBody = [
    'Cuéntame qué ha pasado:', '',
    '• Qué hacías:', '• Qué esperabas:', '• Qué pasó:', '',
    '------------------------------',
    'Datos técnicos (no los borres, me ayudan a localizar el fallo):',
    'Versión: ' + setAppVersion(),
    'Navegador: ' + ((typeof navigator !== 'undefined' && navigator.userAgent) || '—'),
    'Dispositivo: ' + (isMobile ? 'Móvil' : 'Escritorio'),
  ].join('\n');
  const exerciseBody = [
    'Propongo un ejercicio nuevo:', '',
    '• Nombre:', '• Músculo principal:', '• Material:', '• Vídeo de referencia (si tienes):',
  ].join('\n');

  const btn = (bg, fg, border) => ({ padding: isMobile ? '13px 18px' : '11px 18px', minHeight: isMobile ? 46 : 44,
    borderRadius:11, cursor:'pointer', fontFamily:'"Inter",system-ui', fontSize: isMobile ? 15 : 14, fontWeight:700,
    background:bg, color:fg, border: border || 'none' });

  return (
    <section style={{ background:SET.page, minHeight:'100vh', padding: isMobile ? '24px 16px calc(80px + env(safe-area-inset-bottom))' : '48px 32px 96px' }}>
      <div style={{ maxWidth:640, margin:'0 auto' }}>
        <button onClick={() => navigate('/perfil')} style={{ display:'inline-flex', alignItems:'center', gap:8, marginBottom:22, background:'none', border:'none', cursor:'pointer', fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:600, color:SET.sub, padding:0 }}>
          ← Volver
        </button>
        <h1 style={{ fontFamily:'"Inter",system-ui', fontSize: isMobile ? 28 : 34, fontWeight:800, color:SET.ink, letterSpacing:-0.8, margin:'0 0 24px' }}>
          Ajustes
        </h1>

        {/* 1 · Perfil */}
        <SetGroup title="Perfil">
          <SetRow label="Editar perfil" sub="Objetivo, nivel, días, equipo y prioridades." onClick={editProfile} />
        </SetGroup>

        {/* 2 · Entrenamiento */}
        <SetGroup title="Entrenamiento"
          footer="Si una rutina o plantilla define su propio descanso, ese manda; el descanso por defecto solo se usa cuando el ejercicio no lo indica.">
          <SetRow
            label="Descanso por defecto"
            control={
              <select aria-label="Descanso por defecto" value={restDefault} onChange={e => changeRestDefault(e.target.value)}
                style={{ flexShrink:0, minHeight:40, padding:'0 12px', borderRadius:10, border:`1px solid ${SET.border}`, background:'#fff', color:SET.ink, fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:700, cursor:'pointer' }}>
                {restOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            }
          />
          <SetRow
            label="Aviso al terminar el descanso"
            sub={vibrateOk ? undefined : 'La vibración no está disponible en este dispositivo.'}
            control={<SetSegmented options={restAlertOptions} value={restAlert} onChange={changeRestAlert} ariaLabel="Aviso al terminar el descanso" />}
          />
        </SetGroup>

        {/* 3 · Unidades */}
        <SetGroup title="Unidades"
          footer="Incrementos de carga que usa la sugerencia de progresión del modo entreno. Redondea siempre al incremento que elijas aquí (en kg).">
          {incrementOptions.map(opt => (
            <SetRow
              key={opt.key}
              label={opt.label}
              control={
                <div style={{ display:'flex', alignItems:'center', gap:6, flexShrink:0 }}>
                  <input
                    type="number" inputMode="decimal" min="0.5" max="25" step="0.5"
                    aria-label={`Incremento · ${opt.label} (kg)`}
                    value={increments[opt.key]}
                    onChange={e => changeIncrement(opt.key, e.target.value)}
                    style={{ width:72, minHeight:40, padding:'0 10px', borderRadius:10, border:`1px solid ${SET.border}`, background:'#fff', color:SET.ink, fontFamily:'"Inter",system-ui', fontSize:15, fontWeight:700, textAlign:'right' }}
                  />
                  <span style={{ fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:700, color:SET.sub }}>kg</span>
                </div>
              }
            />
          ))}
        </SetGroup>

        {/* 4 · Tus datos */}
        <SetGroup title="Tus datos"
          footer="Tus datos viven solo en este dispositivo y navegador. Descarga una copia para no perderlos si cambias de dispositivo o borras la caché.">
          <SetRow label="Exportar copia de seguridad" onClick={handleExport} />
          <SetRow label="Importar copia" onClick={() => fileRef.current && fileRef.current.click()} />
          <SetRow label="Borrar todos mis datos" danger onClick={() => { setWipeText(''); setWipeOpen(true); }} />
        </SetGroup>
        <input ref={fileRef} type="file" accept=".json" style={{ display:'none' }} onChange={handleFile} />

        {error && (
          <div style={{ margin:'-14px 0 26px', padding:'10px 14px', borderRadius:10, background:'rgba(180,40,40,0.06)', border:'1px solid rgba(180,40,40,0.15)', fontFamily:'"Inter",system-ui', fontSize:12.5, color:'#9B1C1C', lineHeight:1.5 }}>
            {error}
            <button onClick={() => setError(null)} style={{ marginLeft:10, background:'none', border:'none', cursor:'pointer', color:'#9B1C1C', fontSize:11, fontWeight:700, padding:0 }}>✕</button>
          </div>
        )}

        {/* 4 · Ayuda y sugerencias */}
        <SetGroup title="Ayuda y sugerencias">
          <SetRow label="Informar de un error" href={setMailto('Error - Atlas Method', bugBody)} />
          <SetRow label="Sugerir una mejora" href={setMailto('Sugerencia - Atlas Method')} />
          <SetRow label="Sugerir un ejercicio" href={setMailto('Nuevo ejercicio - Atlas Method', exerciseBody)} />
          <SetRow label="Colabora con Atlas" sub="¿Eres graduado en Ciencias de la Actividad Física y del Deporte o dietista-nutricionista y te interesa colaborar? Escríbeme." href={setMailto('Colaboración - Atlas Method')} />
          {(typeof ATLAS_FEATURE === 'function' && ATLAS_FEATURE('FEATURE_COACH_ONLINE')) && (
            <SetRow label="Entrena con un coach" onClick={() => navigate('/coach-online')} />
          )}
        </SetGroup>

        {/* 5 · App */}
        <SetGroup title="App" footer={standalone ? undefined : 'En iPhone: Compartir → Añadir a pantalla de inicio. En Android: menú del navegador → Instalar app / Añadir a pantalla de inicio.'}>
          <SetRow
            label="Instalar en tu móvil"
            value={standalone ? 'Ya instalada' : undefined}
            onClick={standalone ? undefined : () => { try { window.AtlasPWA && window.AtlasPWA.open(); } catch {} }}
          />
        </SetGroup>

        {/* 6 · Legal */}
        <SetGroup title="Legal">
          <div style={{ padding: isMobile ? '15px 16px' : '15px 18px' }}>
            {typeof LegalLinksRow === 'function'
              ? <LegalLinksRow color={SET.body} size={14} />
              : <span style={{ fontFamily:'"Inter",system-ui', fontSize:14, color:SET.sub }}>—</span>}
          </div>
        </SetGroup>

        {/* 7 · Acerca de */}
        <SetGroup title="Acerca de">
          <SetRow label="Versión" value={setAppVersion()} />
          <SetRow label="Créditos de imágenes" sub="Fotos de ejercicios y sus licencias" onClick={() => setCreditsOpen(true)} />
          <div style={{ padding: isMobile ? '15px 16px 17px' : '16px 18px 18px' }}>
            <p style={{ fontFamily:'"Instrument Serif",Georgia,serif', fontStyle:'italic', fontSize:16, color:SET.body, lineHeight:1.5, margin:0 }}>
              Entrenar con fundamento no es tener todas las respuestas: es dejar de adivinar.
            </p>
          </div>
        </SetGroup>
      </div>

      {/* Modal: créditos de imágenes */}
      {creditsOpen && (
        <SetModal onClose={() => setCreditsOpen(false)}>
          <div style={{ fontFamily:'"Inter",system-ui', fontSize:17, fontWeight:800, color:SET.ink, marginBottom:10 }}>Créditos de imágenes</div>
          <p style={{ fontFamily:'"Inter",system-ui', fontSize:13.5, color:SET.body, lineHeight:1.6, margin:'0 0 12px' }}>
            Las <b>{imgCount}</b> fotos de ejercicios proceden de <b>free-exercise-db</b>, bajo <b>Unlicense (dominio público)</b>. Se han redimensionado y convertido a WebP, y se alojan en la propia app (no dependen de servidores externos).
          </p>
          <p style={{ fontFamily:'"Inter",system-ui', fontSize:13.5, color:SET.body, lineHeight:1.6, margin:'0 0 12px' }}>
            Algunos ejercicios muestran una imagen de referencia de una variante (distinto material); se indica con un pie en la tarjeta. El resto usa una ilustración del grupo muscular. No se usan imágenes con licencia restrictiva ni generadas con IA.
          </p>
          <a href="https://github.com/yuhonas/free-exercise-db" target="_blank" rel="noopener noreferrer"
            style={{ fontFamily:'"Inter",system-ui', fontSize:13.5, fontWeight:700, color:SET.accent || '#2563EB', textDecoration:'none' }}>
            github.com/yuhonas/free-exercise-db →
          </a>
          <div style={{ marginTop:16 }}>
            <button onClick={() => setCreditsOpen(false)} style={btn('#0F1A2E', '#FAFAF7')}>Cerrar</button>
          </div>
        </SetModal>
      )}

      {/* Modal: confirmar importación */}
      {confirm && (
        <SetModal onClose={() => setConfirm(null)}>
          <div style={{ fontFamily:'"Inter",system-ui', fontSize:15, fontWeight:800, color:SET.ink, marginBottom:10 }}>Este backup contiene:</div>
          <ul style={{ margin:'0 0 12px 18px', padding:0 }}>
            {confirm.summary.map((line, i) => <li key={i} style={{ fontFamily:'"Inter",system-ui', fontSize:13, color:SET.body, marginBottom:3 }}>{line}</li>)}
          </ul>
          <div style={{ fontFamily:'"Inter",system-ui', fontSize:12.5, color:SET.sub, marginBottom:16, lineHeight:1.5 }}>Esto sobrescribirá los datos actuales de este dispositivo. La app se recargará.</div>
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={() => { confirm.applyFn(); setConfirm(null); }} style={btn('#0F1A2E', '#FAFAF7')}>Restaurar ahora</button>
            <button onClick={() => setConfirm(null)} style={btn('transparent', SET.sub, `1px solid ${SET.border}`)}>Cancelar</button>
          </div>
        </SetModal>
      )}

      {/* Modal: borrar todos los datos */}
      {wipeOpen && (
        <SetModal onClose={() => setWipeOpen(false)}>
          <div style={{ fontFamily:'"Inter",system-ui', fontSize:17, fontWeight:800, color:SET.ink, marginBottom:10 }}>Borrar todos mis datos</div>
          <p style={{ fontFamily:'"Inter",system-ui', fontSize:13.5, color:SET.body, lineHeight:1.6, margin:'0 0 14px' }}>
            Se borrarán tus rutinas, historial, chats y progreso de este dispositivo. Te recomendamos exportar una copia antes.
          </p>
          <label style={{ fontFamily:'"Inter",system-ui', fontSize:12.5, fontWeight:700, color:SET.sub, display:'block', marginBottom:6 }}>
            Escribe <b style={{ color:SET.danger }}>BORRAR</b> para confirmar:
          </label>
          <input
            value={wipeText} onChange={e => setWipeText(e.target.value)} aria-label="Escribe BORRAR para confirmar"
            autoFocus autoCapitalize="characters" autoCorrect="off" spellCheck={false}
            style={{ width:'100%', boxSizing:'border-box', minHeight:46, padding:'0 14px', borderRadius:10, border:`1px solid ${SET.border}`, fontFamily:'"Inter",system-ui', fontSize:15, color:SET.ink, marginBottom:16 }}
          />
          <div style={{ display:'flex', gap:10 }}>
            <button
              onClick={wipeAll}
              disabled={wipeText.trim().toUpperCase() !== 'BORRAR'}
              style={{ ...btn(wipeText.trim().toUpperCase() === 'BORRAR' ? SET.danger : 'rgba(180,35,24,0.35)', '#fff'),
                cursor: wipeText.trim().toUpperCase() === 'BORRAR' ? 'pointer' : 'not-allowed' }}
            >
              Borrar definitivamente
            </button>
            <button onClick={() => setWipeOpen(false)} style={btn('transparent', SET.sub, `1px solid ${SET.border}`)}>Cancelar</button>
          </div>
        </SetModal>
      )}
    </section>
  );
}

// Modal con respaldo oscuro, centrado, accesible (Esc / clic fuera para cerrar).
function SetModal({ children, onClose }) {
  const isMobile = useIsMobile();
  React.useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} role="dialog" aria-modal="true"
      style={{ position:'fixed', inset:0, zIndex:1000, background:'rgba(15,26,46,0.45)', display:'flex', alignItems: isMobile ? 'flex-end' : 'center', justifyContent:'center', padding: isMobile ? 0 : 20 }}>
      <div onClick={e => e.stopPropagation()}
        style={{ background:'#fff', borderRadius: isMobile ? '18px 18px 0 0' : 18, border:`1px solid ${SET.border}`, padding: isMobile ? '22px 18px calc(22px + env(safe-area-inset-bottom))' : '24px 26px', width:'100%', maxWidth: isMobile ? '100%' : 440, boxShadow:'0 20px 60px -20px rgba(15,26,46,0.4)' }}>
        {children}
      </div>
    </div>
  );
}

function AjustesPage() { return <AjustesSection />; }

Object.assign(window, { AjustesSection, AjustesPage });
