<template>
  <div class="p-8 max-w-4xl mx-auto">
    <BreadcrumbBar :segments="[{ label: 'Shared with me' }]" :show-root="false" class="mb-4" />

    <h2 class="text-2xl font-semibold text-gray-900 mb-1">Shared with me</h2>
    <p class="text-gray-500 text-sm mb-6">Documents other users have shared with you.</p>

    <div v-if="loading" class="text-sm text-gray-400">Loading…</div>

    <!-- Empty state -->
    <EmptyState
      v-else-if="sharedDocs.length === 0"
      icon="inbox"
      headline="Nothing shared with you yet"
      subtext="When someone shares a document with you, it will appear here."
    />

    <!-- Shared documents list -->
    <div v-else class="grid gap-3">
      <div
        v-for="share in sharedDocs"
        :key="share.id"
        class="bg-white border border-gray-200 rounded-xl p-4 hover:border-indigo-300 hover:shadow-sm transition-all cursor-pointer"
        @click="$router.push(`/document/${share.document_id || share.id}`)"
      >
        <div class="flex items-start gap-3">
          <!-- Icon -->
          <div class="w-9 h-9 rounded-lg bg-indigo-50 flex items-center justify-center shrink-0 mt-0.5">
            <AppIcon name="document" class="w-5 h-5 text-indigo-500" />
          </div>

          <div class="flex-1 min-w-0">
            <p class="font-medium text-gray-900 text-sm truncate">
              {{ share.document?.original_name || share.filename || 'Document' }}
            </p>
            <p class="text-xs text-gray-400 mt-0.5">
              Shared by <span class="font-medium text-gray-600">{{ share.owner_handle || share.shared_by || '—' }}</span>
            </p>
            <p v-if="share.document?.created_at" class="text-xs text-gray-400 mt-0.5">
              {{ formatDate(share.document.created_at) }} · {{ formatSize(share.document.size_bytes) }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <p v-if="error" class="mt-4 text-sm text-red-600">{{ error }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as api from '../api/client.js'
import { formatDate, formatSize } from '../utils/formatters.js'
import AppIcon from '../components/ui/AppIcon.vue'
import BreadcrumbBar from '../components/ui/BreadcrumbBar.vue'
import EmptyState from '../components/ui/EmptyState.vue'

const sharedDocs = ref([])
const loading = ref(false)
const error = ref(null)

onMounted(async () => {
  loading.value = true
  error.value = null
  try {
    const data = await api.getSharedWithMe()
    sharedDocs.value = Array.isArray(data) ? data : (data.items ?? [])
  } catch (e) {
    error.value = e.message || 'Something went wrong. Please try again.'
  } finally {
    loading.value = false
  }
})

</script>
