import { gql } from '@apollo/client/core';

// ============================================================================
// Profile fragments — verbatim from live app v8.11.0 capture
// ============================================================================

export const PROFILE_LOCATION_FRAGMENT = gql`
  fragment ProfileLocationFragment on ProfileLocation {
    ... on DeviceLocation {
      device {
        latitude
        longitude
        geocode {
          city
          country
          __typename
        }
        __typename
      }
      __typename
    }
    ... on VirtualLocation {
      core
      __typename
    }
    ... on TeleportLocation {
      current: device {
        city
        country
        __typename
      }
      teleport {
        latitude
        longitude
        geocode {
          city
          country
          __typename
        }
        __typename
      }
      __typename
    }
    __typename
  }
`;

export const PICTURE_FRAGMENT = gql`
  fragment GetPictureUrlFragment on Picture {
    id
    publicId
    pictureIsSafe
    pictureIsPrivate
    pictureUrl
    pictureUrls {
      small
      medium
      large
      __typename
    }
    __typename
  }
`;

export const PHOTO_CAROUSEL_FRAGMENT = gql`
  fragment PhotoCarouselPictureFragment on Picture {
    id
    pictureIsPrivate
    pictureIsSafe
    pictureStatus
    pictureType
    pictureUrl
    pictureUrls {
      small
      medium
      large
      __typename
    }
    publicId
    verification {
      status
      __typename
    }
    __typename
  }
`;

export const PROFILE_INTERACTION_STATUS_FRAGMENT = gql`
  fragment ProfileInteractionStatusFragment on Profile {
    interactionStatus {
      message
      mine
      theirs
      __typename
    }
    __typename
  }
`;

export const ANALYTICS_PROFILE_FRAGMENT = gql`
  fragment AnalyticsProfileFragment on Profile {
    id
    isUplift
    lastSeen
    age
    gender
    sexuality
    verificationStatus
    connectionGoals
    hasHiddenBio
    hiddenBio
    imaginaryName
    interactionStatus {
      mine
      theirs
      message
      __typename
    }
    distance {
      km
      mi
      __typename
    }
    profilePairs {
      identityId
      __typename
    }
    metadata {
      source
      __typename
    }
    __typename
  }
`;

// Analytics fragment for the OWN profile (extra fields like analyticsId, lgbtqiaMode, lookingFor, etc.)
export const ANALYTICS_OWN_PROFILE_FRAGMENT = gql`
  ${PROFILE_LOCATION_FRAGMENT}
  fragment AnalyticsOwnProfileFragment on Profile {
    id
    age
    ageRange
    bio
    desires
    desiringFor
    analyticsId
    distanceMax
    hasHiddenBio
    hiddenBio
    interests
    isUplift
    recentlyOnline
    lgbtqiaMode
    isIncognito
    status
    isMajestic
    gender
    dateOfBirth
    lookingFor
    sexuality
    allowPWM
    enableChatContentModeration
    location {
      ...ProfileLocationFragment
      __typename
    }
    profilePairs {
      identityId
      __typename
    }
    __typename
  }
`;

export const DISCOVERY_ANALYTICS_METADATA_FRAGMENT = gql`
  fragment DiscoveryAnalyticsMetadata on Profile {
    metadata {
      source
      __typename
    }
    __typename
  }
`;

export const PARTNER_FRAGMENT = gql`
  ${PICTURE_FRAGMENT}
  ${PROFILE_INTERACTION_STATUS_FRAGMENT}
  fragment Partner on Partner {
    partnerId
    partnerLabel
    partnerProfile {
      id
      age
      imaginaryName
      dateOfBirth
      gender
      sexuality
      isIncognito
      photos {
        ...GetPictureUrlFragment
        __typename
      }
      ...ProfileInteractionStatusFragment
      status
      verificationStatus
      isMajestic
      __typename
    }
    partnerStatus
    __typename
  }
`;

export const CONSTELLATION_FRAGMENT = gql`
  ${PARTNER_FRAGMENT}
  fragment Constellation on Profile {
    constellation {
      ...Partner
      __typename
    }
    __typename
  }
`;

