import { useState } from 'react';
import { useQuery, useMutation } from '@apollo/client/react';
import { PROFILE_QUERY, SEARCH_SETTINGS_QUERY } from '../api/operations/queries';
import { PROFILE_UPDATE_MUTATION } from '../api/operations/mutations';
import { authManager } from '../api/auth';
import { LoadingPage } from '../components/ui/Loading';
import { ProxiedImage } from '../components/ui/ProxiedImage';
import { getBestImageUrl } from '../utils/images';

// Available options for multi-select fields (from API LocalisedDesireCategory)
const DESIRE_OPTIONS = [
  'AFTERCARE', 'BDSM', 'BONDAGE', 'BRAT', 'BRAT_TAMER', 'CASUAL', 'CELIBATE',
  'COMMUNICATION', 'CONNECTION', 'COUPLES', 'CUDDLING', 'DATES', 'DOMINANTS',
  'EDGING', 'ENM', 'EXPLORATION', 'FF', 'FFF', 'FFFF', 'FFM', 'FLIRTING',
  'FOREPLAY', 'FREEDOMME', 'FRIENDSHIPS', 'FUN', 'FWB', 'GGG', 'GROUP',
  'INTIMACY', 'KINK', 'KISSING', 'MASSAGE', 'MF', 'MFMF', 'MM', 'MMF', 'MMM',
  'MMMM', 'MONOGAMY', 'OPEN_RELATIONSHIP', 'PARTIES', 'POLY', 'RELATIONSHIP',
  'ROLE_PLAY', 'ROUGH', 'SENSUAL', 'SINGLES', 'SUBMISSIVES', 'SWITCH',
  'TEXTING', 'THREESOME', 'TOYS', 'VANILLA', 'WATCHING'
];

const LOOKING_FOR_OPTIONS = [
  'MAN', 'WOMAN', 'NON_BINARY',
  'MAN_WOMAN_COUPLE', 'MAN_MAN_COUPLE', 'WOMAN_WOMAN_COUPLE'
];

const CONNECTION_GOAL_OPTIONS = [
  'DATING', 'LONG_TERM_CONNECTIONS', 'NON_MONOGAMY', 'OPEN_RELATIONSHIP', 'FWB', 'CASUAL'
];

