import { computed, type ComputedRef } from 'vue'

import { privacyContentToHtml } from '../../lib/privacyContent'
import { simpleIconForKey } from '../../lib/socialIcons'
import type { OverviewResponse } from '../../types/awards'

export function useHomeSocialPresentation(siteContent: ComputedRef<OverviewResponse['siteContent']>) {
  const siteSocialLinks = computed(() =>
    (siteContent.value.socialLinks ?? [])
      .filter((social) => isSafePublicUrl(social?.url) && social.platform)
      .map((social) => ({
        label: social.label || social.platform || 'Social Link',
        platform: social.platform || 'link',
        icon: social.icon || '',
        url: social.url,
        showOnHost: social.showOnHost ?? true,
        showOnCommunity: social.showOnCommunity ?? true,
      })),
  )

  const hostSocialLinks = computed(() =>
    siteSocialLinks.value.filter((social) => social.showOnHost).slice(0, 3),
  )

  const communitySocialLinks = computed(() =>
    siteSocialLinks.value.filter((social) => social.showOnCommunity),
  )

  const footerLinks = computed(() =>
    (siteContent.value.footerLinks ?? []).filter((link) =>
      link?.label && (link.key === 'showacts' || isSafePublicUrl(link.url) || link.content),
    ),
  )

  const privacyContentHtml = computed(() => privacyContentToHtml(siteContent.value.privacyPolicyContent || ''))

  function platformKey(value: string | null | undefined) {
    return (value ?? 'link').trim().toLowerCase()
  }

  function isUploadedSocialIcon(icon: string | null | undefined) {
    return (icon ?? '').startsWith('data:image/')
  }

  function socialSimpleIconPath(platform: string | null | undefined) {
    return simpleIconForKey(platform)?.path ?? ''
  }

  function socialSimpleIconColor(platform: string | null | undefined) {
    return `#${simpleIconForKey(platform)?.hex ?? '5f44ad'}`
  }

  function isSafePublicUrl(value: string | null | undefined) {
    if (!value) return false

    try {
      const url = new URL(value)
      return url.protocol === 'http:' || url.protocol === 'https:'
    } catch {
      return false
    }
  }

  return {
    hostSocialLinks,
    communitySocialLinks,
    footerLinks,
    privacyContentHtml,
    platformKey,
    isUploadedSocialIcon,
    socialSimpleIconPath,
    socialSimpleIconColor,
  }
}
