<template>
  <div class="p-8 max-w-4xl mx-auto">
    <h2 class="text-2xl font-bold 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 -->
    <div v-else-if="sharedDocs.length === 0" class="text-center py-12 text-gray-400">
      <p class="text-sm font-medium text-gray-500">No documents shared with you yet.</p>
      <p class="text-xs mt-1">When someone shares a document with you, it will appear here.</p>
    </div>

    <!-- 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">
            <svg class="w-5 h-5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
          </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'

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>