const styles = {
  container: {
    maxWidth: '900px',
    margin: '0 auto',
    paddingBottom: '48px',
  },

  // Hero section with large photo
  heroSection: {
    position: 'relative' as const,
    height: '400px',
    borderRadius: '24px',
    overflow: 'hidden',
    marginBottom: '24px',
  },
  heroImage: {
    width: '100%',
    height: '100%',
    objectFit: 'cover' as const,
  },
  heroOverlay: {
    position: 'absolute' as const,
    inset: 0,
    background: 'linear-gradient(180deg, transparent 0%, transparent 40%, rgba(10,10,12,0.7) 70%, rgba(10,10,12,0.95) 100%)',
  },
  heroContent: {
    position: 'absolute' as const,
    bottom: 0,
    left: 0,
    right: 0,
    padding: '32px',
  },
  heroNameRow: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px',
    marginBottom: '8px',
  },
  heroName: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '42px',
    fontWeight: 700,
    color: '#ffffff',
    margin: 0,
    letterSpacing: '-0.02em',
  },
  badgeRow: {
    display: 'flex',
    gap: '8px',
  },
  majesticBadge: {
    width: '32px',
    height: '32px',
    borderRadius: '50%',
    background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: '0 4px 12px rgba(245, 158, 11, 0.4)',
  },
  verifiedBadge: {
    width: '32px',
    height: '32px',
    borderRadius: '50%',
    background: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: '0 4px 12px rgba(59, 130, 246, 0.4)',
  },
  heroMeta: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
    color: 'rgba(255,255,255,0.8)',
    fontSize: '16px',
    fontFamily: "'Satoshi', sans-serif",
  },
  metaDot: {
    width: '4px',
    height: '4px',
    borderRadius: '50%',
    background: 'rgba(255,255,255,0.4)',
  },

  // Main content grid
  contentGrid: {
    display: 'grid',
    gridTemplateColumns: '1fr',
    gap: '24px',
  },

  // Card styles
  card: {
    background: 'rgba(255,255,255,0.03)',
    borderRadius: '20px',
    border: '1px solid rgba(255,255,255,0.06)',
    padding: '28px',
  },
  cardHeader: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: '20px',
  },
  cardTitle: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '13px',
    fontWeight: 600,
    textTransform: 'uppercase' as const,
    letterSpacing: '0.1em',
    color: 'rgba(255,255,255,0.4)',
    margin: 0,
  },
  editCardButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '6px',
    padding: '6px 12px',
    background: 'rgba(190,49,68,0.1)',
    border: '1px solid rgba(190,49,68,0.3)',
    borderRadius: '8px',
    color: '#f4a5b0',
    fontSize: '12px',
    fontWeight: 500,
    fontFamily: "'Satoshi', sans-serif",
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  },
  bioText: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '16px',
    lineHeight: 1.7,
    color: 'rgba(255,255,255,0.85)',
    whiteSpace: 'pre-wrap' as const,
  },

  // Tags/badges
  tagContainer: {
    display: 'flex',
    flexWrap: 'wrap' as const,
    gap: '10px',
  },
  tag: (variant: 'primary' | 'desire' | 'interest', isSelected?: boolean) => {
    const colors = {
      primary: {
        background: isSelected
          ? 'linear-gradient(135deg, rgba(190,49,68,0.4) 0%, rgba(190,49,68,0.3) 100%)'
          : 'linear-gradient(135deg, rgba(190,49,68,0.2) 0%, rgba(190,49,68,0.1) 100%)',
        border: isSelected
          ? '2px solid rgba(190,49,68,0.6)'
          : '1px solid rgba(190,49,68,0.3)',
        color: '#f4a5b0',
      },
      desire: {
        background: isSelected
          ? 'rgba(255,255,255,0.15)'
          : 'rgba(255,255,255,0.05)',
        border: isSelected
          ? '2px solid rgba(255,255,255,0.4)'
          : '1px solid rgba(255,255,255,0.1)',
        color: 'rgba(255,255,255,0.8)',
      },
      interest: {
        background: isSelected
          ? 'linear-gradient(135deg, rgba(16,185,129,0.3) 0%, rgba(16,185,129,0.2) 100%)'
          : 'linear-gradient(135deg, rgba(16,185,129,0.15) 0%, rgba(16,185,129,0.08) 100%)',
        border: isSelected
          ? '2px solid rgba(16,185,129,0.5)'
          : '1px solid rgba(16,185,129,0.25)',
        color: '#6ee7b7',
      },
    };
    return {
      ...colors[variant],
      padding: '10px 18px',
      borderRadius: '24px',
      fontSize: '14px',
      fontWeight: 500,
      fontFamily: "'Satoshi', sans-serif",
      cursor: 'pointer',
      transition: 'all 0.2s ease',
    };
  },

  // Photos section
  photosHeader: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: '20px',
  },
  photosTitle: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '22px',
    fontWeight: 600,
    color: '#ffffff',
  },
  photosCount: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '14px',
    fontWeight: 500,
    color: 'rgba(255,255,255,0.5)',
    background: 'rgba(255,255,255,0.05)',
    padding: '6px 14px',
    borderRadius: '20px',
  },
  photosGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(3, 1fr)',
    gap: '12px',
  },
  photoItem: {
    aspectRatio: '1',
    borderRadius: '16px',
    overflow: 'hidden',
    background: 'rgba(255,255,255,0.03)',
    cursor: 'pointer',
  },
  photoImage: {
    width: '100%',
    height: '100%',
    objectFit: 'cover' as const,
    transition: 'transform 0.5s ease',
  },

  // Empty states
  emptyState: {
    display: 'flex',
    flexDirection: 'column' as const,
    alignItems: 'center',
    justifyContent: 'center',
    padding: '80px 20px',
  },
  emptyIcon: {
    width: '80px',
    height: '80px',
    borderRadius: '50%',
    background: 'rgba(255,255,255,0.03)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: '24px',
  },
  emptyTitle: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '22px',
    fontWeight: 600,
    color: '#ffffff',
    marginBottom: '8px',
  },
  emptyText: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '15px',
    color: 'rgba(255,255,255,0.5)',
    textAlign: 'center' as const,
  },

  // Error state
  errorIcon: {
    width: '64px',
    height: '64px',
    borderRadius: '50%',
    background: 'rgba(239,68,68,0.1)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: '24px',
  },

  // Header with refresh button
  pageHeader: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: '24px',
  },
  pageTitle: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '28px',
    fontWeight: 700,
    color: '#ffffff',
    margin: 0,
  },
  headerButtons: {
    display: 'flex',
    gap: '12px',
  },
  refreshButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    padding: '10px 20px',
    background: 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.1)',
    borderRadius: '12px',
    color: 'rgba(255,255,255,0.8)',
    fontSize: '14px',
    fontWeight: 500,
    fontFamily: "'Satoshi', sans-serif",
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  },
  editButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    padding: '10px 20px',
    background: 'linear-gradient(135deg, #be3144 0%, #a02a3b 100%)',
    border: 'none',
    borderRadius: '12px',
    color: '#ffffff',
    fontSize: '14px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  },
  cancelButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    padding: '10px 20px',
    background: 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.1)',
    borderRadius: '12px',
    color: 'rgba(255,255,255,0.8)',
    fontSize: '14px',
    fontWeight: 500,
    fontFamily: "'Satoshi', sans-serif",
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  },
  saveButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    padding: '10px 24px',
    background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
    border: 'none',
    borderRadius: '12px',
    color: '#ffffff',
    fontSize: '14px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  },

  // Edit mode styles
  editTextarea: {
    width: '100%',
    minHeight: '120px',
    padding: '16px',
    background: 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.15)',
    borderRadius: '12px',
    color: 'rgba(255,255,255,0.9)',
    fontSize: '16px',
    lineHeight: 1.6,
    fontFamily: "'Satoshi', sans-serif",
    resize: 'vertical' as const,
    outline: 'none',
  },
  editLabel: {
    display: 'block',
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '14px',
    fontWeight: 500,
    color: 'rgba(255,255,255,0.6)',
    marginBottom: '8px',
  },
  editHint: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '12px',
    color: 'rgba(255,255,255,0.4)',
    marginTop: '8px',
  },
  selectableTag: {
    cursor: 'pointer',
    userSelect: 'none' as const,
  },

  // Toast notification
  toast: {
    position: 'fixed' as const,
    bottom: '100px',
    left: '50%',
    transform: 'translateX(-50%)',
    padding: '14px 24px',
    borderRadius: '12px',
    fontSize: '14px',
    fontWeight: 500,
    fontFamily: "'Satoshi', sans-serif",
    zIndex: 1000,
    animation: 'slideUp 0.3s ease',
  },
  toastSuccess: {
    background: 'linear-gradient(135deg, rgba(16,185,129,0.95) 0%, rgba(5,150,105,0.95) 100%)',
    color: '#ffffff',
  },
  toastError: {
    background: 'linear-gradient(135deg, rgba(239,68,68,0.95) 0%, rgba(220,38,38,0.95) 100%)',
    color: '#ffffff',
  },
};