// Profile content fragment — what the app uses for ProfileQuery + DiscoverProfiles nodes
export const PROFILE_CONTENT_PROFILE_FRAGMENT = gql`
  ${PROFILE_LOCATION_FRAGMENT}
  ${PHOTO_CAROUSEL_FRAGMENT}
  ${CONSTELLATION_FRAGMENT}
  ${ANALYTICS_PROFILE_FRAGMENT}
  ${DISCOVERY_ANALYTICS_METADATA_FRAGMENT}
  fragment ProfileContentProfileFragment on Profile {
    bio
    hiddenBio
    hasHiddenBio
    age
    streamUserId
    dateOfBirth
    distance {
      km
      mi
      __typename
    }
    connectionGoals
    desires
    gender
    id
    status
    imaginaryName
    interactionStatus {
      message
      mine
      theirs
      __typename
    }
    interests
    isMajestic
    isIncognito
    lastSeen
    location {
      ...ProfileLocationFragment
      __typename
    }
    sexuality
    photos {
      ...PhotoCarouselPictureFragment
      __typename
    }
    ...Constellation
    allowPWM
    verificationStatus
    enableChatContentModeration
    ...AnalyticsProfileFragment
    ...DiscoveryAnalyticsMetadata
    isParticipantToEventChat
    __typename
  }
`;

// Likes-tab profile fragment — used by FilteredWhoLikesMe / pastLikes / pastDislikes
export const LIKES_PROFILE_FRAGMENT = gql`
  ${PROFILE_LOCATION_FRAGMENT}
  ${PHOTO_CAROUSEL_FRAGMENT}
  fragment LikesProfileFragment on Profile {
    id
    age
    gender
    status
    lastSeen
    desires
    connectionGoals
    isUplift
    sexuality
    isMajestic
    dateOfBirth
    streamUserId
    imaginaryName
    bio
    hiddenBio
    hasHiddenBio
    allowPWM
    interests
    verificationStatus
    interactionStatus {
      message
      mine
      theirs
      __typename
    }
    profilePairs {
      identityId
      __typename
    }
    distance {
      km
      mi
      __typename
    }
    location {
      ...ProfileLocationFragment
      __typename
    }
    photos {
      ...PhotoCarouselPictureFragment
      __typename
    }
    __typename
  }
`;

// ============================================================================
// Account / auth fragments — verbatim from live app
// ============================================================================

export const PICTURE_VERIFICATION_META_FRAGMENT = gql`
  fragment PictureVerificationMeta on Picture {
    id
    verification {
      status
      updatedAt
      sessionUrl
      failureReason
      attempts
      __typename
    }
    enrollment {
      sessionId
      status
      updatedAt
      failureReason
      __typename
    }
    __typename
  }
`;

export const CHAT_USER_FRAGMENT = gql`
  fragment ChatUser on Profile {
    id
    streamToken
    streamUserId
    __typename
  }
`;

export const APP_SETTINGS_OPTIONS_ACCOUNT_FRAGMENT = gql`
  fragment AppSettingsOptionsAccountFragment on Account {
    appSettings {
      receiveMarketingNotifications
      receiveNewsEmailNotifications
      receivePromotionsEmailNotifications
      receiveNewsPushNotifications
      receivePromotionsPushNotifications
      receiveNewConnectionPushNotifications
      receiveNewPingPushNotifications
      receiveNewMessagePushNotifications
      receiveNewLikePushNotifications
      __typename
    }
    __typename
  }
`;

export const AUTH_PROFILE_FRAGMENT = gql`
  ${PICTURE_VERIFICATION_META_FRAGMENT}
  ${PICTURE_FRAGMENT}
  ${CHAT_USER_FRAGMENT}
  ${ANALYTICS_OWN_PROFILE_FRAGMENT}
  fragment AuthProfile on Profile {
    imaginaryName
    verificationLimits {
      attemptsAvailable
      __typename
    }
    connectionGoals
    canVerify
    photos {
      pictureUrl
      pictureStatus
      ...PictureVerificationMeta
      ...GetPictureUrlFragment
      __typename
    }
    verificationStatus
    reflectionResponseIds
    ...ChatUser
    ...AnalyticsOwnProfileFragment
    showTerminatedConnectionBanner
    __typename
  }
`;

