import { useState, useEffect, useCallback } from 'react';
import {
  getOkcToken, setOkcToken,
  getMainSession, getStacks, getStack, getStackMatches,
  getLikesIncoming, getRealLikesCount, getNotifications, getLikesCapInfo,
  getMessages, getConversation, sendMessage,
  vote, getProfile,
} from '../api/okcupid';

// ─── Helpers ─────────────────────────────────────────────────────────────────

const safeText = (v: any): string => {
  if (v == null) return '';
  if (typeof v === 'string') return v;
  if (typeof v === 'number' || typeof v === 'boolean') return String(v);
  return '';
};

function timeAgo(ms: number): string {
  if (!ms) return '';
  const diff = Date.now() - ms;
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  return `${days}d ago`;
}

// ─── OKC Detail Enums ────────────────────────────────────────────────────────

const BODY_TYPES: Record<number, string> = { 1: 'Thin', 2: 'Overweight', 3: 'Skinny', 4: 'Average', 5: 'Fit', 6: 'Athletic', 7: 'Jacked', 8: 'A little extra', 9: 'Curvy', 10: 'Full-figured', 11: 'Rather not say', 20: 'Used up' };
const REL_STATUS: Record<number, string> = { 1: 'Single', 2: 'Seeing Someone', 3: 'Married', 4: "It's Complicated" };
const REL_TYPE: Record<number, string> = { 1: 'Monogamous', 2: 'Non-monogamous', 3: 'Open to either' };
const DRINKING: Record<number, string> = { 1: 'Very often', 2: 'Often', 3: 'Sometimes', 4: 'Rarely', 5: 'Never', 6: 'Desperately' };
const SMOKING: Record<number, string> = { 1: 'Yes', 2: 'Sometimes', 3: 'When drinking', 4: 'Trying to quit', 5: 'No' };
const CHILDREN: Record<number, string> = { 1: "Doesn't have kids", 2: 'Has kid(s)', 3: "Doesn't have kids, wants them", 4: "Has kid(s), wants more", 5: "Doesn't have kids, doesn't want", 6: "Has kid(s), doesn't want more", 7: "Doesn't have kids, might want", 8: "Has kid(s), might want more" };
const POLITICS: Record<number, string> = { 1: 'Liberal', 2: 'Moderate', 3: 'Conservative', 4: 'Other', 5: 'Apolitical' };
const RELIGION_VAL: Record<number, string> = { 1: 'Agnosticism', 2: 'Atheism', 3: 'Christianity', 4: 'Judaism', 5: 'Catholicism', 6: 'Islam', 7: 'Hinduism', 8: 'Buddhism', 9: 'Sikh', 10: 'Other' };
const WEED: Record<number, string> = { 14: 'Yes', 15: 'Sometimes', 16: 'Never' };
const GENDERS: Record<number, string> = { 0: 'Woman', 1: 'Man', 2: 'Agender', 3: 'Androgynous', 4: 'Bigender', 5: 'Cis Man', 6: 'Cis Woman', 7: 'Genderfluid', 8: 'Genderqueer', 9: 'Gender Nonconforming', 10: 'Hijra', 11: 'Intersex', 12: 'Non-binary', 13: 'Other', 14: 'Pangender', 15: 'Transfeminine', 16: 'Transgender', 17: 'Transmasculine', 18: 'Transsexual', 19: 'Trans Man', 20: 'Trans Woman', 21: 'Two Spirit' };
const ORIENTATIONS: Record<number, string> = { 1: 'Straight', 2: 'Bisexual', 3: 'Gay', 4: 'Lesbian', 5: 'Pansexual', 6: 'Queer', 7: 'Questioning', 8: 'Asexual', 9: 'Demisexual', 10: 'Heteroflexible', 11: 'Homoflexible', 12: 'Sapiosexual' };

// ─── Profile Detail Modal ────────────────────────────────────────────────────

