<template>
  <div>
    <li
      class="py-3 transition duration-300 hover:bg-gray-50 dark:hover:bg-gray-800 items-start border-b border-gray-200 dark:border-gray-700"
    >
      <div class="flex flex-col mx-4 justify-center md:flex-row text-normal">
        <!-- Announcement icon or board number -->
        <div
          v-if="!showSelectBox"
          class="pr-4 md:pr-8 text-gray-400 hidden md:block"
        >
          <template v-if="item.announcement">
            <font-awesome-icon :icon="iconName" fade style="color: #990000" />
          </template>
          <template v-else>
            {{ item.boards_number }}
          </template>
        </div>

        <!-- Selection checkbox -->
        <label class="flex items-center space-x-2">
          <input
            v-if="showSelectBox"
            type="checkbox"
            :checked="selected"
            @change="selectItem"
            class="mr-8 inline-block text-gray-600 dark:text-white"
          />
        </label>

        <!-- Title link -->
        <NuxtLink
          :to="`${routeName}/${item.docId}`"
          class="cursor-pointer flex-1 pr-8 inline-block text-gray-600 dark:text-white hover:underline"
        >
          {{ truncateTitle(item.title) }}
        </NuxtLink>

        <!-- Display author only for Manager+ -->
        <div
          v-if="userRole >= ROLE_THRESHOLD.MANAGER"
          class="text-xs text-gray-400 flex items-center pr-4"
        >
          {{ userDisplayName }}
        </div>

        <!-- Date -->
        <div class="inline-block text-gray-400 text-left md:hidden">
          {{ formatDate(item.created) }}
        </div>
        <div class="hidden md:inline-block text-gray-400 text-left">
          {{ formatDate2(item.created) }}
        </div>
      </div>
    </li>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue';
import { fetchUserDisplayName } from '@/utils/boardUtils';
import { useUserStore } from '@/stores/user';
import { ROLE_THRESHOLD } from '@/data/config';
import type { BoardItem } from '@/types';

// Helper to normalize Firestore timestamp or other formats into JS Date
function toDate(raw: unknown): Date {
  if (typeof raw === 'string') {
    return new Date(raw);
  }
  if (
    raw &&
    typeof raw === 'object' &&
    'toDate' in (raw as any) &&
    typeof (raw as any).toDate === 'function'
  ) {
    return (raw as any).toDate();
  }
  const sec = (raw as any)?.seconds ?? (raw as any)?._seconds;
  if (typeof sec === 'number') {
    return new Date(sec * 1000);
  }
  return new Date();
}

// Props
const props = defineProps<{
  item: BoardItem;
  showSelectBox?: boolean;
  selected?: boolean;
  iconName?: [string, string];
  routeName: string;
}>();

const emit = defineEmits<{
  (e: 'select', item: BoardItem): void;
}>();

// Reactive state
const userStore = useUserStore();
const userRole = computed(() => userStore.userRole);
const userDisplayName = ref('');

// Title truncation length
const truncatedLength = ref(6);

// Date formatting
const formatDate = (raw: unknown) => {
  const d = toDate(raw);
  const YYYY = d.getFullYear();
  const MM = String(d.getMonth() + 1).padStart(2, '0');
  const DD = String(d.getDate()).padStart(2, '0');
  return `${YYYY}-${MM}-${DD}`;
};
const formatDate2 = (raw: unknown) => {
  const d = toDate(raw);
  const MM = String(d.getMonth() + 1).padStart(2, '0');
  const DD = String(d.getDate()).padStart(2, '0');
  return `${MM}-${DD}`;
};

// Title truncation based on screen width
const updateTruncatedLength = () => {
  const w = window.innerWidth / 14;
  truncatedLength.value = Math.round(Math.min(w, 60));
};
onMounted(() => {
  updateTruncatedLength();
  window.addEventListener('resize', updateTruncatedLength);
});
onBeforeUnmount(() => {
  window.removeEventListener('resize', updateTruncatedLength);
});
const truncateTitle = (t: string) =>
  t.length > truncatedLength.value
    ? t.slice(0, truncatedLength.value) + '…'
    : t;

// Fetch user display name for manager+
watch(
  () => props.item.userId,
  async (uid) => {
    if (uid && userRole.value >= ROLE_THRESHOLD.MANAGER) {
      userDisplayName.value = await fetchUserDisplayName(uid);
    } else {
      userDisplayName.value = uid || '';
    }
  },
  { immediate: true }
);

// Selection emit
const selectItem = () => {
  emit('select', props.item);
};
</script>
