<script setup lang="ts">
import type { ChatArtifactLoader, ChatTimelineArtifactItem } from './types';

import { computed, ref } from 'vue';

const props = defineProps<{
  artifactLoader?: ChatArtifactLoader;
  item: ChatTimelineArtifactItem;
}>();

const downloading = ref(false);
const downloadError = ref('');

const downloadable = computed(
  () =>
    props.item.status === 'available' &&
    Boolean(props.item.downloadUrl) &&
    Boolean(props.artifactLoader),
);

function formatSize(value?: number) {
  const bytes = Number(value || 0);
  if (bytes <= 0) return '';
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${Math.ceil(bytes / 1024)} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

function fileType() {
  const extension = props.item.fileName.trim().split('.').pop()?.toUpperCase();
  if (extension && extension !== props.item.fileName.toUpperCase()) {
    return extension;
  }
  const mime = String(props.item.mimeType || '')
    .split('/')
    .pop();
  return mime ? mime.toUpperCase() : '文件';
}

const statusText = computed(() => {
  if (downloading.value) return '下载中';
  if (downloadError.value) return `${downloadError.value}，点击重试`;
  if (props.item.status === 'expired') return '已过期';
  if (props.item.status === 'delete_failed') return '删除失败';
  if (props.item.status === 'unavailable') return '不可用';
  return [fileType(), formatSize(props.item.size)].filter(Boolean).join(' · ');
});

function downloadTitle() {
  const hash = props.item.sha256 ? `\nSHA-256: ${props.item.sha256}` : '';
  if (downloadable.value) {
    return `${downloadError.value ? '重试下载' : '下载'} ${props.item.fileName}${hash}`;
  }
  return `${props.item.fileName}：${statusText.value}${hash}`;
}

function errorMessage(error: unknown) {
  return error instanceof Error && error.message.trim()
    ? error.message
    : '下载失败，请重试';
}

async function download() {
  if (!downloadable.value || downloading.value || !props.artifactLoader) {
    return;
  }
  downloading.value = true;
  downloadError.value = '';
  try {
    await props.artifactLoader(props.item);
  } catch (error) {
    downloadError.value = errorMessage(error);
  } finally {
    downloading.value = false;
  }
}
</script>

<template>
  <article
    class="chat-artifact"
    :class="[
      `is-${item.status.replaceAll('_', '-')}`,
      { 'has-download-error': Boolean(downloadError) },
    ]"
  >
    <button
      type="button"
      class="chat-artifact__main"
      :aria-label="
        downloadable
          ? `${downloadError ? '重试下载' : '下载'} ${item.fileName}`
          : `${item.fileName} ${statusText}`
      "
      :disabled="!downloadable || downloading"
      :title="downloadTitle()"
      @click="download"
    >
      <span class="chat-artifact__icon-box" aria-hidden="true">
        <span v-if="downloading" class="chat-artifact__spinner"></span>
        <svg v-else viewBox="0 0 24 24">
          <path d="M6.5 3.5h7l4 4v13h-11v-17Zm7 0v4h4" />
          <path d="M9 16.5h6M12 10v4m0 0 2-2m-2 2-2-2" />
        </svg>
      </span>
      <span class="chat-artifact__meta">
        <span class="chat-artifact__name">{{ item.fileName }}</span>
        <span class="chat-artifact__state">{{ statusText }}</span>
      </span>
      <span
        v-if="downloadable && !downloading"
        class="chat-artifact__action"
        aria-hidden="true"
      >
        {{ downloadError ? '重试' : '下载' }}
      </span>
    </button>
  </article>
</template>

<style scoped>
.chat-artifact {
  width: min(320px, 100%);
  min-width: 0;
  overflow: hidden;
  background: hsl(var(--surface-elevated));
  border-radius: var(--radius-toolbar);
  box-shadow: inset 0 0 0 1px hsl(var(--line-subtle));
  transition:
    background-color var(--motion-duration-fast) var(--motion-ease-standard),
    box-shadow var(--motion-duration-fast) var(--motion-ease-standard);
}

.chat-artifact.is-available:hover {
  background: hsl(var(--surface-subtle));
  box-shadow: inset 0 0 0 1px hsl(var(--border));
}

.chat-artifact.is-delete-failed,
.chat-artifact.has-download-error {
  box-shadow: inset 0 0 0 1px hsl(var(--destructive) / 46%);
}

.chat-artifact__main {
  display: flex;
  gap: var(--space-2);
  align-items: center;
  width: 100%;
  min-width: 0;
  min-height: 64px;
  padding: var(--space-2);
  color: inherit;
  text-align: left;
  cursor: pointer;
  background: transparent;
  border: 0;
}

.chat-artifact__main:disabled {
  cursor: default;
}

.chat-artifact__main:active:not(:disabled) {
  background: hsl(var(--surface-contrast-soft));
}

.chat-artifact__main:focus-visible {
  outline: 2px solid hsl(var(--primary));
  outline-offset: -2px;
}

.chat-artifact__icon-box {
  display: inline-flex;
  flex: 0 0 auto;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  color: hsl(var(--document-icon-foreground));
  background: hsl(var(--document-icon-generic));
  border-radius: var(--radius-control);
}

.chat-artifact__icon-box svg {
  width: 22px;
  height: 22px;
  fill: none;
  stroke: currentcolor;
  stroke-width: 1.8;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.chat-artifact__spinner {
  width: 18px;
  height: 18px;
  border: 2px solid hsl(var(--document-icon-foreground) / 38%);
  border-top-color: hsl(var(--document-icon-foreground));
  border-radius: 50%;
  animation: chat-artifact-spin 0.9s linear infinite;
}

.chat-artifact__meta {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-width: 0;
}

.chat-artifact__name {
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  font-weight: 600;
  line-height: 20px;
  color: hsl(var(--text-strong));
  white-space: nowrap;
}

.chat-artifact__state {
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 12px;
  line-height: 18px;
  color: hsl(var(--text-muted));
  white-space: nowrap;
}

.is-expired .chat-artifact__state,
.is-delete-failed .chat-artifact__state,
.has-download-error .chat-artifact__state {
  color: hsl(var(--destructive));
}

.chat-artifact__action {
  flex: 0 0 auto;
  min-width: 48px;
  padding-inline: var(--space-2);
  font-size: 13px;
  font-weight: 500;
  line-height: 32px;
  color: hsl(var(--primary));
  text-align: center;
}

@keyframes chat-artifact-spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 640px) {
  .chat-artifact {
    width: 100%;
  }
}

@media (prefers-reduced-motion: reduce) {
  .chat-artifact,
  .chat-artifact__spinner {
    transition: none;
    animation: none;
  }
}
</style>