export const AUTH_PROVIDER_FRAGMENT = gql`
  ${APP_SETTINGS_OPTIONS_ACCOUNT_FRAGMENT}
  ${AUTH_PROFILE_FRAGMENT}
  fragment AuthProviderFragment on Account {
    id
    email
    analyticsId
    status
    createdAt
    isFinishedOnboarding
    isMajestic
    availablePings
    upliftExpirationTimestamp
    isUplift
    isDistanceInMiles
    language
    ageVerificationStatus
    verificationNumber
    challenges
    ...AppSettingsOptionsAccountFragment
    location {
      device {
        country
        __typename
      }
      __typename
    }
    profiles {
      ...AuthProfile
      __typename
    }
    __typename
  }
`;

// ============================================================================
// Search-settings fragment — used by SearchSettingsQuery + SearchSettingsUpdate
// ============================================================================

export const SEARCH_SETTINGS_PROFILE_FRAGMENT = gql`
  ${PROFILE_LOCATION_FRAGMENT}
  fragment SearchSettingsProfileFragment on Profile {
    id
    ageRange
    distanceMax
    desiringFor
    lookingFor
    location {
      ...ProfileLocationFragment
      __typename
    }
    recentlyOnline
    lgbtqiaMode
    __typename
  }
`;

// ============================================================================
// Queries — verbatim shape from live app v8.11.0
// ============================================================================

export const PROFILE_QUERY = gql`
  ${PROFILE_CONTENT_PROFILE_FRAGMENT}
  query ProfileQuery($profileId: String!) {
    profile(id: $profileId) {
      ...ProfileContentProfileFragment
      streamUserId
      __typename
    }
  }
`;

export const DISCOVER_PROFILES_QUERY = gql`
  ${PROFILE_CONTENT_PROFILE_FRAGMENT}
  ${CONSTELLATION_FRAGMENT}
  ${DISCOVERY_ANALYTICS_METADATA_FRAGMENT}
  query DiscoverProfiles($input: ProfileDiscoveryInput!) {
    discovery(input: $input) {
      nodes {
        ...ProfileContentProfileFragment
        ...DiscoveryAnalyticsMetadata
        ...Constellation
        streamUserId
        analyticsId
        age
        distance {
          km
          mi
          __typename
        }
        __typename
      }
      hasNextBatch
      feedGeneratedAt
      generatedWithProfileUpdatedAt
      feedSize
      feedCapacity
      __typename
    }
  }
`;

export const HEADER_SUMMARIES_QUERY = gql`
  query HeaderSummaries($limit: Int = 10, $cursor: String) {
    summaries: getChatSummariesForChatHeader(limit: $limit, cursor: $cursor) {
      nodes {
        id
        name
        type
        status
        avatarSet
        chatAvatarUrl
        chatDescription
        openedAt
        memberCount
        latestMessage
        streamChannelId
        targetProfileId
        targetProfile {
          isVerified
          isMajestic
          gender
          age
          sexuality
          __typename
        }
        enableChatContentModeration
        participationStatus
        participationType
        __typename
      }
      pageInfo {
        hasNextPage
        nextPageCursor
        __typename
      }
      __typename
    }
  }
`;

export const LIST_SUMMARIES_QUERY = gql`
  query ListSummaries($limit: Int = 10, $cursor: String) {
    summaries: getChatSummariesForChatList(limit: $limit, cursor: $cursor) {
      nodes {
        id
        name
        type
        status
        avatarSet
        chatAvatarUrl
        chatDescription
        openedAt
        memberCount
        latestMessage
        streamChannelId
        targetProfileId
        targetProfile {
          isVerified
          isMajestic
          gender
          age
          sexuality
          __typename
        }
        enableChatContentModeration
        participationStatus
        participationType
        __typename
      }
      pageInfo {
        hasNextPage
        nextPageCursor
        __typename
      }
      __typename
    }
  }
`;

