---
import * as interfaces from '../../lib/interfaces'
import { filePath } from '../../lib/blog-helpers'
import Caption from './Caption.astro'

export interface Props {
  block: interfaces.Block
}

const { block }: Props = Astro.props

if (!block.File) {
  return null
}

let url: URL
try {
  const source = block.File.External?.Url || block.File.File?.Url
  if (!source) {
    throw new Error('Invalid file URL')
  }
  url = new URL(source)
} catch (err) {
  console.error(`Invalid file URL. error: ${err}`)
  url = null
}

const filename =
  url &&
  decodeURIComponent(url.pathname.split('/').slice(-1)[0] || '')
---

<div class="file">
  <div>
    {
      url && (
        <a
          href={block.File.External ? url.toString() : filePath(url)}
          target="_blank"
          rel="noopener noreferrer"
        >
          <img
            src="https://www.notion.so/icons/document_gray.svg"
            alt="File icon in a file block"
          />{' '}
          {filename}
        </a>
      )
    }
  </div>
  <Caption richTexts={block.File.Caption} />
</div>

<style>
  .file {
  }

  .file a {
    display: block;
    padding: 0.5rem 0.2rem 0.4rem;
    border-radius: var(--radius);
    color: var(--fg);
    font-weight: 500;
    line-height: 1.4rem;
  }
  .file a:hover {
    background-color: #eee;
  }

  .file a img {
    width: 1.3rem;
    height: 1.3rem;
    vertical-align: sub;
  }
</style>
