
// ── Settings Screen — Responsive ─────────────────────────────────────────────
const { useState: useStateSettingsR } = React;

function ScreenSettings({ onLogout, username }) {
  const { state, updateGoals } = useSalud();
  const [oldPass, setOldPass]     = useStateSettingsR('');
  const [newPass, setNewPass]     = useStateSettingsR('');
  const [newPass2, setNewPass2]   = useStateSettingsR('');
  const [passMsg, setPassMsg]     = useStateSettingsR(null);
  const [bioLoading, setBioLoad]  = useStateSettingsR(false);
  const [bioMsg, setBioMsg]       = useStateSettingsR(null);
  const [biometric, setBiometric] = useStateSettingsR(localStorage.getItem(WAUTH_KEY)==='true');
  const [section, setSection]     = useStateSettingsR(null);
  const [goalsForm, setGoalsForm] = useStateSettingsR({ ...state.goals });
  const [goalsMsg, setGoalsMsg]   = useStateSettingsR(null);

  const webauthnSupported = !!window.PublicKeyCredential;

  const handleChangePass = async () => {
    setPassMsg(null);
    if (newPass.length < 6)   { setPassMsg({ type:'error', text:'Mínimo 6 caracteres' }); return; }
    if (newPass !== newPass2) { setPassMsg({ type:'error', text:'Las contraseñas no coinciden' }); return; }
    try {
      await api.changePassword(oldPass, newPass);
      setOldPass(''); setNewPass(''); setNewPass2('');
      setPassMsg({ type:'ok', text:'✓ Contraseña actualizada' });
      setTimeout(() => { setPassMsg(null); setSection(null); }, 2500);
    } catch(e) { setPassMsg({ type:'error', text:e.message }); }
  };

  const handleToggleBio = async () => {
    setBioMsg(null); setBioLoad(true);
    try {
      if (biometric) {
        localStorage.setItem(WAUTH_KEY,'false'); localStorage.removeItem('salud_cred_id');
        setBiometric(false); setBioMsg({ type:'ok', text:'Biometría desactivada' });
      } else {
        await registerBiometric(username||'ruben');
        setBiometric(true); setBioMsg({ type:'ok', text:'✓ Face ID / Touch ID activado' });
      }
    } catch(e) { if(e.name!=='NotAllowedError') setBioMsg({ type:'error', text:e.message }); }
    finally { setBioLoad(false); }
    setTimeout(() => setBioMsg(null), 3000);
  };

  const handleSaveGoals = async () => {
    try {
      await updateGoals({ kcal:+goalsForm.kcal, prot:+goalsForm.prot, carbs:+goalsForm.carbs, fat:+goalsForm.fat });
      setGoalsMsg({ type:'ok', text:'✓ Objetivos guardados' });
      setTimeout(() => { setGoalsMsg(null); setSection(null); }, 2500);
    } catch(e) { setGoalsMsg({ type:'error', text:e.message }); }
  };

  const Toggle = ({ on, onClick }) => (
    <button className={`toggle ${on?'toggle-on':'toggle-off'}`} onClick={onClick}>
      <div className={`toggle-thumb ${on?'toggle-thumb-on':'toggle-thumb-off'}`} />
    </button>
  );

  const Section = ({ id, icon, label, children }) => (
    <div>
      <div className="list-row" style={{ cursor:'pointer' }} onClick={() => setSection(section===id?null:id)}>
        <div style={{ flex:1, fontSize:16, color:'#1C1C1E' }}>{icon} {label}</div>
        <span style={{ color:'#AEAEB2', fontSize:12 }}>{section===id?'▲':'▼'}</span>
      </div>
      {section===id && <div style={{ padding:'4px 0 16px' }}>{children}</div>}
    </div>
  );

  return (
    <div className="page">
      <div className="page-header"><h1>Ajustes</h1></div>

      {/* Profile */}
      <div className="card" style={{ display:'flex', alignItems:'center', gap:16, marginBottom:24 }}>
        <div className="avatar" style={{ width:56, height:56, fontSize:22, borderRadius:28 }}>{(username||'R').charAt(0).toUpperCase()}</div>
        <div>
          <div style={{ fontWeight:700, fontSize:18 }}>{username||'ruben'}</div>
          <div style={{ fontSize:13, color:'#8E8E93' }}>salud.rubenfer.es</div>
        </div>
      </div>

      {/* Seguridad */}
      <div style={{ fontSize:12, fontWeight:700, color:'#8E8E93', textTransform:'uppercase', letterSpacing:.5, marginBottom:8 }}>Seguridad</div>
      <div className="card">
        <Section id="pass" icon="🔑" label="Cambiar contraseña">
          <input className="form-input" type="password" placeholder="Contraseña actual" value={oldPass} onChange={e=>setOldPass(e.target.value)} style={{ marginBottom:8 }} />
          <input className="form-input" type="password" placeholder="Nueva contraseña" value={newPass} onChange={e=>setNewPass(e.target.value)} style={{ marginBottom:8 }} />
          <input className="form-input" type="password" placeholder="Repetir nueva contraseña" value={newPass2} onChange={e=>setNewPass2(e.target.value)} style={{ marginBottom:12 }} />
          {passMsg && <div className={passMsg.type==='ok'?'msg-ok':'msg-err'}>{passMsg.text}</div>}
          <button className="btn-primary" style={{ width:'100%' }} onClick={handleChangePass}>Guardar contraseña</button>
        </Section>
        <div className="list-row">
          <div style={{ flex:1 }}>
            <div style={{ fontSize:16 }}>🔒 Face ID / Touch ID</div>
            <div style={{ fontSize:12, color:'#8E8E93' }}>{!webauthnSupported?'No disponible':biometric?'Activado':'Desactivado'}</div>
          </div>
          {webauthnSupported && !bioLoading && <Toggle on={biometric} onClick={handleToggleBio} />}
          {bioLoading && <span style={{ color:'#8E8E93' }}>⏳</span>}
        </div>
        {bioMsg && <div className={bioMsg.type==='ok'?'msg-ok':'msg-err'}>{bioMsg.text}</div>}
      </div>

      {/* Objetivos */}
      <div style={{ fontSize:12, fontWeight:700, color:'#8E8E93', textTransform:'uppercase', letterSpacing:.5, marginBottom:8 }}>Objetivos diarios</div>
      <div className="card">
        <Section id="goals" icon="🎯" label="Editar objetivos nutricionales">
          <div className="form-row" style={{ flexWrap:'wrap' }}>
            {[['kcal','Calorías'],['prot','Proteína g'],['carbs','Carbos g'],['fat','Grasa g']].map(([k,l])=>(
              <div key={k} className="form-group" style={{ minWidth:120 }}>
                <label className="form-label">{l}</label>
                <input className="form-input" type="number" value={goalsForm[k]} onChange={e=>setGoalsForm(f=>({...f,[k]:e.target.value}))} />
              </div>
            ))}
          </div>
          {goalsMsg && <div className={goalsMsg.type==='ok'?'msg-ok':'msg-err'}>{goalsMsg.text}</div>}
          <button className="btn-primary" style={{ width:'100%' }} onClick={handleSaveGoals}>Guardar objetivos</button>
        </Section>
      </div>

      {/* Info */}
      <div style={{ fontSize:12, fontWeight:700, color:'#8E8E93', textTransform:'uppercase', letterSpacing:.5, marginBottom:8 }}>Aplicación</div>
      <div className="card">
        {[['🌐 Dominio','salud.rubenfer.es'],['📱 Versión','1.0.0'],['🗄 Backend','Node.js + SQLite']].map(([l,v],i,a)=>(
          <div key={l} className="list-row" style={{ borderBottom:i===a.length-1?'none':'1px solid #F2F2F7' }}>
            <div style={{ flex:1, fontSize:15 }}>{l}</div>
            <div style={{ fontSize:14, color:'#8E8E93' }}>{v}</div>
          </div>
        ))}
      </div>

      <div style={{ background:'#EFF6FF', borderRadius:14, padding:'16px', marginBottom:20, border:'1px solid #BFDBFE' }}>
        <div style={{ fontSize:15, fontWeight:600, color:'#1E40AF', marginBottom:6 }}>📲 Instalar como app</div>
        <div style={{ fontSize:13, color:'#1E3A8A', lineHeight:1.6 }}>
          En Safari iOS: Compartir → "Añadir a pantalla de inicio".<br/>
          Así funciona como app nativa con Face ID.
        </div>
      </div>

      <button style={{ width:'100%', padding:'15px', borderRadius:14, background:'#fff', color:'#FF3B30', fontWeight:700, fontSize:16, border:'1.5px solid #FFE0E0', cursor:'pointer' }}
        onClick={() => { api.clearToken(); onLogout(); }}>
        Cerrar sesión
      </button>
    </div>
  );
}

Object.assign(window, { ScreenSettings });