interface EditFormState {
  bio: string;
  desires: string[];
  lookingFor: string[];
  connectionGoals: string[];
}

export function ProfilePage() {
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
  const [editForm, setEditForm] = useState<EditFormState>({
    bio: '',
    desires: [],
    lookingFor: [],
    connectionGoals: [],
  });

  const { data, loading, error, refetch } = useQuery(PROFILE_QUERY, {
    variables: { profileId: authManager.getProfileId() },
    fetchPolicy: 'network-only', // Always fetch from network, don't use cache
  });

  // lookingFor (and ageRange/distanceMax/recentlyOnline) live on the SearchSettings
  // query, not on Profile — the live app fetches them separately.
  const { data: searchSettingsData, refetch: refetchSearchSettings } = useQuery(
    SEARCH_SETTINGS_QUERY,
    {
      variables: { profileId: authManager.getProfileId() },
      fetchPolicy: 'network-only',
    }
  );

  const [updateProfile] = useMutation(PROFILE_UPDATE_MUTATION, {
    refetchQueries: [
      { query: PROFILE_QUERY, variables: { profileId: authManager.getProfileId() } },
      { query: SEARCH_SETTINGS_QUERY, variables: { profileId: authManager.getProfileId() } },
    ],
  });

  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      await refetch();
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleStartEdit = () => {
    const profile = data?.profile;
    const settings = searchSettingsData?.profile;
    if (profile) {
      setEditForm({
        bio: profile.bio || '',
        desires: profile.desires || [],
        lookingFor: settings?.lookingFor || [],
        connectionGoals: profile.connectionGoals || [],
      });
      setIsEditing(true);
    }
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditForm({
      bio: '',
      desires: [],
      lookingFor: [],
      connectionGoals: [],
    });
  };

  const handleSave = async () => {
    setIsSaving(true);
    try {
      const input: Record<string, any> = {};

      const profile = data?.profile;
      const settings = searchSettingsData?.profile;
      if (!profile) return;

      // Only include changed fields
      if (editForm.bio !== (profile.bio || '')) {
        input.bio = editForm.bio;
      }
      if (JSON.stringify(editForm.desires) !== JSON.stringify(profile.desires || [])) {
        input.desires = editForm.desires;
      }
      if (JSON.stringify(editForm.lookingFor) !== JSON.stringify(settings?.lookingFor || [])) {
        input.lookingFor = editForm.lookingFor;
      }
      if (JSON.stringify(editForm.connectionGoals) !== JSON.stringify(profile.connectionGoals || [])) {
        input.connectionGoals = editForm.connectionGoals;
      }

      if (Object.keys(input).length === 0) {
        setToast({ message: 'No changes to save', type: 'error' });
        setTimeout(() => setToast(null), 3000);
        return;
      }

      console.log('Updating profile with:', input);

      const result = await updateProfile({
        variables: { input },
      });

      console.log('Profile update result:', result);
      console.log('Updated profile data:', result.data?.profileUpdate);

      setToast({ message: 'Profile updated successfully!', type: 'success' });
      setIsEditing(false);
      // Force network fetch to bypass Apollo cache
      await refetch();
      const settingsResult = await refetchSearchSettings();
      console.log('Refetch search settings result:', settingsResult.data?.profile?.lookingFor);
    } catch (err: any) {
      console.error('Failed to update profile:', err);
      const errorMessage = err?.graphQLErrors?.[0]?.message || err?.message || 'Failed to update profile';
      setToast({ message: errorMessage, type: 'error' });
    } finally {
      setIsSaving(false);
      setTimeout(() => setToast(null), 3000);
    }
  };

  const toggleArrayItem = (field: 'desires' | 'lookingFor' | 'connectionGoals', item: string) => {
    setEditForm(prev => {
      const current = prev[field];
      const newValue = current.includes(item)
        ? current.filter(i => i !== item)
        : [...current, item];
      return { ...prev, [field]: newValue };
    });
  };

  if (loading) return <LoadingPage message="Loading your profile..." />;

  if (error) {
    return (
      <div style={styles.emptyState}>
        <div style={styles.errorIcon}>
          <svg viewBox="0 0 24 24" fill="none" stroke="#ef4444" strokeWidth="1.5" style={{ width: '32px', height: '32px' }}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
          </svg>
        </div>
        <h2 style={styles.emptyTitle}>Unable to Load Profile</h2>
        <p style={styles.emptyText}>{error.message}</p>
      </div>
    );
  }

  const profile = data?.profile;

  if (!profile) {
    return (
      <div style={styles.emptyState}>
        <div style={styles.emptyIcon}>
          <svg viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.3)" strokeWidth="1" style={{ width: '40px', height: '40px' }}>
            <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>
        <h2 style={styles.emptyTitle}>Profile Not Found</h2>
      </div>
    );
  }

  const primaryPhoto = getBestImageUrl(profile.photos?.[0]?.pictureUrls, 'large');

  return (
    <div style={styles.container}>
      {/* Toast Notification */}
      {toast && (
        <div style={{
          ...styles.toast,
          ...(toast.type === 'success' ? styles.toastSuccess : styles.toastError),
        }}>
          {toast.message}
        </div>
      )}

      {/* Header with Refresh/Edit */}
      <div style={styles.pageHeader}>
        <h1 style={styles.pageTitle}>My Profile</h1>
        <div style={styles.headerButtons}>
          {isEditing ? (
            <>
              <button
                onClick={handleCancelEdit}
                style={styles.cancelButton}
              >
                Cancel
              </button>
              <button
                onClick={handleSave}
                disabled={isSaving}
                style={{
                  ...styles.saveButton,
                  opacity: isSaving ? 0.6 : 1,
                }}
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ width: '16px', height: '16px' }}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                </svg>
                {isSaving ? 'Saving...' : 'Save Changes'}
              </button>
            </>
          ) : (
            <>
              <button
                onClick={handleRefresh}
                disabled={isRefreshing}
                style={{
                  ...styles.refreshButton,
                  opacity: isRefreshing ? 0.6 : 1,
                  cursor: isRefreshing ? 'not-allowed' : 'pointer',
                }}
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  style={{
                    width: '16px',
                    height: '16px',
                    animation: isRefreshing ? 'spin 1s linear infinite' : 'none',
                  }}
                >
                  <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
                </svg>
                {isRefreshing ? 'Refreshing...' : 'Refresh'}
              </button>
              <button onClick={handleStartEdit} style={styles.editButton}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ width: '16px', height: '16px' }}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
                </svg>
                Edit Profile
              </button>
            </>
          )}
        </div>
      </div>

      {/* Hero Section */}
      <div style={styles.heroSection}>
        <ProxiedImage
          src={primaryPhoto}
          alt={profile.imaginaryName}
          style={styles.heroImage}
          fallback={
            <div style={{
              width: '100%',
              height: '100%',
              background: 'linear-gradient(135deg, #1a1a1f 0%, #0a0a0c 100%)',
            }} />
          }
        />
        <div style={styles.heroOverlay} />
        <div style={styles.heroContent}>
          <div style={styles.heroNameRow}>
            <h1 style={styles.heroName}>{profile.imaginaryName}</h1>
            <div style={styles.badgeRow}>
              {profile.isMajestic && (
                <div style={styles.majesticBadge} title="Majestic Member">
                  <svg viewBox="0 0 24 24" fill="#ffffff" style={{ width: '18px', height: '18px' }}>
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                  </svg>
                </div>
              )}
              {profile.verificationStatus && (
                <div style={styles.verifiedBadge} title="Verified">
                  <svg viewBox="0 0 24 24" fill="#ffffff" style={{ width: '18px', height: '18px' }}>
                    <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.307zm7.007 6.387a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clipRule="evenodd" />
                  </svg>
                </div>
              )}
            </div>
          </div>
          <div style={styles.heroMeta}>
            <span style={{ fontWeight: 600 }}>{profile.age}</span>
            <div style={styles.metaDot} />
            <span>{typeof profile.gender === 'string' ? profile.gender : ''}</span>
            <div style={styles.metaDot} />
            <span>{typeof profile.sexuality === 'string' ? profile.sexuality : ''}</span>
          </div>
        </div>
      </div>

      {/* Content Grid */}
      <div style={styles.contentGrid}>
        {/* Bio */}
        <div style={styles.card}>
          <div style={styles.cardHeader}>
            <h3 style={styles.cardTitle}>About</h3>
          </div>
          {isEditing ? (
            <div>
              <label style={styles.editLabel}>Bio</label>
              <textarea
                style={styles.editTextarea}
                value={editForm.bio}
                onChange={(e) => setEditForm(prev => ({ ...prev, bio: e.target.value }))}
                placeholder="Tell others about yourself..."
              />
              <p style={styles.editHint}>Write something that reflects your personality</p>
            </div>
          ) : (
            <p style={styles.bioText}>{profile.bio || 'No bio yet'}</p>
          )}
        </div>

        {/* Looking For / Connection Goals */}
        <div style={styles.card}>
          <div style={styles.cardHeader}>
            <h3 style={styles.cardTitle}>Looking For (Connection Goals)</h3>
          </div>
          {isEditing ? (
            <div>
              <p style={styles.editHint}>Select what you're looking for</p>
              <div style={{ ...styles.tagContainer, marginTop: '12px' }}>
                {CONNECTION_GOAL_OPTIONS.map((goal) => (
                  <span
                    key={goal}
                    onClick={() => toggleArrayItem('connectionGoals', goal)}
                    style={{
                      ...styles.tag('primary', editForm.connectionGoals.includes(goal)),
                      ...styles.selectableTag,
                    }}
                  >
                    {goal.replace(/_/g, ' ')}
                  </span>
                ))}
              </div>
            </div>
          ) : (
            <div style={styles.tagContainer}>
              {(profile.connectionGoals && profile.connectionGoals.length > 0) ? (
                profile.connectionGoals.filter((g: any) => typeof g === 'string').map((goal: string) => (
                  <span key={goal} style={styles.tag('primary')}>
                    {goal.replace(/_/g, ' ')}
                  </span>
                ))
              ) : (
                <p style={{ ...styles.bioText, color: 'rgba(255,255,255,0.4)' }}>Not specified</p>
              )}
            </div>
          )}
        </div>

        {/* I'm Looking For (Profile Types) */}
        <div style={styles.card}>
          <div style={styles.cardHeader}>
            <h3 style={styles.cardTitle}>I'm Interested In</h3>
          </div>
          {isEditing ? (
            <div>
              <p style={styles.editHint}>Select who you want to see</p>
              <div style={{ ...styles.tagContainer, marginTop: '12px' }}>
                {LOOKING_FOR_OPTIONS.map((type) => (
                  <span
                    key={type}
                    onClick={() => toggleArrayItem('lookingFor', type)}
                    style={{
                      ...styles.tag('interest', editForm.lookingFor.includes(type)),
                      ...styles.selectableTag,
                    }}
                  >
                    {type.replace(/_/g, ' ')}
                  </span>
                ))}
              </div>
            </div>
          ) : (
            <div style={styles.tagContainer}>
              {(searchSettingsData?.profile?.lookingFor && searchSettingsData.profile.lookingFor.length > 0) ? (
                searchSettingsData.profile.lookingFor.map((type: string) => (
                  <span key={type} style={styles.tag('interest')}>
                    {type.replace(/_/g, ' ')}
                  </span>
                ))
              ) : (
                <p style={{ ...styles.bioText, color: 'rgba(255,255,255,0.4)' }}>Not specified</p>
              )}
            </div>
          )}
        </div>

        {/* Desires */}
        <div style={styles.card}>
          <div style={styles.cardHeader}>
            <h3 style={styles.cardTitle}>Desires</h3>
          </div>
          {isEditing ? (
            <div>
              <p style={styles.editHint}>Select your desires</p>
              <div style={{ ...styles.tagContainer, marginTop: '12px' }}>
                {DESIRE_OPTIONS.map((desire) => (
                  <span
                    key={desire}
                    onClick={() => toggleArrayItem('desires', desire)}
                    style={{
                      ...styles.tag('desire', editForm.desires.includes(desire)),
                      ...styles.selectableTag,
                    }}
                  >
                    {desire.replace(/_/g, ' ')}
                  </span>
                ))}
              </div>
            </div>
          ) : (
            <div style={styles.tagContainer}>
              {(profile.desires && profile.desires.length > 0) ? (
                profile.desires.filter((d: any) => typeof d === 'string').map((desire: string) => (
                  <span key={desire} style={styles.tag('desire')}>
                    {desire.replace(/_/g, ' ')}
                  </span>
                ))
              ) : (
                <p style={{ ...styles.bioText, color: 'rgba(255,255,255,0.4)' }}>Not specified</p>
              )}
            </div>
          )}
        </div>

        {/* Interests (read-only) */}
        {profile.interests && profile.interests.length > 0 && (
          <div style={styles.card}>
            <div style={styles.cardHeader}>
              <h3 style={styles.cardTitle}>Interests</h3>
            </div>
            <div style={styles.tagContainer}>
              {profile.interests.filter((i: any) => typeof i === 'string').map((interest: string) => (
                <span key={interest} style={styles.tag('interest')}>
                  {interest}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* Photos */}
        {profile.photos && profile.photos.length > 0 && (
          <div style={styles.card}>
            <div style={styles.photosHeader}>
              <h3 style={styles.photosTitle}>Photos</h3>
              <span style={styles.photosCount}>{profile.photos.length} photos</span>
            </div>
            <div style={styles.photosGrid}>
              {profile.photos.map((photo: any) => (
                <div key={photo.id} style={styles.photoItem}>
                  <ProxiedImage
                    src={getBestImageUrl(photo.pictureUrls, 'medium')}
                    alt=""
                    style={styles.photoImage}
                    fallback={
                      <div style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth="1" style={{ width: '32px', height: '32px' }}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z" />
                        </svg>
                      </div>
                    }
                  />
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