export const GET_CHAT_SUMMARY_QUERY = gql`
  query GetChatSummary($streamChatId: String!) {
    summary: getChatSummary(streamChatId: $streamChatId) {
      id
      name
      type
      status
      avatarSet
      chatAvatarUrl
      chatDescription
      openedAt
      memberCount
      latestMessage
      streamChannelId
      targetProfileId
      targetProfile {
        isVerified
        isMajestic
        gender
        age
        sexuality
        __typename
      }
      enableChatContentModeration
      participationStatus
      participationType
      __typename
    }
  }
`;

// SearchSettingsQuery — own-profile search settings (the app fetches these
// separately from ProfileQuery, which doesn't include them).
export const SEARCH_SETTINGS_QUERY = gql`
  ${SEARCH_SETTINGS_PROFILE_FRAGMENT}
  query SearchSettingsQuery($profileId: String!) {
    profile(id: $profileId) {
      ...SearchSettingsProfileFragment
      __typename
    }
  }
`;

export const DISCOVER_SEARCH_SETTINGS_QUERY = gql`
  ${PROFILE_LOCATION_FRAGMENT}
  query DiscoverSearchSettingsQuery($profileId: String!) {
    profile(id: $profileId) {
      id
      status
      ageRange
      desiringFor
      desires
      distanceMax
      location {
        ...ProfileLocationFragment
        __typename
      }
      lookingFor
      recentlyOnline
      lgbtqiaMode
      allowPWM
      imaginaryName
      __typename
    }
  }
`;

export const AVAILABLE_DESIRES_QUERY = gql`
  query AvailableDesires($locale: String!, $version: Int) {
    desiresByCategoryLocalised(locale: $locale, version: $version) {
      category
      desires
      localisedCategory
      __typename
    }
  }
`;

export const IS_INCOGNITO_QUERY = gql`
  query IsIncognitoQuery($profileId: String!) {
    profile(id: $profileId) {
      id
      isIncognito
      __typename
    }
  }
`;

export const IS_PROFILE_VALID_QUERY = gql`
  query IsProfileValidQuery($profileId: String!) {
    profile(id: $profileId) {
      id
      status
      __typename
    }
  }
`;

export const LGBTQIA_MODE_CHECK_QUERY = gql`
  query LgbtqiaModeCheck($profileId: String!) {
    profile(id: $profileId) {
      id
      gender
      sexuality
      __typename
    }
  }
`;

export const UPLIFT_PURCHASE_QUERY = gql`
  query UpliftPurchaseQuery($profileId: String!) {
    profile(id: $profileId) {
      id
      status
      __typename
    }
  }
`;

export const PHOTO_SELECTOR_QUERY = gql`
  query PhotoSelectorQuery($profileId: String!) {
    profile(id: $profileId) {
      id
      photos {
        id
        pictureIsPrivate
        pictureIsSafe
        pictureOrder
        pictureStatus
        pictureType
        pictureUrl
        pictureUrls {
          small
          medium
          large
          __typename
        }
        publicId
        verification {
          status
          failureReason
          attempts
          __typename
        }
        enrollment {
          status
          failureReason
          __typename
        }
        __typename
      }
      __typename
    }
  }
`;

export const WLY_FILTERS_QUERY = gql`
  query WLYFiltersQuery($profileId: String!) {
    profile(id: $profileId) {
      id
      ageRange
      whoLikesMeFilters {
        ageRange
        desires
        lookingFor
        sexualities
        __typename
      }
      whoPingsMeFilters {
        ageRange
        __typename
      }
      __typename
    }
  }
`;

export const ANALYTICS_QUERY = gql`
  ${ANALYTICS_OWN_PROFILE_FRAGMENT}
  query AnalyticsQuery($profileId: String!) {
    account {
      id
      analyticsId
      __typename
    }
    profile(id: $profileId) {
      ...AnalyticsOwnProfileFragment
      __typename
    }
  }
`;

// Stream Chat credentials (own-profile streamToken)
export const STREAM_CREDENTIALS_QUERY = gql`
  query StreamCredentialsQuery($profileId: String!) {
    profile(id: $profileId) {
      id
      streamToken
      streamUserId
      imaginaryName
      __typename
    }
  }
`;

