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

const ProfileView = ({ userId, onBack }) => {
  const { theme, toggleTheme } = useCtx(ThemeCtx);
  const isMob = typeof useIsMobile === 'function' ? useIsMobile() : false;
  const [profile, setProfile] = useSt(null);
  const [loading, setLoading] = useSt(true);

  useEff(() => {
    setLoading(true);
    /* RPC controlada — retorna só colunas públicas, requer autenticação.
       Substitui a view profiles_public (que a Supabase flagou por
       rodar com SECURITY DEFINER e bypassar RLS). */
    _supabase.rpc('get_public_profile', { profile_id: userId })
      .then(({ data }) => { setProfile(data || null); setLoading(false); });
  }, [userId]);

  const name       = profile?.name || 'Aluno';
  const initials   = getInitials(name);
  const completed  = profile?.completed_count || 0;
  const pct        = Math.round((completed / COURSE.totalLessons) * 100);
  const hasAvatar  = !!profile?.avatar_url;
  const hasCover   = !!profile?.cover_url;

  /* Gera links automaticamente a partir do @ do Insta e do número do WhatsApp */
  const igUser = (profile?.instagram || '').replace(/^@+/, '').trim();
  const wppRaw = (profile?.whatsapp || '').replace(/\D/g, '');
  const wppFull = wppRaw ? (wppRaw.startsWith('55') ? wppRaw : `55${wppRaw}`) : '';

  const socialLinks = [
    igUser  && { label: 'Instagram', display: `@${igUser}`, url: `https://instagram.com/${igUser}` },
    wppFull && { label: 'WhatsApp',  display: 'Enviar mensagem', url: `https://wa.me/${wppFull}` },
  ].filter(Boolean);

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

      {/* ── TOP BAR ── */}
      <div style={{
        height: isMob ? 'auto' : 52,
        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,
        position: isMob ? 'absolute' : 'relative',
        top: 0, left: 0, right: 0, zIndex: 50,
      }}>
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', gap: 6,
          background: isMob ? 'rgba(0,0,0,0.55)' : 'none',
          color: isMob ? '#fff' : 'var(--text2)',
          padding: isMob ? '7px 12px' : '6px 10px',
          borderRadius: isMob ? 20 : 7,
          backdropFilter: isMob ? 'blur(6px)' : 'none',
          fontSize: 13,
        }}>
          <IconArrowLeft size={14}/> Voltar
        </button>
        <div style={{ flex: 1 }}/>
        {!isMob && (
          <>
            <button onClick={toggleTheme} style={{
              width: 32, height: 32, borderRadius: '50%',
              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>

      {loading ? (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '60vh' }}>
          <p style={{ color: 'var(--text3)', fontSize: 13 }}>Carregando perfil…</p>
        </div>
      ) : (
        <div style={{ maxWidth: 680, margin: '0 auto', padding: '0 0 60px' }}>

          {/* ── CAPA ── */}
          <div style={{
            height: 220, position: 'relative', overflow: 'hidden',
            background: hasCover
              ? '#000'
              : 'linear-gradient(135deg, #1c1400 0%, #2d2000 30%, #0d1520 70%, #0a0a0a 100%)',
          }}>
            {hasCover && (
              <img src={profile.cover_url} alt="Capa"
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
            )}
            {!hasCover && (
              <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.15 }}
                viewBox="0 0 680 220" preserveAspectRatio="xMidYMid slice">
                <circle cx="160" cy="110" r="120" fill="none" stroke="var(--gold)" strokeWidth="1"/>
                <circle cx="160" cy="110" r="175" fill="none" stroke="var(--gold)" strokeWidth="0.5"/>
                <circle cx="520" cy="110" r="95"  fill="none" stroke="var(--gold)" strokeWidth="1"/>
              </svg>
            )}
          </div>

          {/* ── AVATAR + NOME ── */}
          <div style={{ padding: '0 28px' }}>
            <div style={{ marginTop: -44, marginBottom: 16, position: 'relative', zIndex: 1 }}>
              <div style={{
                width: 88, height: 88, borderRadius: '50%',
                border: '4px solid var(--bg)',
                background: hasAvatar ? '#000' : 'var(--gold)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 28, fontWeight: 700, color: '#0A0A0A',
                overflow: 'hidden',
                boxShadow: '0 4px 20px rgba(0,0,0,0.4)',
              }}>
                {hasAvatar
                  ? <img src={profile.avatar_url} alt={name}
                      style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                  : initials
                }
              </div>
            </div>

            {/* Nome e ocupação */}
            <h1 style={{ fontSize: 22, fontWeight: 700, color: 'var(--text)', marginBottom: 4 }}>
              {name}
            </h1>
            {profile?.occupation && (
              <p style={{ fontSize: 13.5, color: 'var(--gold)', marginBottom: 20, fontWeight: 500 }}>
                {profile.occupation}
              </p>
            )}

            {/* ── BIO ── */}
            {profile?.bio && (
              <p style={{
                fontSize: 14, color: 'var(--text2)', lineHeight: 1.75,
                marginBottom: 28,
                padding: '16px 20px',
                background: 'var(--card)', border: '1px solid var(--border)',
                borderRadius: 10,
              }}>
                {profile.bio}
              </p>
            )}

            {/* ── PROGRESSO ── */}
            <div style={{
              background: 'var(--card)', border: '1px solid var(--border)',
              borderRadius: 10, padding: '16px 20px', marginBottom: 24,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <p style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text3)' }}>
                  Progresso no curso
                </p>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--gold)' }}>
                  {completed}/{COURSE.totalLessons} aulas · {pct}%
                </span>
              </div>
              <div style={{
                width: '100%', height: 6, background: 'var(--border)',
                borderRadius: 99, overflow: 'hidden',
              }}>
                <div style={{
                  height: '100%', width: `${pct}%`,
                  background: 'var(--gold)', borderRadius: 99,
                  transition: 'width 0.4s ease',
                }}/>
              </div>
            </div>

            {/* ── REDES SOCIAIS ── */}
            {socialLinks.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                {socialLinks.map(({ label, display, url }) => (
                  <a key={label} href={url} target="_blank" rel="noopener noreferrer" style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    background: 'var(--card)', border: '1px solid var(--border)',
                    borderRadius: 8, padding: '8px 16px',
                    fontSize: 13, fontWeight: 500, color: 'var(--text2)',
                    textDecoration: 'none', transition: 'border-color 0.15s, color 0.15s',
                  }}
                    onMouseEnter={e => {
                      e.currentTarget.style.borderColor = 'var(--border-h)';
                      e.currentTarget.style.color = label === 'WhatsApp' ? '#25D366' : 'var(--gold)';
                    }}
                    onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text2)'; }}
                  >
                    {label === 'Instagram Profissional' && (
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
                        <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/>
                      </svg>
                    )}
                    {label === 'WhatsApp Profissional' && (
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                      </svg>
                    )}
                    {display}
                  </a>
                ))}
              </div>
            )}

            {/* Sem dados */}
            {!profile?.bio && !profile?.occupation && socialLinks.length === 0 && completed === 0 && (
              <p style={{ fontSize: 13, color: 'var(--text3)', textAlign: 'center', padding: '32px 0' }}>
                Este aluno ainda não preencheu o perfil.
              </p>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

window.ProfileView = ProfileView;
