// Mastodon-web-client-style URL shortening for visible link text. The
// underlying href (used by `openBrowserAsync(part.value)`) stays full; only
// the visible string the user sees is shortened. Server-side, Mastodon's
// `text_formatter.rb#shortened_link` does the cut at ~30 chars after the host
// — we mirror that defaults so links look the same as on mastodon.social.

const DISPLAY_PATH_BUDGET = 30

export interface FormattedLink {
  /** The original href — unchanged, used by openBrowserAsync. */
  href: string
  /** Punycode-as-is host (we don't decode IDN). Used for favicon caching. */
  host: string
  /** Display string for visible text: host + (optional) trimmed path + ellipsis. */
  display: string
}

export function formatLink(url: string): FormattedLink | null {
  let parsed: URL
  try {
    parsed = new URL(url)
  } catch {
    return null
  }
  if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return null

  const host = parsed.hostname.replace(/^www\./, '')
  const port = parsed.port ? `:${parsed.port}` : ''
  // Drop query + fragment in the visible form — the href keeps them.
  const path = parsed.pathname === '/' ? '' : parsed.pathname
  const hostPart = host + port

  let display: string
  if (path.length <= DISPLAY_PATH_BUDGET) {
    display = hostPart + path
  } else {
    display = hostPart + path.slice(0, DISPLAY_PATH_BUDGET).replace(/[\s/]+$/, '') + '…'
  }

  return { href: url, host, display }
}
