// ── CONFIGURACIÓN — Perfil, metas y preferencias ────────────────
const ConfigScreen = () => {
  const [user, setUser] = React.useState(null);
  const [form, setForm] = React.useState({
    name:'', business_name:'', business_type:'', email:'', whatsapp:'', 
    country:'', currency:'USD', avatar_url:''
  });
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);

  const load = () => {
    setLoading(true);
    API.get('/me').then(r => {
      if (r) {
        setUser(r);
        setForm({
          name: r.name || '',
          business_name: r.business_name || '',
          business_type: r.business_type || '',
          email: r.email || '',
          whatsapp: r.whatsapp || '',
          country: r.country || '',
          currency: r.currency || 'USD',
          avatar_url: r.avatar_url || ''
        });
      }
      setLoading(false);
    });
  };

  React.useEffect(() => { load(); }, []);

  const save = async () => {
    setSaving(true);
    const res = await API.put('/me', form);
    setSaving(false);
    if (res.ok) {
      showToast('Perfil actualizado ✓');
      // Actualizar el objeto global window.USER para que el sidebar se actualice
      if (window.USER) {
        window.USER = { ...window.USER, ...form };
      }
    } else {
      showToast('Error al guardar', 'error');
    }
  };

  if (loading) return <div style={{ padding: 40, textAlign: 'center', color: EJ.muted }}>Cargando configuración...</div>;

  const inputStyle = {
    width: '100%', padding: '12px 16px', borderRadius: 16, border: `1.5px solid ${EJ.border}`,
    fontSize: 14, outline: 'none', background: '#fff', color: EJ.body, transition: 'border-color 0.2s'
  };

  return (
    <div style={{ padding: '28px 32px', background: EJ.bgApp, minHeight: '100%' }}>
      <SectionHeader title="Configuración" subtitle="Tu perfil, metas y preferencias del sistema" />

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 0.8fr', gap: 24, marginTop: 24 }}>
        
        {/* PANEL IZQUIERDO: PERFIL */}
        <Card style={{ padding: '24px 28px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 28 }}>
            <div style={{ position: 'relative' }}>
              <img src={form.avatar_url || 'Wuilldelys.jpg'} 
                style={{ width: 80, height: 80, borderRadius: '50%', objectFit: 'cover', border: `3px solid ${EJ.violet}22` }} />
              <button style={{ position: 'absolute', bottom: 0, right: 0, width: 28, height: 28, borderRadius: '50%', background: EJ.violet, color: '#fff', border: 'none', cursor: 'pointer', fontSize: 14 }}>✏️</button>
            </div>
            <div>
              <div style={{ fontSize: 20, fontWeight: 800, color: EJ.navy, fontFamily: 'Nunito, sans-serif' }}>{form.name || 'Usuaria'}</div>
              <div style={{ fontSize: 13, color: EJ.secondary }}>{form.email}</div>
              <div style={{ marginTop: 6 }}><Badge variant="violet">✦ Ejecutora Pro</Badge></div>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Nombre</label>
              <input style={inputStyle} value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Negocio / Marca</label>
              <input style={inputStyle} value={form.business_name} onChange={e => setForm(f => ({ ...f, business_name: e.target.value }))} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Email</label>
              <input style={{ ...inputStyle, background: '#f5f7fa', color: EJ.muted, cursor: 'not-allowed' }} value={form.email} disabled />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>WhatsApp</label>
              <input style={inputStyle} value={form.whatsapp} onChange={e => setForm(f => ({ ...f, whatsapp: e.target.value }))} />
            </div>
            <div style={{ gridColumn: '1 / -1' }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Sector de tu negocio</label>
              <select style={inputStyle} value={form.business_type} onChange={e => setForm(f => ({ ...f, business_type: e.target.value }))}>
                <option value="">Seleccionar sector</option>
                <option value="Coach negocios">Coach negocios</option>
                <option value="Coach bienestar">Coach bienestar</option>
                <option value="Diseñadora">Diseñadora</option>
                <option value="Infoproductora">Infoproductora</option>
                <option value="Pastelería">Pastelería</option>
                <option value="Entrenadora">Entrenadora</option>
                <option value="Fotógrafa">Fotógrafa</option>
                <option value="Otro">Otro</option>
              </select>
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>País</label>
              <input style={inputStyle} value={form.country} onChange={e => setForm(f => ({ ...f, country: e.target.value }))} placeholder="Venezuela" />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Moneda</label>
              <select style={inputStyle} value={form.currency} onChange={e => setForm(f => ({ ...f, currency: e.target.value }))}>
                <option value="USD">USD ($)</option>
                <option value="EUR">EUR (€)</option>
                <option value="MXN">MXN ($)</option>
                <option value="COP">COP ($)</option>
                <option value="ARS">ARS ($)</option>
                <option value="VES">VES (Bs.)</option>
              </select>
            </div>
          </div>

          <div style={{ marginTop: 32, display: 'flex', justifyContent: 'flex-end' }}>
            <Btn variant="primary" onClick={save} disabled={saving}>{saving ? 'Guardando...' : 'Guardar configuración'}</Btn>
          </div>
        </Card>

        {/* PANEL DERECHO: PLAN Y SUSCRIPCIÓN */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <Card style={{ padding: '24px 28px' }}>
            <div style={{ fontSize: 14, fontWeight: 800, color: EJ.navy, marginBottom: 20 }}>Plan actual</div>
            <div style={{ background: 'linear-gradient(135deg, #1A1F6E, #7B5CF5)', borderRadius: 18, padding: 24, color: '#fff' }}>
              <div style={{ fontSize: 12, opacity: 0.8, marginBottom: 8 }}>Plan activo</div>
              <div style={{ fontSize: 22, fontWeight: 800, marginBottom: 12 }}>✦ Ejecutora Pro</div>
              <div style={{ fontSize: 11, opacity: 0.7 }}>Acceso total · Templates · Mentoría · Software</div>
            </div>
            <div style={{ marginTop: 20, fontSize: 12, color: EJ.muted }}>Próxima facturación: 25 junio 2026</div>
            <div style={{ marginTop: 20 }}>
              <Btn variant="outline" style={{ width: '100%', borderColor: EJ.cyan, color: EJ.cyan }}>Gestionar suscripción</Btn>
            </div>
          </Card>

          <Card style={{ padding: '24px 28px' }}>
            <div style={{ fontSize: 14, fontWeight: 800, color: EJ.navy, marginBottom: 20 }}>Niveles de La Rutina que Vende™</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 18px', background: EJ.bgApp, borderRadius: 16 }}>
                <div>
                  <div style={{ fontWeight: 700, color: EJ.navy, fontSize: 13 }}>Esencial</div>
                  <div style={{ fontSize: 10, color: EJ.muted }}>5 módulos + 8 plantillas</div>
                </div>
                <div style={{ fontWeight: 800, color: EJ.navy }}>$97</div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 18px', background: `${EJ.violet}11`, border: `1.5px solid ${EJ.violet}`, borderRadius: 16 }}>
                <div>
                  <div style={{ fontWeight: 800, color: EJ.violet, fontSize: 13 }}>Pro IA ✦</div>
                  <div style={{ fontSize: 10, color: EJ.violet, opacity: 0.8 }}>Software + IA Copilot</div>
                </div>
                <div style={{ fontWeight: 800, color: EJ.violet }}>$197</div>
              </div>
            </div>
          </Card>
        </div>

      </div>
    </div>
  );
};

Object.assign(window, { ConfigScreen });
