const { useState: useSt, useEffect: useEff, useContext: useCtx, useRef } = React;


/* ── Upload helper ───────────────────────────────────────────────── */
const uploadToStorage = async (file, bucket, path) => {
  const { error } = await _supabase.storage.from(bucket).upload(path, file, {
    upsert: true,
    contentType: file.type,
  });
  if (error) { console.error('Upload error:', error); return null; }
  const { data: { publicUrl } } = _supabase.storage.from(bucket).getPublicUrl(path);
  return publicUrl;
};

/* ── AccountPage ─────────────────────────────────────────────────── */
const AccountPage = ({ onBack }) => {
  const { user, logout, openOnboarding, openMentorias, goToAdminOnboarding } = useCtx(UserCtx);
  const isAdmin = typeof ADMIN_EMAILS !== 'undefined'
    && Array.isArray(ADMIN_EMAILS) && user && ADMIN_EMAILS.includes(user.email);
  const { theme, toggleTheme } = useCtx(ThemeCtx);
  const isMob = typeof useIsMobile === 'function' ? useIsMobile() : false;
  const [tab, setTab] = useSt('perfil');
  const [saving, setSaving] = useSt(false);
  const [uploading, setUploading] = useSt(''); // 'avatar' | 'cover' | ''
  const [feedback, setFeedback] = useSt(null);

  /* Pré-visualização antes de confirmar troca de foto */
  const [pendingFile, setPendingFile] = useSt(null);
  const [pendingKind, setPendingKind] = useSt(''); // 'avatar' | 'cover'
  const [pendingPreview, setPendingPreview] = useSt('');

  /* ── Perfil ── */
  const [firstName,  setFirstName]  = useSt('');
  const [lastName,   setLastName]   = useSt('');
  const [phone,      setPhone]      = useSt('');
  const [occupation, setOccupation] = useSt('');
  const [timezone,   setTimezone]   = useSt('America/Sao_Paulo');
  const [bio,        setBio]        = useSt('');
  const [avatarUrl,  setAvatarUrl]  = useSt('');
  const [coverUrl,   setCoverUrl]   = useSt('');

  /* ── Senha ── */
  const [newPass,     setNewPass]     = useSt('');
  const [confirmPass, setConfirmPass] = useSt('');
  const [passError,   setPassError]   = useSt('');

  /* ── Social ── */
  const [instagram, setInstagram] = useSt('');
  const [whatsapp,  setWhatsapp]  = useSt('');

  const avatarInputRef = useRef(null);
  const coverInputRef  = useRef(null);

  /* Carrega metadados do Supabase */
  useEff(() => {
    _supabase.auth.getUser().then(({ data: { user: sb } }) => {
      if (!sb) return;
      const m = sb.user_metadata || {};
      const parts = (m.name || '').trim().split(' ');
      setFirstName(parts[0] || '');
      setLastName(parts.slice(1).join(' ') || '');
      setPhone(m.phone || '');
      setOccupation(m.occupation || '');
      setTimezone(m.timezone || 'America/Sao_Paulo');
      setBio(m.bio || '');
      setInstagram(m.instagram || '');
      setWhatsapp(m.whatsapp || '');
      setAvatarUrl(m.avatar_url || '');
      setCoverUrl(m.cover_url || '');
    });
  }, []);

  const flash = (msg, ok = true) => {
    setFeedback({ msg, ok });
    setTimeout(() => setFeedback(null), 3500);
  };

  /* ── Seleção: agora só preview, upload só após confirmar ── */
  const handlePickFile = (kind) => (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    /* Cria preview local com FileReader */
    const reader = new FileReader();
    reader.onload = () => {
      setPendingFile(file);
      setPendingKind(kind);
      setPendingPreview(reader.result);
    };
    reader.readAsDataURL(file);
    e.target.value = ''; // permite re-selecionar o mesmo arquivo depois
  };

  const cancelPendingPhoto = () => {
    setPendingFile(null);
    setPendingKind('');
    setPendingPreview('');
  };

  const confirmPendingPhoto = async () => {
    if (!pendingFile || !pendingKind || !user?.id) return;
    setUploading(pendingKind);
    const ext = pendingFile.name.split('.').pop();
    const bucket = pendingKind === 'avatar' ? 'avatars' : 'covers';
    const path   = `${user.id}/${pendingKind}.${ext}`;
    const url    = await uploadToStorage(pendingFile, bucket, path);
    if (url) {
      if (pendingKind === 'avatar') setAvatarUrl(url);
      else setCoverUrl(url);
      const metaKey = pendingKind === 'avatar' ? 'avatar_url' : 'cover_url';
      await _supabase.auth.updateUser({ data: { [metaKey]: url } });
      await _supabase.from('profiles').upsert({ id: user.id, [metaKey]: url }, { onConflict: 'id' });
      flash(pendingKind === 'avatar' ? 'Foto de perfil atualizada!' : 'Foto de capa atualizada!');
    } else {
      flash('Erro ao enviar foto.', false);
    }
    setUploading('');
    cancelPendingPhoto();
  };

  const saveProfile = async (extra = {}) => {
    if (!user?.id) return;
    setSaving(true);
    const fullName = [firstName.trim(), lastName.trim()].filter(Boolean).join(' ');

    /* Normaliza: tira @ do Instagram e tudo que não for dígito do WhatsApp */
    const cleanInsta = (instagram || '').trim().replace(/^@+/, '');
    const cleanWpp   = (whatsapp || '').replace(/\D/g, '');

    /* Salva na tabela pública (rápido) */
    const { error } = await _supabase.from('profiles').upsert({
      id:         user.id,
      name:       fullName,
      bio,
      occupation,
      instagram:  cleanInsta,
      whatsapp:   cleanWpp,
      avatar_url: avatarUrl,
      cover_url:  coverUrl,
      updated_at: new Date().toISOString(),
      ...extra,
    }, { onConflict: 'id' });

    /* Atualiza metadados de auth em background (não bloqueia) */
    _supabase.auth.updateUser({
      data: { name: fullName, phone, occupation, timezone, bio, instagram: cleanInsta, whatsapp: cleanWpp },
    }).then(() => {});

    setSaving(false);
    if (error) console.error('Erro profiles upsert:', error);
    flash(error ? `Erro: ${error.message}` : 'Perfil atualizado!', !error);
  };

  const savePassword = async () => {
    setPassError('');
    if (newPass.length < 6) return setPassError('Mínimo de 6 caracteres.');
    if (newPass !== confirmPass) return setPassError('As senhas não coincidem.');
    setSaving(true);
    const { error } = await _supabase.auth.updateUser({ password: newPass });
    setSaving(false);
    if (error) setPassError('Erro ao atualizar senha.');
    else { setNewPass(''); setConfirmPass(''); flash('Senha atualizada!'); }
  };

  const initials  = getInitials(user?.name || user?.email || '?');
  const timezones = [
    { v: 'America/Sao_Paulo',   l: 'São Paulo (GMT-3)' },
    { v: 'America/Fortaleza',   l: 'Fortaleza (GMT-3)' },
    { v: 'America/Recife',      l: 'Recife (GMT-3)' },
    { v: 'America/Belem',       l: 'Belém (GMT-3)' },
    { v: 'America/Manaus',      l: 'Manaus (GMT-4)' },
    { v: 'America/Porto_Velho', l: 'Porto Velho (GMT-4)' },
    { v: 'America/Rio_Branco',  l: 'Rio Branco (GMT-5)' },
    { v: 'America/Noronha',     l: 'Fernando de Noronha (GMT-2)' },
  ];

  const inp = {
    width: '100%', boxSizing: 'border-box',
    background: 'var(--card)', border: '1px solid var(--border)',
    borderRadius: 8, padding: '10px 14px', fontSize: 13.5,
    color: 'var(--text)', fontFamily: 'inherit', outline: 'none',
    transition: 'border-color 0.15s',
  };
  const lbl = { fontSize: 12, fontWeight: 500, color: 'var(--text2)', marginBottom: 6, display: 'block' };

  const SaveBtn = ({ onClick }) => (
    <button onClick={() => onClick()} disabled={saving} style={{
      background: 'var(--gold)', color: '#0A0A0A', borderRadius: 8,
      padding: '10px 26px', fontSize: 13.5, fontWeight: 700,
      opacity: saving ? 0.55 : 1, transition: 'opacity 0.15s',
    }}>
      {saving ? 'Salvando…' : 'Salvar'}
    </button>
  );

  return (
    <div style={{
      minHeight: '100vh', background: 'var(--bg)', color: 'var(--text)',
      paddingBottom: isMob ? 90 : 0,
    }}>

      {/* ── TOP BAR ── */}
      <div style={{
        height: isMob ? 'auto' : 52, flexShrink: 0,
        background: isMob ? 'transparent' : 'var(--nav-bg)',
        backdropFilter: isMob ? 'none' : 'blur(18px)',
        borderBottom: isMob ? 'none' : '1px solid var(--border)',
        display: 'flex', alignItems: 'center',
        padding: isMob ? 'calc(env(safe-area-inset-top, 0px) + 12px) 16px 6px' : '0 20px',
        gap: 10,
      }}>
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', gap: 6,
          background: 'none', color: 'var(--text2)',
          padding: '6px 10px', borderRadius: 7, fontSize: 13,
        }}>
          <IconArrowLeft size={14}/> Voltar
        </button>
        <div style={{ flex: 1 }}/>
        {/* No mobile, theme/bell vêm do AppShell flutuante */}
        {!isMob && (
          <>
            <button onClick={toggleTheme} style={{
              width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: 'var(--gold-bg)', border: '1px solid var(--border)', color: 'var(--gold)',
            }}>
              {theme === 'dark' ? <IconSun size={15}/> : <IconMoon size={15}/>}
            </button>
            <NotificationBell/>
            <UserMenu size={32}/>
          </>
        )}
      </div>

      <div style={{
        maxWidth: 800, margin: '0 auto',
        padding: isMob ? '20px 16px' : '36px 24px',
      }}>
        <h1 style={{
          fontSize: isMob ? 20 : 22, fontWeight: 600, color: 'var(--text)',
          marginBottom: isMob ? 16 : 20,
        }}>
          Configurações
        </h1>

        {/* ── Itens pendentes (questionário + mentorias) — só se houver acesso ao curso ── */}
        {user?.course_access === true && (() => {
          const onbDone = user?.onboarding_completed === true;
          const m1 = user?.mentorias?.mentoria_1;
          const m2 = user?.mentorias?.mentoria_2;
          const m1Done = !!m1?.scheduled_at;
          const m2Done = !!m2?.scheduled_at;
          /* Não mostra a seção se tudo está completo */
          if (onbDone && m1Done && m2Done) return null;

          const fmtBR = (iso) => new Date(iso).toLocaleString('pt-BR',
            { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' });

          const Row = ({ label, done, doneText, action, onClick, disabled }) => (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '12px 14px',
              borderBottom: '1px solid var(--border)',
              opacity: disabled ? 0.55 : 1,
            }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
                background: done ? 'var(--gold)' : 'var(--card)',
                border: `1.5px solid ${done ? 'var(--gold)' : 'var(--border-h)'}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {done && <IconCheck size={11} color="#0A0A0A"/>}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--text)', marginBottom: 2 }}>
                  {label}
                </p>
                <p style={{ fontSize: 12, color: 'var(--text2)' }}>
                  {done ? doneText : (disabled ? 'Desbloqueia depois da mentoria 1' : 'Pendente')}
                </p>
              </div>
              {!done && !disabled && (
                <button onClick={onClick} style={{
                  background: 'var(--gold)', color: '#0A0A0A',
                  padding: '7px 14px', borderRadius: 7,
                  fontSize: 12, fontWeight: 700, letterSpacing: '0.02em',
                  fontFamily: 'inherit',
                }}>
                  {action} →
                </button>
              )}
            </div>
          );

          return (
            <div style={{
              background: 'var(--card)', border: '1px solid var(--border-h)',
              borderRadius: 12, marginBottom: 24, overflow: 'hidden',
            }}>
              <div style={{
                padding: '12px 14px', background: 'var(--gold-bg)',
                borderBottom: '1px solid var(--border)',
              }}>
                <p style={{ fontSize: 11, fontWeight: 700, color: 'var(--gold)',
                  letterSpacing: '0.14em', textTransform: 'uppercase' }}>
                  Itens pendentes
                </p>
              </div>
              <Row
                label="Questionário inicial"
                done={onbDone}
                doneText="Respondido"
                action="Responder"
                onClick={() => { if (typeof openOnboarding === 'function') openOnboarding(); }}
              />
              <Row
                label="Mentoria 1"
                done={m1Done}
                doneText={m1Done ? `Marcada para ${fmtBR(m1.scheduled_at)}` : ''}
                action="Marcar"
                onClick={() => { if (typeof openMentorias === 'function') openMentorias(); }}
              />
              <Row
                label="Mentoria 2"
                done={m2Done}
                doneText={m2Done ? `Marcada para ${fmtBR(m2.scheduled_at)}` : ''}
                action="Marcar"
                disabled={!m1Done}
                onClick={() => { if (typeof openMentorias === 'function') openMentorias(); }}
              />
            </div>
          );
        })()}

        {/* ── TABS (scrollable no mobile) ── */}
        <div style={{
          display: 'flex',
          borderBottom: '1px solid var(--border)',
          marginBottom: isMob ? 22 : 32,
          overflowX: isMob ? 'auto' : 'visible',
          scrollbarWidth: 'none',
        }}>
          {(() => {
            /* Mentorias: só pra alunas com acesso ao curso, e SÓ no desktop.
               Respostas do onboarding: só admin, SÓ no desktop. */
            const baseTabs = [
              { id: 'perfil', label: 'Perfil' },
              { id: 'senha',  label: 'Senha' },
              { id: 'social', label: 'Perfil Social' },
            ];
            const extraTabs = [];
            if (isMob && user?.course_access === true) {
              extraTabs.push({ id: '__mentorias', label: 'Mentorias', action: openMentorias });
            }
            if (isMob && isAdmin) {
              extraTabs.push({ id: '__admin_onb', label: 'Respostas do onboarding', action: goToAdminOnboarding });
            }
            return [...baseTabs, ...extraTabs].map(({ id, label, action }) => (
              <button
                key={id}
                onClick={() => action ? action() : setTab(id)}
                style={{
                  padding: isMob ? '10px 16px' : '10px 22px',
                  fontSize: 13, background: 'none', whiteSpace: 'nowrap',
                  fontWeight: tab === id ? 600 : 400,
                  color: tab === id ? 'var(--gold)' : 'var(--text3)',
                  borderBottom: `2px solid ${tab === id ? 'var(--gold)' : 'transparent'}`,
                  marginBottom: -1, transition: 'all 0.15s',
                }}
              >
                {label}
              </button>
            ));
          })()}
        </div>

        {/* ── FEEDBACK ── */}
        {feedback && (
          <div style={{
            background: feedback.ok ? 'var(--gold-bg)' : 'rgba(220,50,50,0.08)',
            border: `1px solid ${feedback.ok ? 'var(--gold)' : 'rgba(220,50,50,0.35)'}`,
            borderRadius: 8, padding: '10px 16px', marginBottom: 24,
            fontSize: 13, color: feedback.ok ? 'var(--gold)' : '#e05555',
          }}>
            {feedback.msg}
          </div>
        )}

        {/* ══════════════ TAB: PERFIL ══════════════ */}
        {tab === 'perfil' && (
          <div>
            {/* Inputs de arquivo ocultos */}
            <input ref={avatarInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handlePickFile('avatar')}/>
            <input ref={coverInputRef}  type="file" accept="image/*" style={{ display: 'none' }} onChange={handlePickFile('cover')}/>

            {/* Banner + avatar */}
            <div style={{ marginBottom: 48, position: 'relative' }}>

              {/* ── CAPA ── */}
              <div
                onClick={() => coverInputRef.current?.click()}
                style={{
                  height: 160, borderRadius: 14, overflow: 'hidden',
                  position: 'relative', cursor: 'pointer',
                  background: coverUrl
                    ? 'var(--bg)'
                    : 'linear-gradient(135deg, #1c1400 0%, #2d2000 25%, #0d1520 65%, #0a0a0a 100%)',
                }}
              >
                {/* Imagem de capa */}
                {coverUrl && (
                  <img src={coverUrl} alt="Capa"
                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                )}

                {/* Decoração se sem capa */}
                {!coverUrl && (
                  <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.18 }}
                    viewBox="0 0 800 160" preserveAspectRatio="xMidYMid slice">
                    <circle cx="180" cy="80"  r="110" fill="none" stroke="var(--gold)" strokeWidth="1"/>
                    <circle cx="180" cy="80"  r="160" fill="none" stroke="var(--gold)" strokeWidth="0.5"/>
                    <circle cx="620" cy="80"  r="90"  fill="none" stroke="var(--gold)" strokeWidth="1"/>
                    <circle cx="620" cy="80"  r="135" fill="none" stroke="var(--gold)" strokeWidth="0.4"/>
                  </svg>
                )}

                {/* Overlay com ícone de câmera */}
                <div style={{
                  position: 'absolute', inset: 0,
                  background: 'rgba(0,0,0,0)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'background 0.2s',
                }}
                  onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,0,0,0.45)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'rgba(0,0,0,0)'}
                >
                  <div style={{
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                    opacity: 0, transition: 'opacity 0.2s', pointerEvents: 'none',
                  }}
                    ref={el => {
                      if (!el) return;
                      el.parentElement.addEventListener('mouseenter', () => el.style.opacity = 1);
                      el.parentElement.addEventListener('mouseleave', () => el.style.opacity = 0);
                    }}
                  >
                    <div style={{
                      width: 40, height: 40, borderRadius: '50%',
                      background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(6px)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      {uploading === 'cover'
                        ? <span style={{ fontSize: 18 }}>⏳</span>
                        : <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                            <circle cx="12" cy="13" r="4"/>
                          </svg>
                      }
                    </div>
                    <span style={{ fontSize: 12, color: 'white', fontWeight: 500 }}>
                      {uploading === 'cover' ? 'Enviando…' : 'Alterar foto de capa'}
                    </span>
                  </div>
                </div>
              </div>

              {/* ── AVATAR ── */}
              <div
                onClick={() => avatarInputRef.current?.click()}
                style={{
                  position: 'absolute', bottom: -36, left: 28,
                  width: 80, height: 80, borderRadius: '50%', cursor: 'pointer',
                  border: '3px solid var(--bg)',
                  boxShadow: '0 4px 16px rgba(0,0,0,0.45)',
                  overflow: 'hidden', flexShrink: 0,
                  background: avatarUrl ? '#000' : 'var(--gold)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}
              >
                {avatarUrl
                  ? <img src={avatarUrl} alt="Avatar"
                      style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                  : <span style={{ fontSize: 26, fontWeight: 700, color: '#0A0A0A' }}>{initials}</span>
                }

                {/* Overlay câmera */}
                <div style={{
                  position: 'absolute', inset: 0, borderRadius: '50%',
                  background: 'rgba(0,0,0,0)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'background 0.2s',
                }}
                  onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,0,0,0.55)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'rgba(0,0,0,0)'}
                >
                  <div style={{
                    opacity: 0, transition: 'opacity 0.2s', pointerEvents: 'none',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
                  }}
                    ref={el => {
                      if (!el) return;
                      el.parentElement.addEventListener('mouseenter', () => el.style.opacity = 1);
                      el.parentElement.addEventListener('mouseleave', () => el.style.opacity = 0);
                    }}
                  >
                    {uploading === 'avatar'
                      ? <span style={{ fontSize: 16 }}>⏳</span>
                      : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                          <circle cx="12" cy="13" r="4"/>
                        </svg>
                    }
                  </div>
                </div>
              </div>

              {/* Labels de dica */}
              <div style={{
                position: 'absolute', bottom: -30, right: 0,
                display: 'flex', gap: 16,
              }}>
                <span style={{ fontSize: 10, color: 'var(--text3)' }}>Clique no avatar ou na capa para alterar</span>
              </div>
            </div>

            {/* Formulário */}
            <div style={{ paddingTop: 24 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                <div>
                  <label style={lbl}>Nome</label>
                  <input value={firstName} onChange={e => setFirstName(e.target.value)}
                    style={inp} placeholder="Seu nome"
                    onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                    onBlur={e => e.target.style.borderColor = 'var(--border)'}/>
                </div>
                <div>
                  <label style={lbl}>Sobrenome</label>
                  <input value={lastName} onChange={e => setLastName(e.target.value)}
                    style={inp} placeholder="Seu sobrenome"
                    onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                    onBlur={e => e.target.style.borderColor = 'var(--border)'}/>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                <div>
                  <label style={lbl}>E-mail</label>
                  <input value={user?.email || ''} disabled
                    style={{ ...inp, opacity: 0.45, cursor: 'not-allowed' }}/>
                </div>
                <div>
                  <label style={lbl}>Telefone</label>
                  <input value={phone} onChange={e => setPhone(e.target.value)}
                    style={inp} placeholder="(00) 00000-0000"
                    onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                    onBlur={e => e.target.style.borderColor = 'var(--border)'}/>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                <div>
                  <label style={lbl}>Ocupação</label>
                  <input value={occupation} onChange={e => setOccupation(e.target.value)}
                    style={inp} placeholder="Ex: Psicóloga Clínica"
                    onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                    onBlur={e => e.target.style.borderColor = 'var(--border)'}/>
                </div>
                <div>
                  <label style={lbl}>Fuso horário</label>
                  <select value={timezone} onChange={e => setTimezone(e.target.value)}
                    style={{ ...inp, cursor: 'pointer' }}>
                    {timezones.map(({ v, l }) => <option key={v} value={v}>{l}</option>)}
                  </select>
                </div>
              </div>

              <div style={{ marginBottom: 28 }}>
                <label style={lbl}>Bio</label>
                <textarea value={bio} onChange={e => setBio(e.target.value)}
                  placeholder="Conte um pouco sobre você…" rows={4}
                  style={{ ...inp, resize: 'vertical' }}
                  onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                  onBlur={e => e.target.style.borderColor = 'var(--border)'}/>
              </div>

              <SaveBtn onClick={saveProfile}/>
            </div>
          </div>
        )}

        {/* ══════════════ TAB: SENHA ══════════════ */}
        {tab === 'senha' && (
          <div style={{ maxWidth: 400 }}>
            <p style={{ fontSize: 13.5, color: 'var(--text2)', marginBottom: 24, lineHeight: 1.65 }}>
              Escolha uma nova senha com pelo menos 6 caracteres.
            </p>
            <div style={{ marginBottom: 16 }}>
              <label style={lbl}>Nova senha</label>
              <input type="password" value={newPass} onChange={e => setNewPass(e.target.value)}
                style={inp} placeholder="••••••••"
                onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                onBlur={e => e.target.style.borderColor = 'var(--border)'}/>
            </div>
            <div style={{ marginBottom: 24 }}>
              <label style={lbl}>Confirmar nova senha</label>
              <input type="password" value={confirmPass} onChange={e => setConfirmPass(e.target.value)}
                style={inp} placeholder="••••••••"
                onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                onBlur={e => e.target.style.borderColor = 'var(--border)'}/>
            </div>
            {passError && <p style={{ fontSize: 12.5, color: '#e05555', marginBottom: 16 }}>{passError}</p>}
            <SaveBtn onClick={savePassword}/>
          </div>
        )}

        {/* ══════════════ TAB: SOCIAL ══════════════ */}
        {tab === 'social' && (
          <div style={{ maxWidth: 480 }}>
            <p style={{ fontSize: 13.5, color: 'var(--text2)', marginBottom: 24, lineHeight: 1.65 }}>
              Adicione seus perfis para que outros alunos possam te encontrar.
              Os links são gerados automaticamente no seu perfil público.
            </p>

            {/* Instagram */}
            <div style={{ marginBottom: 16 }}>
              <label style={lbl}>Instagram profissional</label>
              <div style={{ position: 'relative' }}>
                <span style={{
                  position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
                  color: 'var(--text3)', fontSize: 14, pointerEvents: 'none',
                }}>@</span>
                <input
                  value={instagram.replace(/^@+/, '')}
                  onChange={e => setInstagram(e.target.value.replace(/^@+/, ''))}
                  style={{ ...inp, paddingLeft: 28 }}
                  placeholder="seuperfil"
                  onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                  onBlur={e => e.target.style.borderColor = 'var(--border)'}
                />
              </div>
            </div>

            {/* WhatsApp */}
            <div style={{ marginBottom: 16 }}>
              <label style={lbl}>WhatsApp profissional</label>
              <input
                value={whatsapp}
                onChange={e => setWhatsapp(e.target.value)}
                style={inp}
                placeholder="(11) 99999-9999"
                inputMode="tel"
                onFocus={e => e.target.style.borderColor = 'var(--border-h)'}
                onBlur={e => e.target.style.borderColor = 'var(--border)'}
              />
              <p style={{ fontSize: 11, color: 'var(--text3)', marginTop: 5 }}>
                Digite com DDD. O código do país (+55) é adicionado automaticamente.
              </p>
            </div>

            <div style={{ marginTop: 8 }}>
              <SaveBtn onClick={saveProfile}/>
            </div>
          </div>
        )}

        {/* ── Sair da conta — só no mobile (no desktop sai pelo menu do avatar) ── */}
        {isMob && (
          <div style={{
            marginTop: 40, paddingTop: 24,
            borderTop: '1px solid var(--border)',
            display: 'flex', justifyContent: 'center',
          }}>
            <button
              onClick={() => {
                if (confirm('Tem certeza que deseja sair?')) {
                  logout();
                }
              }}
              style={{
                display: 'flex', alignItems: 'center', gap: 9,
                background: 'rgba(220,80,80,0.06)',
                border: '1px solid rgba(220,80,80,0.3)',
                borderRadius: 10, padding: '12px 22px',
                fontSize: 13.5, fontWeight: 600, color: '#E07070',
              }}
            >
              <IconLogout size={15}/> Sair da conta
            </button>
          </div>
        )}
      </div>

      {/* ── Modal de confirmação de troca de foto (avatar/capa) ── */}
      {pendingPreview && (
        <div
          onClick={cancelPendingPhoto}
          style={{
            position: 'fixed', inset: 0, zIndex: 1000,
            background: 'rgba(0,0,0,0.72)', backdropFilter: 'blur(6px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 16,
          }}
        >
          <div
            onClick={e => e.stopPropagation()}
            style={{
              width: '100%', maxWidth: 420,
              background: 'var(--card)', border: '1px solid var(--border-h)',
              borderRadius: 14, overflow: 'hidden',
              display: 'flex', flexDirection: 'column',
            }}
          >
            <div style={{ padding: '20px 22px 0' }}>
              <p style={{
                fontSize: 11, fontWeight: 700, color: 'var(--gold)',
                letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 6,
              }}>
                Confirmar troca de foto
              </p>
              <h3 style={{ fontSize: 17, fontWeight: 700, color: 'var(--text)', marginBottom: 6 }}>
                {pendingKind === 'avatar' ? 'Nova foto de perfil' : 'Nova foto de capa'}
              </h3>
              <p style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 16, lineHeight: 1.5 }}>
                A imagem abaixo vai substituir sua {pendingKind === 'avatar' ? 'foto de perfil' : 'capa'} atual.
                Tem certeza?
              </p>
            </div>

            {/* Preview */}
            <div style={{
              padding: '0 22px 18px',
              display: 'flex', justifyContent: 'center',
            }}>
              {pendingKind === 'avatar' ? (
                <img
                  src={pendingPreview} alt="Preview"
                  style={{
                    width: 120, height: 120, borderRadius: '50%',
                    objectFit: 'cover',
                    border: '3px solid var(--border-h)',
                  }}
                />
              ) : (
                <img
                  src={pendingPreview} alt="Preview"
                  style={{
                    width: '100%', height: 140, borderRadius: 10,
                    objectFit: 'cover',
                    border: '1px solid var(--border-h)',
                  }}
                />
              )}
            </div>

            {/* Ações */}
            <div style={{
              display: 'flex', gap: 10,
              padding: '14px 22px 20px',
              borderTop: '1px solid var(--border)',
            }}>
              <button
                onClick={cancelPendingPhoto}
                disabled={!!uploading}
                style={{
                  flex: 1, padding: '11px 18px', borderRadius: 9,
                  background: 'var(--bg2)', border: '1px solid var(--border)',
                  color: 'var(--text2)', fontSize: 13, fontWeight: 600,
                  fontFamily: 'inherit', cursor: 'pointer',
                }}
              >
                Cancelar
              </button>
              <button
                onClick={confirmPendingPhoto}
                disabled={!!uploading}
                style={{
                  flex: 1, padding: '11px 18px', borderRadius: 9,
                  background: 'var(--gold)', color: '#0A0A0A',
                  fontSize: 13, fontWeight: 700, letterSpacing: '0.02em',
                  fontFamily: 'inherit',
                  opacity: uploading ? 0.6 : 1,
                  cursor: uploading ? 'wait' : 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
                }}
              >
                {uploading ? (
                  <>
                    <span style={{
                      width: 12, height: 12, borderRadius: '50%',
                      border: '2px solid rgba(10,10,10,0.25)', borderTopColor: '#0A0A0A',
                      animation: 'ac-spin 0.7s linear infinite',
                    }}/>
                    Enviando…
                  </>
                ) : 'Confirmar'}
              </button>
            </div>
            <style>{`@keyframes ac-spin { to { transform: rotate(360deg); } }`}</style>
          </div>
        </div>
      )}
    </div>
  );
};

window.AccountPage = AccountPage;
