// ── CONFIGURACIÓN — Perfil, metas y preferencias ────────────────
const ConfigScreen = () => {
  const [tab, setTab] = React.useState('perfil'); // perfil | metas | plan
  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 [avatarError, setAvatarError] = React.useState('');
  const [avatarPreview, setAvatarPreview] = React.useState('');
  const fileInputRef = React.useRef(null);

  const DEFAULT_AVATAR = '/sparkle-violeta.png';
  const MAX_FILE_MB = 2;
  const MAX_BYTES = MAX_FILE_MB * 1024 * 1024;

  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 || ''
        });
        setAvatarPreview(r.avatar_url || DEFAULT_AVATAR);
      }
      setLoading(false);
    });
  };

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

  const handleAvatarChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setAvatarError('');

    if (!file.type.startsWith('image/')) {
      setAvatarError('Solo se permiten imágenes (JPG, PNG, WebP).');
      return;
    }
    if (file.size > MAX_BYTES) {
      setAvatarError(`La imagen no puede superar ${MAX_FILE_MB}MB.`);
      return;
    }
    const reader = new FileReader();
    reader.onload = (ev) => {
      const dataUrl = ev.target.result;
      setAvatarPreview(dataUrl);
      setForm(f => ({ ...f, avatar_url: dataUrl }));
    };
    reader.readAsDataURL(file);
  };

  const save = async () => {
    setSaving(true);
    const res = await API.put('/me', form);
    setSaving(false);
    if (res.ok) {
      showToast('Perfil actualizado ✓');
      try {
        const stored = JSON.parse(localStorage.getItem('ej_user') || '{}');
        const updated = { ...stored, ...form };
        localStorage.setItem('ej_user', JSON.stringify(updated));
        // Force re-render of avatars globally
        window.dispatchEvent(new Event('storage'));
      } catch {}
    } else {
      showToast('Error al guardar', 'error');
    }
  };

  const repetirOnboarding = () => {
    if (!confirm('¿Quieres repetir el proceso de configuración inicial?')) return;
    try {
      const stored = JSON.parse(localStorage.getItem('ej_user') || '{}');
      localStorage.setItem('ej_user', JSON.stringify({ ...stored, onboarded: false }));
      window.location.reload();
    } catch {}
  };

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

  const inp = {
    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',
    fontFamily: 'Nunito Sans, sans-serif', boxSizing: 'border-box'
  };

  const isMobile = window.__isMobile;

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

      {/* TABS */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 24, flexWrap: 'wrap' }}>
        {[
          { id: 'perfil', label: '👤 Mi perfil' },
          { id: 'metas', label: '🎯 Metas' },
          { id: 'plan', label: '✦ Plan' }
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{
              padding: '10px 20px', borderRadius: 50, border: 'none', cursor: 'pointer',
              fontFamily: 'Nunito, sans-serif', fontWeight: 700, fontSize: 13,
              background: tab === t.id ? EJ.navy : '#fff',
              color: tab === t.id ? '#fff' : EJ.muted,
              boxShadow: tab === t.id ? '0 4px 12px rgba(26,31,110,0.2)' : '0 2px 8px rgba(0,0,0,0.05)',
              transition: 'all 0.2s'
            }}>
            {t.label}
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: tab==='perfil' && !isMobile ? '1fr 320px' : '1fr', gap: 24 }}>
        
        {/* VISTA PERFIL */}
        {tab === 'perfil' && (
          <>
            <Card style={{ padding: isMobile ? '20px' : '28px' }}>
              <div style={{ display: 'flex', flexDirection: isMobile?'column':'row', alignItems: isMobile?'center':'center', gap: 24, marginBottom: 32, textAlign: isMobile?'center':'left' }}>
                <div style={{ position: 'relative', flexShrink: 0 }}>
                  <img
                    src={avatarPreview || DEFAULT_AVATAR}
                    onError={e => { e.target.src = DEFAULT_AVATAR; }}
                    style={{ width: 100, height: 100, borderRadius: '50%', objectFit: 'cover', border: `4px solid #fff`, boxShadow: '0 4px 20px rgba(0,0,0,0.1)', display: 'block' }}
                    alt="Avatar"
                  />
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    style={{ position: 'absolute', bottom: 4, right: 4, width: 32, height: 32, borderRadius: '50%', background: EJ.violet, color: '#fff', border: '3px solid #fff', cursor: 'pointer', fontSize: 14, display:'flex', alignItems:'center', justifyContent:'center', boxShadow: '0 4px 8px rgba(0,0,0,0.2)' }}>
                    ✏️
                  </button>
                  <input ref={fileInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleAvatarChange} />
                </div>
                <div>
                  <div style={{ fontSize: 24, fontWeight: 800, color: EJ.navy, fontFamily: 'Nunito, sans-serif' }}>{form.name || 'Usuaria'}</div>
                  <div style={{ fontSize: 14, color: EJ.secondary }}>{form.email}</div>
                  <div style={{ marginTop: 8, display:'flex', justifyContent: isMobile?'center':'flex-start' }}>
                    <Badge variant="violet">✦ Admin</Badge>
                  </div>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 20 }}>
                <div>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Nombre completo</label>
                  <input style={inp} 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 }}>WhatsApp</label>
                  <input style={inp} value={form.whatsapp} onChange={e => setForm(f => ({ ...f, whatsapp: e.target.value }))} placeholder="+58 412 000 0000" />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Email</label>
                  <input style={{ ...inp, background: '#f5f7fa', color: EJ.muted }} value={form.email} disabled />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Sector de tu negocio</label>
                  <select style={{ ...inp, cursor: 'pointer', appearance: 'auto' }} value={form.business_type} onChange={e => setForm(f => ({ ...f, business_type: e.target.value }))}>
                    <option value="">Seleccionar sector</option>
                    {(window.SECTORES || []).map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>País</label>
                  <input style={inp} value={form.country} onChange={e => setForm(f => ({ ...f, country: e.target.value }))} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: EJ.navy, marginBottom: 8 }}>Moneda</label>
                  <select style={{ ...inp, cursor: 'pointer', appearance: 'auto' }} value={form.currency} onChange={e => setForm(f => ({ ...f, currency: e.target.value }))}>
                    <option value="USD">USD — Dólar</option>
                    <option value="EUR">EUR — Euro</option>
                    <option value="VES">VES — Bolívar</option>
                  </select>
                </div>
              </div>

              <div style={{ marginTop: 32, display: 'flex', flexDirection: isMobile?'column':'row', justifyContent: 'space-between', alignItems: 'center', gap:16 }}>
                <button onClick={repetirOnboarding} style={{ background:'none', border:'none', color:EJ.muted, fontSize:12, cursor:'pointer', textDecoration:'underline' }}>Repetir onboarding →</button>
                <Btn variant="primary" onClick={save} disabled={saving} style={{ width: isMobile?'100%':'auto' }}>{saving ? 'Guardando...' : 'Guardar perfil'}</Btn>
              </div>
            </Card>

            {!isMobile && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                 <Card style={{ textAlign: 'center', padding: 24 }}>
                    <div style={{ fontSize: 32, marginBottom: 12 }}>🚀</div>
                    <div style={{ fontWeight: 800, color: EJ.navy, marginBottom: 8 }}>Tu evolución</div>
                    <div style={{ fontSize: 12, color: EJ.secondary, marginBottom: 16 }}>Estás al 85% de completar tu configuración estratégica de este mes.</div>
                    <ProgressBar value={85} color={EJ.cyan} />
                 </Card>
              </div>
            )}
          </>
        )}

        {/* VISTA METAS */}
        {tab === 'metas' && (
          <Card>
            <div style={{ fontSize: 18, fontWeight: 800, color: EJ.navy, marginBottom: 20 }}>🎯 Definición de Metas Estratégicas</div>
            <p style={{ fontSize: 14, color: EJ.secondary, marginBottom: 24 }}>Estas metas se sincronizan con tu panel de **Ventas & KPIs** y tu **Planificación** mensual.</p>
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 24 }}>
               <div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 700, color: EJ.navy, marginBottom: 10 }}>Meta de Facturación Mensual ($)</label>
                  <input style={inp} type="number" placeholder="Ej: 5000" />
               </div>
               <div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 700, color: EJ.navy, marginBottom: 10 }}>Meta de Clientes Nuevos / mes</label>
                  <input style={inp} type="number" placeholder="Ej: 10" />
               </div>
            </div>
            <div style={{ marginTop: 32 }}>
               <Btn variant="primary" style={{ width: isMobile?'100%':'auto' }}>Guardar metas</Btn>
            </div>
          </Card>
        )}

        {/* VISTA PLAN */}
        {tab === 'plan' && (
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 24 }}>
            <Card style={{ border: `2px solid ${EJ.cyan}`, position: 'relative', overflow: 'hidden' }}>
              <div style={{ position: 'absolute', top: 12, right: 12 }}><Badge variant="cyan">ACTIVO</Badge></div>
              <div style={{ fontSize: 24, marginBottom: 12 }}>🕯️</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: EJ.navy, marginBottom: 8 }}>Plan Clarity</div>
              <div style={{ fontSize: 13, color: EJ.secondary, marginBottom: 20 }}>Fundamentos y orden para tu negocio.</div>
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: EJ.body, lineHeight: 1.6 }}>
                <li>Gestión de CRM & Ventas</li>
                <li>Planificación Mensual</li>
                <li>Rutina Diaria RQV</li>
              </ul>
            </Card>
            <Card style={{ opacity: 0.7, background: EJ.bgApp }}>
              <div style={{ fontSize: 24, marginBottom: 12 }}>🚀</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: EJ.navy, marginBottom: 8 }}>Plan Pro</div>
              <div style={{ fontSize: 13, color: EJ.secondary, marginBottom: 20 }}>Escalado con IA y mentoría personalizada.</div>
              <Btn variant="outline" style={{ width: '100%' }}>Mejorar plan ✦</Btn>
            </Card>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { ConfigScreen });