// AuthProviderQuery — fetches the full account snapshot via AuthProviderFragment.
// The live app uses this to populate its account state at startup.
export const AUTH_PROVIDER_QUERY = gql`
  ${AUTH_PROVIDER_FRAGMENT}
  query AuthProviderQuery {
    account {
      ...AuthProviderFragment
      __typename
    }
  }
`;

// AuthProviderStatusSyncQuery — incremental account/profile sync for status changes.
export const ACCOUNT_STATUS_QUERY = gql`
  ${PICTURE_FRAGMENT}
  ${PROFILE_INTERACTION_STATUS_FRAGMENT}
  ${CONSTELLATION_FRAGMENT}
  query AuthProviderStatusSyncQuery {
    account {
      id
      status
      isFinishedOnboarding
      isMajestic
      availablePings
      upliftExpirationTimestamp
      isUplift
      profiles {
        id
        profileLinks(linkType: PAIR) {
          linkId
          linkType
          profileId
          __typename
        }
        ...Constellation
        __typename
      }
      __typename
    }
  }
`;

// AppSettings — same shape as AuthProviderQuery (live app reuses the fragment).
export const APP_SETTINGS_QUERY = gql`
  ${AUTH_PROVIDER_FRAGMENT}
  query AppSettings {
    account {
      ...AuthProviderFragment
      __typename
    }
  }
`;

export const POPULAR_LOCATIONS_QUERY = gql`
  query PopularLocationsQuery {
    popularLocations {
      latitude
      longitude
      geocode {
        city
        country
        __typename
      }
      __typename
    }
  }
`;

export const GET_PROFILE_CONNECTIONS_QUERY = gql`
  ${PICTURE_FRAGMENT}
  query ProfileConnections($limit: Int = 25, $cursor: String) {
    connections: getProfileConnections(limit: $limit, cursor: $cursor) {
      nodes {
        imaginaryName
        isIncognito
        sexuality
        verificationStatus
        isMajestic
        age
        gender
        photos {
          ...GetPictureUrlFragment
          __typename
        }
        __typename
      }
      pageInfo {
        total
        hasNextPage
        nextPageCursor
        __typename
      }
      __typename
    }
  }
`;

export const REDEEMED_OFFERS_QUERY = gql`
  query RedeemedOffers {
    account {
      redeemedOffers {
        offerName
        redeemedAt
        __typename
      }
      __typename
    }
  }
`;

export const PROFILE_BY_STREAM_USER_ID_QUERY = gql`
  ${PICTURE_FRAGMENT}
  query ProfileByStreamUserId($streamUserId: String!) {
    profile: profileByStreamUserId(streamUserId: $streamUserId) {
      id
      age
      imaginaryName
      gender
      sexuality
      bio
      desires
      connectionGoals
      interests
      verificationStatus
      isMajestic
      photos {
        ...GetPictureUrlFragment
        __typename
      }
      __typename
    }
  }
`;

export const PROFILE_MATCHES_QUERY = gql`
  ${PICTURE_FRAGMENT}
  query ProfileMatches($profileId: String!, $limit: Int, $cursor: String) {
    profile(id: $profileId) {
      matches(limit: $limit, cursor: $cursor) {
        nodes {
          profile {
            id
            imaginaryName
            age
            gender
            sexuality
            bio
            desires
            connectionGoals
            interests
            verificationStatus
            isMajestic
            distance {
              km
              mi
              __typename
            }
            photos {
              ...GetPictureUrlFragment
              __typename
            }
            interactionStatus {
              mine
              theirs
              message
              __typename
            }
            __typename
          }
          chat {
            id
            streamChatId
            name
            type
            status
            __typename
          }
          __typename
        }
        pageInfo {
          total
          hasNextPage
          nextPageCursor
          __typename
        }
        __typename
      }
      __typename
    }
  }
`;

// hasLinkedReflection — operationName is lowercase to match live app exactly.
export const HAS_LINKED_REFLECTION_QUERY = gql`
  query hasLinkedReflection {
    hasLinkedReflection
  }
`;

// Note: the legacy WhoLikesMe / WhoPingsMe *queries* are no longer used.
// The live app uses FilteredWhoLikesMe / FilteredWhoPingsMe *mutations*
// (see mutations.ts). Don't add them back.
