import type {
  Heading1,
  Heading2,
  Heading3,
  RichText,
  Text,
} from './interfaces'

function toSlug(text: string): string {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')
}

function extractHeadingText(
  heading?: Heading1 | Heading2 | Heading3,
): { text: string; slug: string } {
  const parts = heading?.RichTexts ?? []
  const plain = parts.map((r) => r.PlainText || r.Text?.Content || '').join('')
  const slug = toSlug(plain) || heading?.RichTexts?.[0]?.PlainText || ''
  return { text: plain, slug: slug || 'heading' }
}

export function buildHeadingId(
  heading?: Heading1 | Heading2 | Heading3,
): string {
  const { slug } = extractHeadingText(heading)
  return slug || 'heading'
}

export function isAmazonURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /amazon\.[a-z.]+|amzn\.to/.test(href)
}

export function isGitHubURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /github\.com/.test(href)
}

export function isTweetURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /twitter\.com|x\.com/.test(href)
}

export function isTikTokURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /tiktok\.com/.test(href)
}

export function isInstagramURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /instagram\.com/.test(href)
}

export function isPinterestURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /pinterest\.com|pin\.it/.test(href)
}

export function isCodePenURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /codepen\.io/.test(href)
}

export function isCircuitSimulatorAppletURL(
  url?: URL | string | null,
): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /falstad\.com\/circuit/.test(href)
}

export function isYouTubeURL(url?: URL | string | null): boolean {
  if (!url) return false
  const href = typeof url === 'string' ? url : url.toString()
  return /youtube\.com|youtu\.be/.test(href)
}

export function parseYouTubeVideoId(url?: URL | string | null): string {
  if (!url) return ''
  const target = typeof url === 'string' ? new URL(url) : url
  if (target.hostname.includes('youtu.be')) {
    return target.pathname.replace('/', '')
  }
  if (target.searchParams.has('v')) {
    return target.searchParams.get('v') || ''
  }
  const parts = target.pathname.split('/')
  return parts.pop() || ''
}

export function filePath(url: URL | string): string {
  return typeof url === 'string' ? url : url.toString()
}

export function getPostLink(slug: string): string {
  return `/blog/${slug}`
}

export function richTextToPlainText(richTexts: RichText[] = []): string {
  return richTexts
    .map((r) => r.PlainText || r.Text?.Content || '')
    .filter(Boolean)
    .join('')
}

export function getStaticFilePath(path: string): string {
  return `${path}`
}
export function buildText(
  content: string,
  link?: string,
  annotation?: Partial<RichText['Annotation']>,
): RichText {
  const text: Text = { Content: content }
  if (link) {
    text.Link = { Url: link }
  }
  return {
    Text: text,
    Annotation: {
      Bold: false,
      Italic: false,
      Strikethrough: false,
      Underline: false,
      Code: false,
      Color: 'default',
      ...(annotation || {}),
    },
    PlainText: content,
    Href: link,
  }
}

export function toNotionImageUrl(
  url: string,
  block?: { parent_table?: string; id?: string },
): string {
  if (!url) return url

  let notionUrl = url

  if (!url.startsWith('https://www.notion.so')) {
    notionUrl = 'https://www.notion.so'.concat(
      url.startsWith('/image') ? url : `/image/${encodeURIComponent(url)}`,
    )
  }

  try {
    const imageUrl = new URL(notionUrl)
    if (block) {
      const table = ['space', 'team'].includes(block.parent_table || '')
        ? 'block'
        : block.parent_table
      if (table) {
        imageUrl.searchParams.set('table', table)
      }
      if (block.id) {
        imageUrl.searchParams.set('id', block.id)
      }
      imageUrl.searchParams.set('cache', 'v2')
    }
    return imageUrl.toString()
  } catch (err) {
    console.error('toNotionImageUrl error:', err)
    return url
  }
}