function OkcProfileModal({ userId, stream, onClose, onVote }: { userId: string; stream?: string; onClose: () => void; onVote?: (id: string, type: string) => void }) {
  const [profile, setProfile] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [photoIdx, setPhotoIdx] = useState(0);
  const [voting, setVoting] = useState(false);

  useEffect(() => {
    setLoading(true);
    setError('');
    setPhotoIdx(0);
    getProfile(userId).then(data => {
      setProfile(data);
    }).catch(e => setError(e.message)).finally(() => setLoading(false));
  }, [userId]);

  const match = profile?.me?.match;
  const user = match?.user;
  const photos = user?.photos || [];
  const essays = user?.essaysWithUniqueIds?.filter((e: any) => e.rawContent) || [];
  const thread = profile?.me?.conversationThread;

  const handleVote = async (type: string) => {
    if (voting) return;
    setVoting(true);
    try {
      if (onVote) onVote(userId, type);
      await vote(userId, type, stream);
      onClose();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setVoting(false);
    }
  };

  const detailItems: Array<{ label: string; value: string }> = [];
  if (user) {
    if (user.genders?.length) detailItems.push({ label: 'Gender', value: user.genders.map((g: number) => GENDERS[g] || g).join(', ') });
    if (user.orientations?.length) detailItems.push({ label: 'Orientation', value: user.orientations.map((o: number) => ORIENTATIONS[o] || o).join(', ') });
    if (user.pronounCategory) detailItems.push({ label: 'Pronouns', value: safeText(user.pronounCategory) });
    if (user.height) detailItems.push({ label: 'Height', value: `${Math.floor(user.height / 2.54 / 12)}'${Math.round(user.height / 2.54 % 12)}"` });
    if (user.bodyType) detailItems.push({ label: 'Body', value: BODY_TYPES[user.bodyType] || String(user.bodyType) });
    if (user.relationshipStatus) detailItems.push({ label: 'Status', value: REL_STATUS[user.relationshipStatus] || String(user.relationshipStatus) });
    if (user.relationshipType) detailItems.push({ label: 'Relationship', value: REL_TYPE[user.relationshipType] || String(user.relationshipType) });
    if (user.children) detailItems.push({ label: 'Children', value: CHILDREN[user.children] || String(user.children) });
    if (user.drinking) detailItems.push({ label: 'Drinking', value: DRINKING[user.drinking] || String(user.drinking) });
    if (user.smoking) detailItems.push({ label: 'Smoking', value: SMOKING[user.smoking] || String(user.smoking) });
    if (user.weed) detailItems.push({ label: 'Weed', value: WEED[user.weed] || String(user.weed) });
    if (user.politics) detailItems.push({ label: 'Politics', value: POLITICS[user.politics] || String(user.politics) });
    if (user.religion?.value) detailItems.push({ label: 'Religion', value: RELIGION_VAL[user.religion.value] || String(user.religion.value) });
    if (user.diet) detailItems.push({ label: 'Diet', value: safeText(user.diet) });
    if (user.pets?.length) detailItems.push({ label: 'Pets', value: user.pets.map(safeText).join(', ') });
    if (user.knownLanguages?.length) detailItems.push({ label: 'Languages', value: user.knownLanguages.map(safeText).join(', ') });
    if (user.education?.level || user.education?.school?.name) detailItems.push({ label: 'Education', value: [user.education.school?.name, user.education.level].filter(Boolean).map(safeText).join(' — ') });
    if (user.occupation?.title || user.occupation?.employer) detailItems.push({ label: 'Work', value: [user.occupation.title, user.occupation.employer].filter(Boolean).map(safeText).join(' at ') });
    if (user.badges?.length) detailItems.push({ label: 'Badges', value: user.badges.map((b: any) => safeText(b.name)).join(', ') });
  }

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.85)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      backdropFilter: 'blur(8px)',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: '480px', maxHeight: '92dvh',
        background: 'var(--color-deep, #1a1a1e)',
        borderRadius: '20px 20px 0 0',
        overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Drag handle */}
        <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
          <div style={{ width: '36px', height: '4px', borderRadius: '2px', background: 'rgba(255,255,255,0.2)' }} />
        </div>

        {loading ? (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: 'rgba(255,255,255,0.4)' }}>Loading profile...</div>
        ) : error ? (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: '#ef4444' }}>{error}</div>
        ) : !user ? (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: 'rgba(255,255,255,0.4)' }}>Profile not found</div>
        ) : (
          <>
            {/* Scrollable content */}
            <div style={{ flex: 1, overflowY: 'auto', WebkitOverflowScrolling: 'touch' }}>
              {/* Photo carousel */}
              {photos.length > 0 && (
                <div style={{ position: 'relative' }}>
                  <img
                    src={photos[photoIdx]?.square800 || photos[photoIdx]?.original}
                    alt=""
                    style={{ width: '100%', aspectRatio: '3/4', objectFit: 'cover', display: 'block' }}
                  />
                  {/* Photo dots */}
                  {photos.length > 1 && (
                    <div style={{ position: 'absolute', bottom: '12px', left: '50%', transform: 'translateX(-50%)', display: 'flex', gap: '6px' }}>
                      {photos.map((_: any, idx: number) => (
                        <button key={idx} onClick={() => setPhotoIdx(idx)} style={{
                          width: idx === photoIdx ? '20px' : '8px', height: '8px',
                          borderRadius: '4px', border: 'none', cursor: 'pointer',
                          background: idx === photoIdx ? '#fff' : 'rgba(255,255,255,0.4)',
                          transition: 'all 200ms',
                        }} />
                      ))}
                    </div>
                  )}
                  {/* Prev/Next tap zones */}
                  {photos.length > 1 && (
                    <>
                      <div onClick={() => setPhotoIdx(i => Math.max(0, i - 1))} style={{ position: 'absolute', inset: '0 50% 0 0', cursor: 'pointer' }} />
                      <div onClick={() => setPhotoIdx(i => Math.min(photos.length - 1, i + 1))} style={{ position: 'absolute', inset: '0 0 0 50%', cursor: 'pointer' }} />
                    </>
                  )}
                  {/* Photo counter */}
                  <div style={{ position: 'absolute', top: '12px', right: '12px', padding: '4px 10px', borderRadius: '12px', background: 'rgba(0,0,0,0.6)', fontSize: '12px', color: 'rgba(255,255,255,0.8)', fontWeight: 600 }}>
                    {photoIdx + 1}/{photos.length}
                  </div>
                  {/* Match badge */}
                  {match?.matchPercent && (
                    <div style={{ position: 'absolute', top: '12px', left: '12px', padding: '4px 12px', borderRadius: '12px', background: 'rgba(230,73,128,0.85)', fontSize: '13px', fontWeight: 700, color: '#fff', backdropFilter: 'blur(8px)' }}>
                      {match.matchPercent}% Match
                    </div>
                  )}
                </div>
              )}

              {/* Name, age, location */}
              <div style={{ padding: '16px 20px 12px' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px', marginBottom: '4px' }}>
                  <span style={{ fontFamily: 'var(--font-display, system-ui)', fontSize: '24px', fontWeight: 700, color: '#fff' }}>{safeText(user.displayname)}</span>
                  <span style={{ fontSize: '20px', color: 'rgba(255,255,255,0.6)', fontWeight: 500 }}>{safeText(user.age)}</span>
                  {user.isOnline && <span style={{ width: '10px', height: '10px', borderRadius: '50%', background: '#22c55e', display: 'inline-block', boxShadow: '0 0 6px rgba(34,197,94,0.5)' }} />}
                  {user.selfieVerifiedStatus === 'VERIFIED' && (
                    <svg viewBox="0 0 24 24" fill="#3b82f6" style={{ width: 20, height: 20 }}>
                      <path fillRule="evenodd" d="M8.603 3.799A4.49 4.49 0 0112 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 013.498 1.307 4.491 4.491 0 011.307 3.497A4.49 4.49 0 0121.75 12a4.49 4.49 0 01-1.549 3.397 4.491 4.491 0 01-1.307 3.497 4.491 4.491 0 01-3.497 1.307A4.49 4.49 0 0112 21.75a4.49 4.49 0 01-3.397-1.549 4.49 4.49 0 01-3.498-1.306 4.491 4.491 0 01-1.307-3.498A4.49 4.49 0 012.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 011.307-3.497 4.49 4.49 0 013.497-1.307z" clipRule="evenodd" />
                    </svg>
                  )}
                </div>
                {user.userLocation?.publicName && (
                  <div style={{ fontSize: '14px', color: 'rgba(255,255,255,0.5)', display: 'flex', alignItems: 'center', gap: '5px' }}>
                    <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 13, height: 13, opacity: 0.6 }}>
                      <path fillRule="evenodd" d="M11.54 22.351l.07.04.028.016a.76.76 0 00.723 0l.028-.015.071-.041a16.975 16.975 0 001.144-.742 19.58 19.58 0 002.683-2.282c1.944-1.99 3.963-4.98 3.963-8.827a8.25 8.25 0 00-16.5 0c0 3.846 2.02 6.837 3.963 8.827a19.58 19.58 0 002.682 2.282 16.975 16.975 0 001.145.742z" clipRule="evenodd" />
                    </svg>
                    {Array.isArray(user.userLocation.publicName) ? user.userLocation.publicName.join(', ') : safeText(user.userLocation.publicName)}
                  </div>
                )}
              </div>

              {/* Match info bar */}
              {match && (
                <div style={{ display: 'flex', gap: '12px', padding: '0 20px 16px', flexWrap: 'wrap' }}>
                  {match.targetLikes && (
                    <span style={{ padding: '4px 12px', borderRadius: '10px', fontSize: '12px', fontWeight: 600, background: 'rgba(34,197,94,0.15)', color: '#22c55e' }}>Likes You</span>
                  )}
                  {match.targetLikeViaSpotlight && (
                    <span style={{ padding: '4px 12px', borderRadius: '10px', fontSize: '12px', fontWeight: 600, background: 'rgba(245,158,11,0.15)', color: '#f59e0b' }}>Via Spotlight</span>
                  )}
                  {match.targetLikeViaSuperBoost && (
                    <span style={{ padding: '4px 12px', borderRadius: '10px', fontSize: '12px', fontWeight: 600, background: 'rgba(59,130,246,0.15)', color: '#3b82f6' }}>Via SuperBoost</span>
                  )}
                  {match.senderVote === 'LIKE' && (
                    <span style={{ padding: '4px 12px', borderRadius: '10px', fontSize: '12px', fontWeight: 600, background: 'rgba(124,58,237,0.15)', color: '#a855f7' }}>You Liked</span>
                  )}
                </div>
              )}

              {/* Details grid */}
              {detailItems.length > 0 && (
                <div style={{ padding: '0 20px 16px' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
                    {detailItems.map(d => (
                      <div key={d.label} style={{ padding: '10px 12px', borderRadius: '10px', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.04)' }}>
                        <div style={{ fontSize: '10px', fontWeight: 600, color: 'rgba(255,255,255,0.35)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '2px' }}>{d.label}</div>
                        <div style={{ fontSize: '13px', color: 'rgba(255,255,255,0.8)' }}>{d.value}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Essays / Prompts */}
              {essays.length > 0 && (
                <div style={{ padding: '0 20px 16px' }}>
                  {essays.map((e: any) => (
                    <div key={e.id} style={{ marginBottom: '16px' }}>
                      <div style={{ fontSize: '12px', fontWeight: 700, color: 'rgba(255,255,255,0.4)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '6px' }}>{safeText(e.title || e.groupTitle)}</div>
                      <div style={{ fontSize: '15px', color: 'rgba(255,255,255,0.85)', lineHeight: '1.6' }}>{safeText(e.rawContent || e.processedContent)}</div>
                    </div>
                  ))}
                </div>
              )}

              {/* Existing messages */}
              {thread?.messages?.length > 0 && (
                <div style={{ padding: '0 20px 16px' }}>
                  <div style={{ fontSize: '12px', fontWeight: 700, color: 'rgba(255,255,255,0.4)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '8px' }}>Messages</div>
                  {thread.messages.map((m: any) => (
                    <div key={m.id} style={{ padding: '8px 12px', borderRadius: '10px', background: m.senderId === profile?.me?.id ? 'rgba(124,58,237,0.15)' : 'rgba(255,255,255,0.04)', marginBottom: '4px', fontSize: '14px', color: 'rgba(255,255,255,0.8)' }}>
                      {safeText(m.text)}
                    </div>
                  ))}
                </div>
              )}

              {/* Bottom padding for actions */}
              <div style={{ height: '80px' }} />
            </div>

            {/* Fixed bottom actions */}
            <div style={{
              padding: '12px 20px', paddingBottom: 'max(12px, env(safe-area-inset-bottom, 0px))',
              background: 'var(--color-deep, #1a1a1e)',
              borderTop: '1px solid rgba(255,255,255,0.06)',
              display: 'flex', gap: '12px', justifyContent: 'center',
            }}>
              <button onClick={() => handleVote('PASS')} disabled={voting} style={{
                width: '56px', height: '56px', borderRadius: '50%', border: 'none',
                background: 'rgba(100,116,139,0.7)', color: '#fff', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '22px', transition: 'all 200ms',
              }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ width: 24, height: 24 }}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
              <button onClick={() => handleVote('LIKE')} disabled={voting} style={{
                width: '56px', height: '56px', borderRadius: '50%', border: 'none',
                background: 'linear-gradient(135deg, #e64980, #d946ef)', color: '#fff', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '22px', transition: 'all 200ms',
                boxShadow: '0 4px 16px rgba(230,73,128,0.4)',
              }}>
                <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 24, height: 24 }}>
                  <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
                </svg>
              </button>
              <button onClick={onClose} style={{
                width: '56px', height: '56px', borderRadius: '50%', border: '1px solid rgba(255,255,255,0.1)',
                background: 'transparent', color: 'rgba(255,255,255,0.6)', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '13px', fontWeight: 600, fontFamily: 'var(--font-body, system-ui)',
              }}>
                Close
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ─── Styles ──────────────────────────────────────────────────────────────────

const S = {
  page: {
    minHeight: '100vh',
    background: 'var(--color-void, #0f0f14)',
    color: '#fff',
    fontFamily: 'var(--font-body, system-ui)',
  } as React.CSSProperties,
  header: {
    padding: '20px 24px 0',
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
  } as React.CSSProperties,
  logo: {
    width: '36px',
    height: '36px',
    borderRadius: '10px',
    background: 'linear-gradient(135deg, #e64980, #d946ef)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontWeight: 800,
    fontSize: '14px',
    color: '#fff',
    fontFamily: 'var(--font-display, system-ui)',
    flexShrink: 0,
  } as React.CSSProperties,
  title: {
    fontFamily: 'var(--font-display, system-ui)',
    fontSize: '22px',
    fontWeight: 700,
    color: '#fff',
  } as React.CSSProperties,
  tabs: {
    display: 'flex',
    gap: '2px',
    padding: '16px 24px 0',
    borderBottom: '1px solid rgba(255,255,255,0.06)',
  } as React.CSSProperties,
  tab: (active: boolean) => ({
    padding: '10px 18px',
    fontSize: '14px',
    fontWeight: active ? 600 : 500,
    color: active ? '#e64980' : 'rgba(255,255,255,0.5)',
    background: active ? 'rgba(230,73,128,0.1)' : 'transparent',
    border: 'none',
    borderBottom: active ? '2px solid #e64980' : '2px solid transparent',
    borderRadius: '8px 8px 0 0',
    cursor: 'pointer',
    transition: 'all 200ms',
    fontFamily: 'var(--font-body, system-ui)',
  }) as React.CSSProperties,
  content: {
    padding: '20px 24px',
    paddingBottom: '100px',
  } as React.CSSProperties,
  card: {
    position: 'relative' as const,
    borderRadius: '16px',
    overflow: 'hidden',
    cursor: 'pointer',
    background: 'var(--color-surface, #1E1E22)',
    border: '1px solid rgba(255,255,255,0.04)',
  } as React.CSSProperties,
  cardPhoto: {
    width: '100%',
    aspectRatio: '3/4',
    objectFit: 'cover' as const,
    display: 'block',
    background: 'rgba(255,255,255,0.04)',
  } as React.CSSProperties,
  cardGradient: {
    position: 'absolute' as const,
    inset: 0,
    background: 'linear-gradient(180deg, transparent 0%, transparent 50%, rgba(0,0,0,0.6) 75%, rgba(0,0,0,0.92) 100%)',
    pointerEvents: 'none' as const,
  } as React.CSSProperties,
  cardInfo: {
    position: 'absolute' as const,
    bottom: 0,
    left: 0,
    right: 0,
    padding: '16px',
  } as React.CSSProperties,
  cardRow: {
    display: 'flex',
    gap: '14px',
    alignItems: 'center',
  } as React.CSSProperties,
  avatar: {
    width: '56px',
    height: '56px',
    borderRadius: '14px',
    objectFit: 'cover' as const,
    background: 'rgba(255,255,255,0.06)',
    flexShrink: 0,
  } as React.CSSProperties,
  avatarLg: {
    width: '100%',
    maxWidth: '360px',
    aspectRatio: '1',
    borderRadius: '16px',
    objectFit: 'cover' as const,
    background: 'rgba(255,255,255,0.06)',
  } as React.CSSProperties,
  name: {
    fontWeight: 600,
    fontSize: '18px',
    fontFamily: 'var(--font-display, system-ui)',
    color: '#fff',
    letterSpacing: '-0.01em',
  } as React.CSSProperties,
  sub: {
    fontSize: '12px',
    color: 'rgba(255,255,255,0.6)',
    marginTop: '2px',
  } as React.CSSProperties,
  badge: {
    display: 'inline-block',
    padding: '3px 10px',
    borderRadius: '20px',
    fontSize: '11px',
    fontWeight: 600,
    background: 'rgba(230,73,128,0.25)',
    color: '#f4a5b0',
    marginLeft: '8px',
  } as React.CSSProperties,
  cardActions: {
    position: 'absolute' as const,
    bottom: '12px',
    right: '12px',
    display: 'flex',
    gap: '8px',
    zIndex: 10,
  } as React.CSSProperties,
  cardActionBtn: (variant: 'like' | 'pass') => ({
    width: '44px',
    height: '44px',
    borderRadius: '50%',
    border: 'none',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    backdropFilter: 'blur(8px)',
    transition: 'all 200ms',
    background: variant === 'like' ? 'rgba(34,197,94,0.8)' : 'rgba(100,116,139,0.7)',
    color: '#fff',
    boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
  }) as React.CSSProperties,
  matchBadge: {
    position: 'absolute' as const,
    top: '10px',
    left: '10px',
    zIndex: 10,
    padding: '4px 10px',
    borderRadius: '20px',
    fontSize: '11px',
    fontWeight: 600,
    background: 'rgba(230,73,128,0.85)',
    color: '#fff',
    backdropFilter: 'blur(8px)',
  } as React.CSSProperties,
  likesBadge: {
    position: 'absolute' as const,
    top: '10px',
    left: '10px',
    zIndex: 10,
    padding: '4px 10px',
    borderRadius: '20px',
    fontSize: '11px',
    fontWeight: 600,
    background: 'rgba(34,197,94,0.85)',
    color: '#fff',
    backdropFilter: 'blur(8px)',
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
  } as React.CSSProperties,
  btn: (variant: 'primary' | 'secondary' | 'danger') => ({
    padding: '10px 20px',
    borderRadius: '12px',
    border: 'none',
    fontWeight: 600,
    fontSize: '14px',
    cursor: 'pointer',
    transition: 'all 200ms',
    fontFamily: 'var(--font-body, system-ui)',
    ...(variant === 'primary' ? {
      background: 'linear-gradient(135deg, #e64980, #d946ef)',
      color: '#fff',
    } : variant === 'danger' ? {
      background: 'rgba(239,68,68,0.15)',
      color: '#ef4444',
    } : {
      background: 'rgba(255,255,255,0.08)',
      color: 'rgba(255,255,255,0.7)',
    }),
  }) as React.CSSProperties,
  empty: {
    textAlign: 'center' as const,
    padding: '40px 20px',
    color: 'rgba(255,255,255,0.3)',
    fontSize: '15px',
  } as React.CSSProperties,
  error: {
    padding: '16px',
    borderRadius: '12px',
    background: 'rgba(239,68,68,0.1)',
    border: '1px solid rgba(239,68,68,0.2)',
    color: '#ef4444',
    fontSize: '14px',
    marginBottom: '16px',
  } as React.CSSProperties,
  loading: {
    textAlign: 'center' as const,
    padding: '40px',
    color: 'rgba(255,255,255,0.4)',
    fontSize: '14px',
  } as React.CSSProperties,
  grid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))',
    gap: '12px',
  } as React.CSSProperties,
  input: {
    width: '100%',
    padding: '12px 16px',
    borderRadius: '12px',
    border: '1px solid rgba(255,255,255,0.1)',
    background: 'rgba(255,255,255,0.04)',
    color: '#fff',
    fontSize: '14px',
    fontFamily: 'var(--font-body, system-ui)',
    outline: 'none',
    boxSizing: 'border-box' as const,
  } as React.CSSProperties,
  msgBubble: (isMine: boolean) => ({
    maxWidth: '75%',
    padding: '10px 14px',
    borderRadius: '14px',
    fontSize: '14px',
    lineHeight: '1.45',
    marginBottom: '6px',
    alignSelf: isMine ? 'flex-end' : 'flex-start',
    background: isMine ? 'linear-gradient(135deg, #e64980, #d946ef)' : 'rgba(255,255,255,0.08)',
    color: '#fff',
  }) as React.CSSProperties,
  stackChip: (active: boolean) => ({
    padding: '8px 16px',
    borderRadius: '20px',
    fontSize: '13px',
    fontWeight: 600,
    cursor: 'pointer',
    border: active ? '1px solid #e64980' : '1px solid rgba(255,255,255,0.1)',
    background: active ? 'rgba(230,73,128,0.15)' : 'rgba(255,255,255,0.04)',
    color: active ? '#e64980' : 'rgba(255,255,255,0.6)',
    whiteSpace: 'nowrap' as const,
    transition: 'all 200ms',
  }) as React.CSSProperties,
  section: {
    marginBottom: '24px',
  } as React.CSSProperties,
  sectionTitle: {
    fontSize: '13px',
    fontWeight: 600,
    color: 'rgba(255,255,255,0.4)',
    textTransform: 'uppercase' as const,
    letterSpacing: '0.06em',
    marginBottom: '12px',
  } as React.CSSProperties,
  profileActions: {
    display: 'flex',
    gap: '10px',
    marginTop: '12px',
  } as React.CSSProperties,
};

// ─── Discover Tab ────────────────────────────────────────────────────────────

function DiscoverTab() {
  const [stacks, setStacks] = useState<any[]>([]);
  const [selectedStack, setSelectedStack] = useState<string>('');
  const [profiles, setProfiles] = useState<any[]>([]);
  const [excludedIds, setExcludedIds] = useState<string[]>([]);
  const [likesInfo, setLikesInfo] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [votingId, setVotingId] = useState<string | null>(null);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [selectedProfileId, setSelectedProfileId] = useState<string | null>(null);
  const [expandedProfile, setExpandedProfile] = useState<any>(null);

  const loadStacks = useCallback(async () => {
    try {
      setLoading(true);
      setError('');
      const [stacksData, capData] = await Promise.all([getStacks(), getLikesCapInfo()]);
      const s = stacksData?.me?.stacks || [];
      setStacks(s);
      if (s.length > 0 && !selectedStack) {
        setSelectedStack(s[0].id);
      }
      setLikesInfo(capData?.me?.likesCap);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, [selectedStack]);

  const [loadingMore, setLoadingMore] = useState(false);

  const loadStack = useCallback(async (stackId: string, append = false) => {
    if (!stackId) return;
    try {
      if (append) setLoadingMore(true); else setLoading(true);
      setError('');
      const currentIds = append ? [...excludedIds, ...profiles.map(m => m?.user?.id).filter(Boolean)] : excludedIds;
      const data = await getStack(stackId, currentIds);
      const stackData = data?.me?.stack?.data || [];
      const matches = stackData
        .filter((d: any) => d.__typename === 'StackMatch' && d.match?.user?.id)
        .map((d: any) => ({ ...d.match, _stream: d.stream }));
      if (append) {
        setProfiles(prev => [...prev, ...matches]);
        setExcludedIds(currentIds);
      } else {
        setProfiles(matches);
      }
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  }, [excludedIds, profiles]);

  useEffect(() => { loadStacks(); }, []);
  useEffect(() => { if (selectedStack) loadStack(selectedStack); }, [selectedStack]);

  const handleVote = async (targetId: string, type: 'LIKE' | 'PASS') => {
    try {
      setVotingId(targetId);
      const profile = profiles.find(p => p?.user?.id === targetId);
      const stream = profile?._stream;
      const result = await vote(targetId, type, stream);
      setExcludedIds(prev => [...prev, targetId]);
      setProfiles(prev => prev.filter(p => p?.user?.id !== targetId));
      if (result?.userVote?.likesRemaining != null) {
        setLikesInfo((prev: any) => prev ? { ...prev, likesRemaining: result.userVote.likesRemaining } : prev);
      }
    } catch (e: any) {
      setError(e.message);
    } finally {
      setVotingId(null);
    }
  };

  const handleExpand = async (userId: string) => {
    if (expandedId === userId) {
      setExpandedId(null);
      setExpandedProfile(null);
      return;
    }
    setExpandedId(userId);
    try {
      const data = await getProfile(userId);
      setExpandedProfile(data?.me?.match);
    } catch {
      setExpandedProfile(null);
    }
  };

  return (
    <div>
      {error && <div style={S.error}>{error}</div>}

      {likesInfo && (
        <div style={{ ...S.card, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: '14px', color: 'rgba(255,255,255,0.6)' }}>Likes remaining</span>
          <span style={{ fontSize: '18px', fontWeight: 700, color: '#e64980' }}>
            {safeText(likesInfo.likesRemaining)} / {safeText(likesInfo.likesCapTotal)}
          </span>
        </div>
      )}

      {stacks.length > 0 && (
        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', marginBottom: '16px' }}>
          {stacks.map((s: any) => (
            <button
              key={s.id}
              style={S.stackChip(selectedStack === s.id)}
              onClick={() => { setSelectedStack(s.id); setExcludedIds([]); setProfiles([]); }}
            >
              {safeText(s.id)} {s.badge ? `(${safeText(s.badge)})` : ''}
            </button>
          ))}
          <button style={S.btn('secondary')} onClick={() => loadStack(selectedStack)}>
            Refresh
          </button>
        </div>
      )}

      {loading ? (
        <div style={S.loading}>Loading profiles...</div>
      ) : profiles.length === 0 ? (
        <div style={S.empty}>No profiles in this stack. Try another or refresh.</div>
      ) : (
        <div style={S.grid}>
          {profiles.map((match: any) => {
            const user = match?.user;
            if (!user) return null;
            const photoUrl = user.primaryImage?.square800;
            return (
              <div key={user.id} style={S.card} onClick={() => setSelectedProfileId(user.id)}>
                {photoUrl ? (
                  <img src={photoUrl} alt="" style={S.cardPhoto} />
                ) : (
                  <div style={{ ...S.cardPhoto, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'linear-gradient(135deg, var(--color-surface, #1E1E22), var(--color-void, #121212))' }}>
                    <svg viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="1" style={{ width: 48, height: 48 }}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                    </svg>
                  </div>
                )}
                <div style={S.cardGradient} />

                {match.matchPercent && (
                  <div style={S.matchBadge}>{safeText(match.matchPercent)}%</div>
                )}

                {match.targetLikes && (
                  <div style={S.likesBadge}>
                    <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 12, height: 12 }}>
                      <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
                    </svg>
                    Likes you
                  </div>
                )}

                <div style={S.cardInfo}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: '6px', marginBottom: '3px' }}>
                    <span style={S.name}>{safeText(user.displayname)}</span>
                    <span style={{ fontSize: '15px', color: 'rgba(255,255,255,0.75)', fontWeight: 500 }}>{safeText(user.age)}</span>
                  </div>
                  <div style={S.sub}>{safeText(user.userLocation?.publicName)}</div>
                </div>

                <div style={S.cardActions}>
                  <button
                    style={S.cardActionBtn('pass')}
                    disabled={votingId === user.id}
                    onClick={(e) => { e.stopPropagation(); handleVote(user.id, 'PASS'); }}
                  >
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ width: 18, height: 18 }}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                  <button
                    style={S.cardActionBtn('like')}
                    disabled={votingId === user.id}
                    onClick={(e) => { e.stopPropagation(); handleVote(user.id, 'LIKE'); }}
                  >
                    <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 18, height: 18 }}>
                      <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
                    </svg>
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {profiles.length > 0 && !loading && (
        <div style={{ textAlign: 'center', marginTop: '16px' }}>
          <button
            style={S.btn('secondary')}
            onClick={() => loadStack(selectedStack, true)}
            disabled={loadingMore}
          >
            {loadingMore ? 'Loading...' : `Load More (${profiles.length} shown)`}
          </button>
        </div>
      )}

      {selectedProfileId && (
        <OkcProfileModal
          userId={selectedProfileId}
          stream={profiles.find(p => p?.user?.id === selectedProfileId)?._stream}
          onClose={() => setSelectedProfileId(null)}
          onVote={(id, type) => {
            setProfiles(prev => prev.filter(m => m?.user?.id !== id));
            setExcludedIds(prev => [...prev, id]);
          }}
        />
      )}
    </div>
  );
}

// ─── Likes Tab ───────────────────────────────────────────────────────────────

function LikesTab() {
  const [likes, setLikes] = useState<any[]>([]);
  const [selectedProfileId, setSelectedProfileId] = useState<string | null>(null);
  const [pageInfo, setPageInfo] = useState<any>(null);
  const [notifications, setNotifications] = useState<any>(null);
  const [realLikeCount, setRealLikeCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async (nextPageKey: string | null = null) => {
    try {
      setLoading(true);
      setError('');
      const [likesData, notifData, realCount] = await Promise.all([
        getLikesIncoming(20, nextPageKey),
        getNotifications(),
        nextPageKey ? Promise.resolve(realLikeCount) : getRealLikesCount(),
      ]);
      const items = likesData?.me?.likesIncomingWithPreviews?.data || [];
      setLikes(prev => nextPageKey ? [...prev, ...items] : items);
      setPageInfo(likesData?.me?.likesIncomingWithPreviews?.pageInfo);
      setNotifications(notifData?.me?.notificationCounts);
      if (typeof realCount === 'number') setRealLikeCount(realCount);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, []);

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

  return (
    <div>
      {error && <div style={S.error}>{error}</div>}

      {notifications && (
        <div style={{ ...S.card, display: 'flex', gap: '20px' }}>
          <div>
            <div style={{ fontSize: '22px', fontWeight: 700, color: '#22c55e' }}>{realLikeCount}</div>
            <div style={S.sub}>Real likes</div>
          </div>
          <div>
            <div style={{ fontSize: '22px', fontWeight: 700, color: 'rgba(255,255,255,0.4)' }}>{safeText(notifications.likesIncoming)}</div>
            <div style={S.sub}>Views</div>
          </div>
          <div>
            <div style={{ fontSize: '22px', fontWeight: 700, color: '#d946ef' }}>{safeText(notifications.likesMutual)}</div>
            <div style={S.sub}>Mutual matches</div>
          </div>
          <div>
            <div style={{ fontSize: '22px', fontWeight: 700, color: 'rgba(255,255,255,0.6)' }}>{safeText(notifications.messages)}</div>
            <div style={S.sub}>Messages</div>
          </div>
        </div>
      )}

      {loading && likes.length === 0 ? (
        <div style={S.loading}>Loading likes...</div>
      ) : likes.length === 0 ? (
        <div style={S.empty}>No incoming likes yet.</div>
      ) : (
        <>
          <div style={S.grid}>
            {likes.map((item: any, i: number) => {
              const user = item?.user;
              const preview = item;
              const img = user?.primaryImage?.square800 || preview?.primaryImage?.square800 || preview?.primaryImageBlurred?.square800;
              const highlights = item?.matchHighlights || preview?.matchHighlights;
              const matchPct = item?.matchPercent || highlights?.matchScore;
              const location = highlights?.dynamicHighlight?.summary || user?.userLocation?.publicName;
              const isOnline = user?.isOnline || highlights?.isOnline;
              const isVerified = highlights?.isVerified;
              const isSuperlike = item?.targetSuperlikes || preview?.targetSuperlikes;
              const hasIntro = item?.hasFirstMessage || preview?.hasFirstMessage || highlights?.hasIntroMessage;
              const viewedMe = item?.targetViewedMe || preview?.targetViewedMe;
              const age = user?.age || highlights?.age;
              const displayName = user?.displayname;

              // OKC puts real likes first, views after
              const isRealLike = i < realLikeCount;
              const isJustViewed = !isRealLike;

              return (
                <div key={user?.id || `like-${i}`} style={S.card} onClick={() => user?.id && setSelectedProfileId(user.id)}>
                  {img ? (
                    <img src={img} alt="" style={S.cardPhoto} />
                  ) : (
                    <div style={{ ...S.cardPhoto, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'linear-gradient(135deg, #1E1E22, #121212)' }}>
                      <svg viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="1" style={{ width: 48, height: 48 }}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                      </svg>
                    </div>
                  )}
                  <div style={S.cardGradient} />

                  {/* Top-left badges */}
                  <div style={{ position: 'absolute', top: '10px', left: '10px', zIndex: 10, display: 'flex', flexDirection: 'column', gap: '4px' }}>
                    {isRealLike && (
                      <div style={{ ...S.likesBadge, background: 'rgba(34,197,94,0.9)' }}>
                        <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 12, height: 12 }}>
                          <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
                        </svg>
                        Liked You
                      </div>
                    )}
                    {isJustViewed && (
                      <div style={{ ...S.matchBadge, background: 'rgba(100,116,139,0.75)' }}>
                        Viewed
                      </div>
                    )}
                    {matchPct && <div style={S.matchBadge}>{safeText(matchPct)}% Match</div>}
                    {isSuperlike && (
                      <div style={{ ...S.matchBadge, background: 'rgba(59,130,246,0.85)' }}>
                        <span style={{ marginRight: '4px' }}>★</span>SuperLike
                      </div>
                    )}
                  </div>

                  {/* Top-right badges */}
                  <div style={{ position: 'absolute', top: '10px', right: '10px', zIndex: 10, display: 'flex', gap: '4px' }}>
                    {isVerified && (
                      <div style={{ width: '26px', height: '26px', borderRadius: '50%', background: 'linear-gradient(135deg, #3b82f6, #2563eb)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(59,130,246,0.4)' }} title="Verified">
                        <svg viewBox="0 0 24 24" fill="#fff" style={{ width: 14, height: 14 }}>
                          <path fillRule="evenodd" d="M8.603 3.799A4.49 4.49 0 0112 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 013.498 1.307 4.491 4.491 0 011.307 3.497A4.49 4.49 0 0121.75 12a4.49 4.49 0 01-1.549 3.397 4.491 4.491 0 01-1.307 3.497 4.491 4.491 0 01-3.497 1.307A4.49 4.49 0 0112 21.75a4.49 4.49 0 01-3.397-1.549 4.49 4.49 0 01-3.498-1.306 4.491 4.491 0 01-1.307-3.498A4.49 4.49 0 012.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 011.307-3.497 4.49 4.49 0 013.497-1.307z" clipRule="evenodd" />
                        </svg>
                      </div>
                    )}
                    {isOnline && (
                      <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: '#22c55e', border: '2px solid rgba(0,0,0,0.5)', boxShadow: '0 0 6px rgba(34,197,94,0.6)', marginTop: '8px' }} title="Online now" />
                    )}
                  </div>

                  {/* Bottom info */}
                  <div style={S.cardInfo}>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: '6px', marginBottom: '3px' }}>
                      <span style={S.name}>{displayName ? safeText(displayName) : 'Hidden'}</span>
                      {age && <span style={{ fontSize: '15px', color: 'rgba(255,255,255,0.75)', fontWeight: 500 }}>{safeText(age)}</span>}
                    </div>

                    {location && (
                      <div style={{ ...S.sub, display: 'flex', alignItems: 'center', gap: '4px' }}>
                        <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 11, height: 11, opacity: 0.6 }}>
                          <path fillRule="evenodd" d="M11.54 22.351l.07.04.028.016a.76.76 0 00.723 0l.028-.015.071-.041a16.975 16.975 0 001.144-.742 19.58 19.58 0 002.683-2.282c1.944-1.99 3.963-4.98 3.963-8.827a8.25 8.25 0 00-16.5 0c0 3.846 2.02 6.837 3.963 8.827a19.58 19.58 0 002.682 2.282 16.975 16.975 0 001.145.742zM12 13.5a3 3 0 100-6 3 3 0 000 6z" clipRule="evenodd" />
                        </svg>
                        {safeText(location)}
                      </div>
                    )}

                    {/* Status tags */}
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginTop: '6px' }}>
                      {hasIntro && (
                        <span style={{ padding: '2px 8px', borderRadius: '8px', fontSize: '10px', fontWeight: 600, background: 'rgba(124,58,237,0.25)', color: 'rgba(200,170,255,0.9)', textTransform: 'uppercase', letterSpacing: '0.03em' }}>
                          Intro
                        </span>
                      )}
                      {viewedMe && (
                        <span style={{ padding: '2px 8px', borderRadius: '8px', fontSize: '10px', fontWeight: 600, background: 'rgba(255,255,255,0.08)', color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: '0.03em' }}>
                          Viewed
                        </span>
                      )}
                    </div>

                    {item?.firstMessage && (
                      <div style={{ fontSize: '11px', color: 'rgba(255,255,255,0.5)', marginTop: '4px', fontStyle: 'italic', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        "{safeText(item.firstMessage.text)}"
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
          {pageInfo?.hasMore && (
            <div style={{ textAlign: 'center', marginTop: '16px' }}>
              <button style={S.btn('secondary')} onClick={() => load(pageInfo.after)} disabled={loading}>
                {loading ? 'Loading...' : 'Load More'}
              </button>
            </div>
          )}
        </>
      )}

      {selectedProfileId && (
        <OkcProfileModal
          userId={selectedProfileId}
          onClose={() => setSelectedProfileId(null)}
        />
      )}
    </div>
  );
}

// ─── Messages Tab ────────────────────────────────────────────────────────────

function MessagesTab() {
  const [conversations, setConversations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [activeConvo, setActiveConvo] = useState<string | null>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [convoLoading, setConvoLoading] = useState(false);
  const [convoCorrespondent, setConvoCorrespondent] = useState<any>(null);
  const [msgText, setMsgText] = useState('');
  const [sending, setSending] = useState(false);
  const [myId, setMyId] = useState<string>('');

  const loadConversations = useCallback(async () => {
    try {
      setLoading(true);
      setError('');
      const data = await getMessages('ALL');
      setConversations(data?.me?.conversationsAndMatches?.data || []);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadConversations();
    getMainSession().then(d => { if (d?.me?.id) setMyId(d.me.id); }).catch(() => {});
  }, []);

  const openConvo = async (targetId: string, correspondent: any) => {
    try {
      setActiveConvo(targetId);
      setConvoLoading(true);
      setConvoCorrespondent(correspondent);
      const data = await getConversation(targetId);
      setMessages(data?.me?.conversationThread?.messages || []);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setConvoLoading(false);
    }
  };

  const handleSend = async () => {
    if (!msgText.trim() || !activeConvo) return;
    try {
      setSending(true);
      await sendMessage(activeConvo, msgText.trim());
      setMsgText('');
      // Reload conversation
      const data = await getConversation(activeConvo);
      setMessages(data?.me?.conversationThread?.messages || []);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSending(false);
    }
  };

  if (activeConvo) {
    const corrUser = convoCorrespondent?.user;
    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px' }}>
          <button style={S.btn('secondary')} onClick={() => { setActiveConvo(null); setMessages([]); }}>
            Back
          </button>
          {corrUser?.primaryImage?.square225 && (
            <img src={corrUser.primaryImage.square225} alt="" style={{ ...S.avatar, width: '36px', height: '36px' }} />
          )}
          <div style={S.name}>{safeText(corrUser?.displayname)}</div>
        </div>

        {error && <div style={S.error}>{error}</div>}

        {convoLoading ? (
          <div style={S.loading}>Loading messages...</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', marginBottom: '16px', maxHeight: '500px', overflowY: 'auto' }}>
            {messages.map((msg: any) => {
              const isMine = msg.senderId === myId;
              return (
                <div key={msg.id} style={S.msgBubble(isMine)}>
                  <div>{safeText(msg.text)}</div>
                  <div style={{ fontSize: '10px', color: 'rgba(255,255,255,0.35)', marginTop: '4px' }}>
                    {timeAgo(msg.time)}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        <div style={{ display: 'flex', gap: '8px' }}>
          <input
            style={{ ...S.input, flex: 1 }}
            placeholder="Type a message..."
            value={msgText}
            onChange={(e) => setMsgText(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
          />
          <button style={S.btn('primary')} onClick={handleSend} disabled={sending || !msgText.trim()}>
            {sending ? '...' : 'Send'}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      {error && <div style={S.error}>{error}</div>}

      {loading ? (
        <div style={S.loading}>Loading conversations...</div>
      ) : conversations.length === 0 ? (
        <div style={S.empty}>No conversations yet.</div>
      ) : (
        conversations.map((item: any, i: number) => {
          const isConvo = item.__typename === 'Conversation';
          const isMutual = item.__typename === 'MutualMatch';
          const correspondent = isConvo ? item.correspondent : isMutual ? item.match : null;
          const user = correspondent?.user;
          if (!user) return null;
          return (
            <div
              key={user.id || `conv-${i}`}
              style={{ ...S.card, cursor: 'pointer' }}
              onClick={() => openConvo(user.id, correspondent)}
            >
              <div style={S.cardRow}>
                {user.primaryImage?.square225 && (
                  <img src={user.primaryImage.square225} alt="" style={S.avatar} />
                )}
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={S.name}>
                      {safeText(user.displayname)}
                      {user.isOnline && <span style={{ ...S.badge, background: 'rgba(34,197,94,0.15)', color: '#22c55e' }}>Online</span>}
                    </div>
                    {isConvo && item.time && (
                      <div style={{ fontSize: '12px', color: 'rgba(255,255,255,0.3)' }}>{timeAgo(item.time)}</div>
                    )}
                  </div>
                  {isConvo && item.snippet?.text && (
                    <div style={{ ...S.sub, marginTop: '4px' }}>
                      {item.isUnread && <span style={{ color: '#e64980', marginRight: '4px', fontWeight: 700 }}>*</span>}
                      {safeText(item.snippet.text).slice(0, 80)}{item.snippet.text?.length > 80 ? '...' : ''}
                    </div>
                  )}
                  {isMutual && (
                    <div style={{ ...S.sub, color: '#d946ef' }}>New match!</div>
                  )}
                </div>
              </div>
            </div>
          );
        })
      )}
    </div>
  );
}

// ─── Profile Tab ─────────────────────────────────────────────────────────────

function ProfileTab() {
  const [session, setSession] = useState<any>(null);
  const [likesInfo, setLikesInfo] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [tokenInput, setTokenInput] = useState('');
  const [tokenSaved, setTokenSaved] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        setLoading(true);
        const [sessionData, capData] = await Promise.all([getMainSession(), getLikesCapInfo()]);
        setSession(sessionData);
        setLikesInfo(capData?.me?.likesCap);
      } catch (e: any) {
        setError(e.message);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const handleSaveToken = () => {
    const cleaned = tokenInput.trim();
    if (!cleaned) return;
    setOkcToken(cleaned);
    setTokenInput('');
    setTokenSaved(true);
    setTimeout(() => setTokenSaved(false), 3000);
  };

  if (loading) return <div style={S.loading}>Loading profile...</div>;

  const me = session?.me;
  const xFields = me?.xMatchFields;

  return (
    <div>
      {error && <div style={S.error}>{error}</div>}

      <div style={S.section}>
        <div style={S.sectionTitle}>Token Management</div>
        <div style={S.card}>
          <div style={{ fontSize: '13px', color: 'rgba(255,255,255,0.4)', marginBottom: '8px' }}>
            Paste a new JWT token from Proxyman. Current token: {getOkcToken().slice(0, 20)}...
          </div>
          <div style={{ display: 'flex', gap: '8px' }}>
            <input
              style={{ ...S.input, flex: 1 }}
              placeholder="Paste JWT token..."
              value={tokenInput}
              onChange={(e) => setTokenInput(e.target.value)}
            />
            <button style={S.btn('primary')} onClick={handleSaveToken}>Save</button>
          </div>
          {tokenSaved && <div style={{ color: '#22c55e', fontSize: '13px', marginTop: '8px' }}>Token saved!</div>}
        </div>
      </div>

      {me && (
        <div style={S.section}>
          <div style={S.sectionTitle}>Your Profile</div>
          <div style={S.card}>
            <div style={S.cardRow}>
              {me.primaryImage?.square800 && (
                <img src={me.primaryImage.square800} alt="" style={{ ...S.avatar, width: '80px', height: '80px' }} />
              )}
              <div>
                <div style={{ fontSize: '20px', fontWeight: 700, color: '#fff' }}>{safeText(me.displayname)}, {safeText(me.age)}</div>
                <div style={S.sub}>{safeText(me.userLocation?.publicName)}</div>
                <div style={S.sub}>{safeText(me.emailAddress)}</div>
              </div>
            </div>

            <div style={{ display: 'flex', gap: '16px', marginTop: '16px', flexWrap: 'wrap' }}>
              {me.orientations?.length > 0 && (
                <div style={S.sub}>Orientations: {me.orientations.map(safeText).join(', ')}</div>
              )}
              {me.relationshipType && <div style={S.sub}>Relationship: {safeText(me.relationshipType)}</div>}
              {me.joinDate && <div style={S.sub}>Joined: {new Date(me.joinDate).toLocaleDateString()}</div>}
            </div>
          </div>
        </div>
      )}

      {xFields && (
        <div style={S.section}>
          <div style={S.sectionTitle}>Cross-Sell Profile Data</div>
          <div style={S.card}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
              {xFields.firstName && <div style={S.sub}>Name: {safeText(xFields.firstName)}</div>}
              {xFields.bio && <div style={{ ...S.sub, gridColumn: '1/-1' }}>Bio: {safeText(xFields.bio)}</div>}
              {xFields.genderPresentation && <div style={S.sub}>Gender: {safeText(xFields.genderPresentation)}</div>}
              {xFields.bodyType && <div style={S.sub}>Body: {safeText(xFields.bodyType)}</div>}
              {xFields.heightInCm && <div style={S.sub}>Height: {safeText(xFields.heightInCm)}cm</div>}
              {xFields.relationshipStatus && <div style={S.sub}>Status: {safeText(xFields.relationshipStatus)}</div>}
              {xFields.relationshipIntent && <div style={S.sub}>Intent: {safeText(xFields.relationshipIntent)}</div>}
              {xFields.lookingFor?.length > 0 && <div style={S.sub}>Looking for: {xFields.lookingFor.map(safeText).join(', ')}</div>}
              {xFields.drinking && <div style={S.sub}>Drinking: {safeText(xFields.drinking)}</div>}
              {xFields.smoking && <div style={S.sub}>Smoking: {safeText(xFields.smoking)}</div>}
              {xFields.marijuana && <div style={S.sub}>Marijuana: {safeText(xFields.marijuana)}</div>}
              {xFields.pets?.length > 0 && <div style={S.sub}>Pets: {xFields.pets.map(safeText).join(', ')}</div>}
              {xFields.education && <div style={S.sub}>Education: {safeText(xFields.education)}</div>}
              {xFields.jobTitle && <div style={S.sub}>Job: {safeText(xFields.jobTitle)}{xFields.jobCompany ? ` at ${safeText(xFields.jobCompany)}` : ''}</div>}
            </div>
          </div>
        </div>
      )}

      {likesInfo && (
        <div style={S.section}>
          <div style={S.sectionTitle}>Likes Cap</div>
          <div style={S.card}>
            <div style={{ display: 'flex', gap: '20px' }}>
              <div>
                <div style={{ fontSize: '22px', fontWeight: 700, color: '#e64980' }}>{safeText(likesInfo.likesRemaining)}</div>
                <div style={S.sub}>Remaining</div>
              </div>
              <div>
                <div style={{ fontSize: '22px', fontWeight: 700, color: 'rgba(255,255,255,0.6)' }}>{safeText(likesInfo.likesCapTotal)}</div>
                <div style={S.sub}>Total</div>
              </div>
              <div>
                <div style={{ fontSize: '22px', fontWeight: 700, color: 'rgba(255,255,255,0.6)' }}>{safeText(likesInfo.viewCount)}</div>
                <div style={S.sub}>Views</div>
              </div>
              {likesInfo.resetTime && (
                <div>
                  <div style={{ fontSize: '14px', fontWeight: 600, color: 'rgba(255,255,255,0.5)' }}>{new Date(likesInfo.resetTime).toLocaleString()}</div>
                  <div style={S.sub}>Resets</div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {me?.photos?.length > 0 && (
        <div style={S.section}>
          <div style={S.sectionTitle}>Your Photos</div>
          <div style={{ display: 'flex', gap: '8px', overflowX: 'auto' }}>
            {me.photos.map((p: any) => (
              <img key={p.id} src={p.original} alt="" style={{ width: '140px', height: '180px', borderRadius: '12px', objectFit: 'cover', flexShrink: 0 }} />
            ))}
          </div>
        </div>
      )}

      <div style={S.section}>
        <div style={S.sectionTitle}>Subscription Status</div>
        <div style={S.card}>
          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
            {[
              ['Basic', me?.ALIST_BASIC],
              ['Premium', me?.ALIST_PREMIUM],
              ['Premium+', me?.ALIST_PREMIUM_PLUS],
              ['Incognito', me?.INCOGNITO],
            ].map(([label, val]) => (
              <div key={label as string} style={{ fontSize: '13px' }}>
                <span style={{ color: 'rgba(255,255,255,0.5)' }}>{label as string}: </span>
                <span style={{ color: val ? '#22c55e' : 'rgba(255,255,255,0.25)' }}>{val ? 'Active' : 'No'}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Main Page ───────────────────────────────────────────────────────────────

type TabId = 'discover' | 'likes' | 'messages' | 'profile';

export function OkCupidPage() {
  const [tab, setTab] = useState<TabId>('discover');

  const tabs: { id: TabId; label: string }[] = [
    { id: 'discover', label: 'Discover' },
    { id: 'likes', label: 'Likes' },
    { id: 'messages', label: 'Messages' },
    { id: 'profile', label: 'Profile' },
  ];

  return (
    <div style={S.page}>
      <div style={S.header}>
        <div style={S.logo}>OK</div>
        <div style={S.title}>OkCupid</div>
      </div>

      <div style={S.tabs}>
        {tabs.map((t) => (
          <button key={t.id} style={S.tab(tab === t.id)} onClick={() => setTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>

      <div style={S.content}>
        {tab === 'discover' && <DiscoverTab />}
        {tab === 'likes' && <LikesTab />}
        {tab === 'messages' && <MessagesTab />}
        {tab === 'profile' && <ProfileTab />}
      </div>
    </div>
  );
}
