<template>
  <!-- Loading State -->
  <div v-if="loading" class="flex justify-center items-center py-16">
    <div class="text-center">
      <Spinner size="lg" class="mb-4" />
      <p class="text-gray-600">{{ t('groupDetailPage.loadingLabel', 'Loading household...') }}</p>
    </div>
  </div>

  <!-- Error State -->
  <Alert v-else-if="error" type="error" class="mb-6">
    <div class="flex items-center justify-between">
      <span>{{ error }}</span>
      <Button size="sm" color="error" @click="fetchGroupDetails">
        {{ t('groupDetailPage.retryButton', 'Retry') }}
      </Button>
    </div>
  </Alert>

  <!-- Main Content -->
  <div v-else-if="group" class="space-y-6">
    <!-- Header Section -->
    <div class="flex items-center justify-between">
      <div>
        <Heading :level="1" class="text-3xl font-black text-gray-900 mb-2">
          {{ group.name }}
        </Heading>
        <div class="flex items-center space-x-4">
          <div class="flex items-center text-sm text-gray-600">
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z" />
            </svg>
            {{ t('groupDetailPage.memberCount', { count: group.members?.length || 0 }) }}
          </div>
        </div>
      </div>

      <!-- Member Avatars & Actions -->
      <div class="flex items-center space-x-4">
        <!-- Member Avatars -->
        <div class="flex -space-x-2">
          <div v-for="member in group.members?.slice(0, 4)" :key="member.id" class="relative">
            <div
              class="w-10 h-10 rounded-full bg-gradient-to-br from-blue-400 to-purple-500 flex items-center justify-center text-white font-bold text-sm border-2 border-white cursor-pointer hover:scale-110 transition-transform"
              :title="member.email" @click="toggleMemberMenu(member.id)">
              {{ member.email.charAt(0).toUpperCase() }}
            </div>
          </div>
          <div v-if="(group.members?.length || 0) > 4"
            class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 font-bold text-sm border-2 border-white">
            +{{ (group.members?.length || 0) - 4 }}
          </div>

          <!-- Add Member Button -->
          <button @click="toggleInviteUI"
            class="w-10 h-10 rounded-full bg-white border-2 border-dashed border-gray-300 flex items-center justify-center text-gray-400 hover:text-blue-500 hover:border-blue-300 transition-colors">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
          </button>
        </div>

        <!-- Settings Button -->
        <Button variant="outline" size="sm" @click="goToSettings">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          </svg>
        </Button>
      </div>
    </div>

    <!-- Dashboard Grid -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- Personal Status Card -->
      <Card class="lg:col-span-1 p-6 bg-white border-3 border-gray-900 shadow-[6px_6px_0px_0px_#111]">
        <Heading :level="3" class="text-lg font-bold text-gray-900 mb-4 flex items-center">
          <svg class="w-5 h-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
          </svg>
          {{ t('groupDetailPage.personalStatus.title', 'Your Status') }}
        </Heading>

        <div class="space-y-4">
          <!-- Quick Win Suggestion -->
          <div class="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg">
            <h4 class="font-bold text-green-800 mb-2">{{ t('groupDetailPage.personalStatus.quickWin', 'Quick Win')
              }}</h4>
            <p class="text-sm text-green-700 mb-3">Complete a quick task to help your household</p>
            <Button size="sm" class="w-full">
              {{ t('groupDetailPage.personalStatus.takeAction', 'Take Action') }}
            </Button>
          </div>

          <!-- Financial Status -->
          <div class="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200 rounded-lg">
            <h4 class="font-bold text-blue-800 mb-2">{{ t('groupDetailPage.personalStatus.balance', 'Your Balance')
              }}</h4>
            <p class="text-2xl font-black text-blue-900">$0.00</p>
            <p class="text-sm text-blue-700">All settled up!</p>
          </div>
        </div>
      </Card>

      <!-- Main Content Area -->
      <div class="lg:col-span-2 space-y-6">
        <!-- Tabs for different sections -->
        <Tabs>
          <template #tabs>
            <div class="flex space-x-1 bg-gray-100 p-1 rounded-lg">
              <button v-for="tab in tabs" :key="tab.id" @click="activeTab = tab.id" :class="[
                'flex-1 py-2 px-4 text-sm font-medium rounded-md transition-colors',
                activeTab === tab.id
                  ? 'bg-white text-gray-900 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              ]">
                <div class="flex items-center justify-center space-x-2">
                  <span v-html="tab.icon"></span>
                  <span>{{ tab.label }}</span>
                </div>
              </button>
            </div>
          </template>

          <template #content>
            <!-- Chores Tab -->
            <div v-if="activeTab === 'chores'" class="space-y-4">
              <ChoresPage :group-id="groupId" />
            </div>

            <!-- Lists Tab -->
            <div v-if="activeTab === 'lists'" class="space-y-4">
              <ListsPage :group-id="groupId" />
            </div>

            <!-- Expenses Tab -->
            <div v-if="activeTab === 'expenses'" class="space-y-4">
              <ExpensesPage :group-id="groupId" />
            </div>

            <!-- Activity Tab -->
            <div v-if="activeTab === 'activity'" class="space-y-4">
              <Card class="p-6 bg-white border-3 border-gray-900 shadow-[6px_6px_0px_0px_#111]">
                <Heading :level="3" class="text-lg font-bold text-gray-900 mb-4">
                  {{ t('groupDetailPage.activityLog.title', 'Recent Activity') }}
                </Heading>

                <div v-if="groupHistoryLoading" class="flex justify-center py-8">
                  <Spinner size="sm" />
                </div>

                <div v-else-if="groupChoreHistory.length > 0" class="space-y-3">
                  <div v-for="entry in groupChoreHistory" :key="entry.id"
                    class="flex items-start space-x-3 p-3 bg-gray-50 rounded-lg">
                    <div class="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                      <svg class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M13 10V3L4 14h7v7l9-11h-7z" />
                      </svg>
                    </div>
                    <div class="flex-1 min-w-0">
                      <p class="text-sm text-gray-900">{{ formatHistoryEntry(entry) }}</p>
                      <p class="text-xs text-gray-500">{{ formatDistanceToNow(new Date(entry.timestamp), {
                        addSuffix: true
                      }) }}</p>
                    </div>
                  </div>
                </div>

                <div v-else class="text-center py-8 text-gray-500">
                  <svg class="w-12 h-12 mx-auto mb-4 text-gray-300" 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>
                  <p>{{ t('groupDetailPage.activityLog.emptyState', 'No recent activity') }}</p>
                </div>
              </Card>
            </div>
          </template>
        </Tabs>
      </div>
    </div>
  </div>

  <!-- Universal FAB -->
  <div class="fixed bottom-6 right-6 z-50">
    <Menu>
      <template #trigger>
        <Button size="lg"
          class="w-14 h-14 rounded-full shadow-[6px_6px_0px_0px_#111] hover:shadow-[8px_8px_0px_0px_#111] hover:-translate-y-1 transition-all duration-200">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        </Button>
      </template>

      <template #content>
        <div class="bg-white border-3 border-gray-900 shadow-[6px_6px_0px_0px_#111] rounded-lg p-2 min-w-48">
          <button @click="() => { }"
            class="w-full flex items-center space-x-3 px-4 py-3 text-left hover:bg-gray-50 rounded-lg transition-colors">
            <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
              </svg>
            </div>
            <div>
              <p class="font-medium text-gray-900">{{ t('groupDetailPage.fab.addExpense', 'Add Expense') }}</p>
              <p class="text-xs text-gray-500">{{ t('groupDetailPage.fab.addExpenseDesc', 'Split a bill or cost') }}
              </p>
            </div>
          </button>

          <button @click="() => { }"
            class="w-full flex items-center space-x-3 px-4 py-3 text-left hover:bg-gray-50 rounded-lg transition-colors">
            <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
              </svg>
            </div>
            <div>
              <p class="font-medium text-gray-900">{{ t('groupDetailPage.fab.completeChore', 'Complete Chore') }}
              </p>
              <p class="text-xs text-gray-500">{{ t('groupDetailPage.fab.completeChoreDesc', 'Mark a task as done')
                }}</p>
            </div>
          </button>

          <button @click="() => { }"
            class="w-full flex items-center space-x-3 px-4 py-3 text-left hover:bg-gray-50 rounded-lg transition-colors">
            <div class="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
            </div>
            <div>
              <p class="font-medium text-gray-900">{{ t('groupDetailPage.fab.addToList', 'Add to List') }}</p>
              <p class="text-xs text-gray-500">{{ t('groupDetailPage.fab.addToListDesc', 'Add item to list') }}
              </p>
            </div>
          </button>
        </div>
      </template>
    </Menu>
  </div>

  <!-- Member Menu Popup -->
  <div v-if="activeMemberMenu" ref="memberMenuRef"
    class="fixed z-50 bg-white border-3 border-gray-900 shadow-[6px_6px_0px_0px_#111] rounded-lg p-4 min-w-64"
    :style="memberMenuPosition">
    <div class="flex items-center justify-between mb-3">
      <Heading :level="4" class="text-sm font-bold text-gray-900">
        {{ getMemberById(activeMemberMenu)?.email || 'Unknown Member' }}
      </Heading>
      <Button variant="ghost" size="sm" @click="activeMemberMenu = null">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </Button>
    </div>

    <div class="space-y-2">
      <div class="flex items-center justify-between">
        <span class="text-sm text-gray-600">Role:</span>
        <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded">
          {{ getMemberById(activeMemberMenu)?.role || 'Member' }}
        </span>
      </div>

      <Button v-if="canRemoveMember(getMemberById(activeMemberMenu)!)" color="error" size="sm" class="w-full"
        @click="removeMember(activeMemberMenu!)" :disabled="removingMember === activeMemberMenu">
        <Spinner v-if="removingMember === activeMemberMenu" size="sm" class="mr-2" />
        {{ t('groupDetailPage.members.removeButton', 'Remove Member') }}
      </Button>
    </div>
  </div>

  <!-- Invite UI Popup -->
  <div v-if="showInviteUI" ref="inviteUIRef"
    class="fixed z-50 bg-white border-3 border-gray-900 shadow-[6px_6px_0px_0px_#111] rounded-lg p-6 min-w-80"
    :style="inviteUIPosition">
    <div class="flex items-center justify-between mb-4">
      <Heading :level="3" class="text-lg font-bold text-gray-900">
        {{ t('groupDetailPage.invites.title', 'Invite Members') }}
      </Heading>
      <Button variant="ghost" size="sm" @click="showInviteUI = false">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </Button>
    </div>

    <div class="space-y-4">
      <p class="text-sm text-gray-600">
        {{ inviteDescription }}
      </p>

      <Button @click="generateInviteCode" :disabled="generatingInvite" class="w-full">
        <Spinner v-if="generatingInvite" size="sm" class="mr-2" />
        {{ inviteCode ? t('groupDetailPage.invites.regenerateButton', 'Regenerate Code') :
          t('groupDetailPage.invites.generateButton', 'Generate Invite Code') }}
      </Button>

      <div v-if="inviteCode" class="p-4 bg-gray-50 border-2 border-gray-200 rounded-lg">
        <label class="block text-sm font-medium text-gray-700 mb-2">
          {{ t('groupDetailPage.invites.activeCodeLabel', 'Active Invite Code') }}
        </label>
        <div class="flex space-x-2">
          <Input v-model="inviteCode" readonly class="font-mono flex-1" />
          <Button variant="outline" @click="copyInviteCodeHandler">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2z" />
            </svg>
          </Button>
        </div>
        <p v-if="copySuccess" class="mt-2 text-sm text-green-600">
          {{ t('groupDetailPage.invites.copySuccess', 'Copied to clipboard!') }}
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { apiClient, API_ENDPOINTS } from '@/services/api';
import { useClipboard, useStorage } from '@vueuse/core';
import ListsPage from './ListsPage.vue';
import { useNotificationStore } from '@/stores/notifications';
import { choreService } from '../services/choreService'
import type { Chore, ChoreFrequency, ChoreAssignment, ChoreHistory, ChoreAssignmentHistory } from '../types/chore'
import { format, formatDistanceToNow, parseISO, startOfDay, isEqual, isToday as isTodayDate } from 'date-fns'

import { useAuthStore } from '@/stores/auth';
import {
  Button,
  Dialog,
  Input,
  Heading,
  Spinner,
  Alert,
  Listbox,
  Card,
  Tabs,
  Menu,
} from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import { onClickOutside } from '@vueuse/core'
import { groupService } from '../services/groupService';
import ChoresPage from './ChoresPage.vue';
import ExpensesPage from './ExpensesPage.vue';
import { useRouter } from 'vue-router';

const { t } = useI18n();

const inviteDescription = computed(() =>
  t('groupDetailPage.invites.description', 'Share this invite code with people you want to add to your household.')
);

const CACHE_DURATION = 5 * 60 * 1000;

interface CachedGroup { group: Group; timestamp: number; }
const cachedGroups = useStorage<Record<string, CachedGroup>>('cached-groups-v1', {});

interface CachedChores { chores: Chore[]; timestamp: number; }
const cachedUpcomingChores = useStorage<Record<string, CachedChores>>('cached-group-chores-v1', {});

interface Group {
  id: string | number;
  name: string;
  members?: GroupMember[];
}

interface GroupMember {
  id: number;
  email: string;
  role?: string;
}

const props = defineProps<{
  id: string;
}>();

const notificationStore = useNotificationStore();
const group = ref<Group | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);
const inviteCode = ref<string | null>(null);
const inviteExpiresAt = ref<string | null>(null);
const generatingInvite = ref(false);
const copySuccess = ref(false);
const removingMember = ref<number | null>(null);
const showInviteUI = ref(false);
const activeMemberMenu = ref<number | null>(null);

const memberMenuRef = ref(null)
const inviteUIRef = ref(null)
const addMemberButtonRef = ref(null)
const avatarsContainerRef = ref(null)

onClickOutside(memberMenuRef, () => {
  activeMemberMenu.value = null
}, { ignore: [avatarsContainerRef] })

onClickOutside(inviteUIRef, () => {
  showInviteUI.value = false
}, { ignore: [addMemberButtonRef] })

const groupId = computed(() => props.id);

const { copy, copied, isSupported: clipboardIsSupported } = useClipboard({
  source: computed(() => inviteCode.value || '')
});

const upcomingChores = ref<Chore[]>([])


const authStore = useAuthStore();



const showChoreDetailModal = ref(false);
const selectedChore = ref<Chore | null>(null);
const editingAssignment = ref<Partial<ChoreAssignment> | null>(null);

const showGenerateScheduleModal = ref(false);
const scheduleForm = reactive({
  start_date: '',
  end_date: '',
  member_ids: []
});
const generatingSchedule = ref(false);

const groupChoreHistory = ref<ChoreHistory[]>([]);
const groupHistoryLoading = ref(false);

const loadingAssignments = ref(false);
const selectedChoreAssignments = ref<ChoreAssignment[]>([]);

const router = useRouter();

const badgeClasses = (variant: string) => {
  const colorMap: Record<string, string> = {
    primary: 'bg-primary text-white',
    secondary: 'bg-secondary text-white',
    success: 'bg-green-500 text-white',
    warning: 'bg-yellow-500 text-white',
    danger: 'bg-red-500 text-white',
    neutral: 'bg-gray-500 text-white',
    info: 'bg-blue-500 text-white',
    accent: 'bg-purple-500 text-white'
  };
  return `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${colorMap[variant] || colorMap.neutral}`;
}

const getApiErrorMessage = (err: unknown, fallbackMessageKey: string): string => {
  if (err && typeof err === 'object') {
    if ('response' in err && err.response && typeof err.response === 'object' && 'data' in err.response && err.response.data) {
      const errorData = err.response.data as any;
      if (typeof errorData.detail === 'string') {
        return errorData.detail;
      }
      if (typeof errorData.message === 'string') {
        return errorData.message;
      }
      if (Array.isArray(errorData.detail) && errorData.detail.length > 0) {
        const firstError = errorData.detail[0];
        if (typeof firstError.msg === 'string' && typeof firstError.type === 'string') {
          return firstError.msg;
        }
      }
      if (typeof errorData === 'string') {
        return errorData;
      }
    }
    if (err instanceof Error && err.message) {
      return err.message;
    }
  }
  return t(fallbackMessageKey);
};

const fetchActiveInviteCode = async () => {
  if (!groupId.value) return;
  try {
    const response = await apiClient.get(API_ENDPOINTS.GROUPS.GET_ACTIVE_INVITE(String(groupId.value)));
    if (response.data && response.data.code) {
      inviteCode.value = response.data.code;
      inviteExpiresAt.value = response.data.expires_at;
    } else {
      inviteCode.value = null;
      inviteExpiresAt.value = null;
    }
  } catch (err: any) {
    if (err.response && err.response.status === 404) {
      inviteCode.value = null;
      inviteExpiresAt.value = null;
      console.info(t('groupDetailPage.console.noActiveInvite'));
    } else {
      const message = err instanceof Error ? err.message : t('groupDetailPage.errors.failedToFetchActiveInvite');
      console.error('Error fetching active invite code:', err);
      notificationStore.addNotification({ message, type: 'error' });
    }
  }
};

const fetchGroupDetails = async () => {
  if (!groupId.value) return;
  const groupIdStr = String(groupId.value);
  const cached = cachedGroups.value[groupIdStr];

  if (cached) {
    group.value = cached.group;
    loading.value = false;
  } else {
    loading.value = true;
  }

  error.value = null;
  try {
    const response = await apiClient.get(API_ENDPOINTS.GROUPS.BY_ID(groupIdStr));
    group.value = response.data;
    cachedGroups.value[groupIdStr] = {
      group: response.data,
      timestamp: Date.now(),
    };
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : t('groupDetailPage.errors.failedToFetchGroupDetails');
    if (!group.value) {
      error.value = message;
    }
    console.error('Error fetching group details:', err);
    notificationStore.addNotification({ message, type: 'error' });
  } finally {
    if (loading.value) {
      loading.value = false;
    }
  }
  await fetchActiveInviteCode();
};

const generateInviteCode = async () => {
  if (!groupId.value) return;
  generatingInvite.value = true;
  copySuccess.value = false;
  try {
    const response = await apiClient.post(API_ENDPOINTS.GROUPS.CREATE_INVITE(String(groupId.value)));
    if (response.data && response.data.code) {
      inviteCode.value = response.data.code;
      inviteExpiresAt.value = response.data.expires_at;
      notificationStore.addNotification({ message: t('groupDetailPage.notifications.generateInviteSuccess'), type: 'success' });
    } else {
      throw new Error(t('groupDetailPage.invites.errors.newDataInvalid'));
    }
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : t('groupDetailPage.notifications.generateInviteError');
    console.error('Error generating invite code:', err);
    notificationStore.addNotification({ message, type: 'error' });
  } finally {
    generatingInvite.value = false;
  }
};

const copyInviteCodeHandler = async () => {
  if (!clipboardIsSupported.value || !inviteCode.value) {
    notificationStore.addNotification({ message: t('groupDetailPage.notifications.clipboardNotSupported'), type: 'warning' });
    return;
  }
  await copy(inviteCode.value);
  if (copied.value) {
    copySuccess.value = true;
    setTimeout(() => (copySuccess.value = false), 2000);
  } else {
    notificationStore.addNotification({ message: t('groupDetailPage.notifications.copyInviteFailed'), type: 'error' });
  }
};

const canRemoveMember = (member: GroupMember): boolean => {
  const isOwner = group.value?.members?.find(m => m.id === member.id)?.role === 'owner';
  return !isOwner;
};

const removeMember = async (memberId: number) => {
  if (!groupId.value) return;

  removingMember.value = memberId;
  try {
    await apiClient.delete(API_ENDPOINTS.GROUPS.MEMBER(String(groupId.value), String(memberId)));
    await fetchGroupDetails();
    notificationStore.addNotification({
      message: t('groupDetailPage.notifications.removeMemberSuccess'),
      type: 'success'
    });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : t('groupDetailPage.notifications.removeMemberFailed');
    console.error('Error removing member:', err);
    notificationStore.addNotification({ message, type: 'error' });
  } finally {
    removingMember.value = null;
  }
};

const loadUpcomingChores = async () => {
  if (!groupId.value) return
  const groupIdStr = String(groupId.value);
  const cached = cachedUpcomingChores.value[groupIdStr];

  if (cached) {
    upcomingChores.value = cached.chores;
  }

  try {
    const chores = await choreService.getChores(Number(groupId.value))
    const sortedChores = chores
      .sort((a, b) => new Date(a.next_due_date).getTime() - new Date(b.next_due_date).getTime())
      .slice(0, 5)
    upcomingChores.value = sortedChores;
    cachedUpcomingChores.value[groupIdStr] = {
      chores: sortedChores,
      timestamp: Date.now()
    };
  } catch (error) {
    console.error(t('groupDetailPage.errors.failedToLoadUpcomingChores'), error)
  }
}

const formatDate = (date: string) => {
  return format(new Date(date), 'MMM d, yyyy')
}

const getDueDateStatus = (chore: Chore) => {
  const today = startOfDay(new Date());
  const dueDate = startOfDay(new Date(chore.next_due_date));

  if (dueDate < today) return 'overdue';
  if (isEqual(dueDate, today)) return 'due-today';
  return 'upcoming';
}

const getChoreStatusInfo = (chore: Chore) => {
  const currentAssignment = chore.assignments && chore.assignments.length > 0 ? chore.assignments[0] : null;
  const isCompleted = currentAssignment?.is_complete ?? false;
  const assignedUser = currentAssignment?.assigned_user;
  const dueDateStatus = getDueDateStatus(chore);

  return {
    currentAssignment,
    isCompleted,
    assignedUser,
    dueDateStatus,
    assignedUserName: assignedUser?.name || assignedUser?.email || 'Unassigned'
  };
}

const formatFrequency = (frequency: ChoreFrequency) => {
  const options: Record<ChoreFrequency, string> = {
    one_time: t('choresPage.frequencyOptions.oneTime'),
    daily: t('choresPage.frequencyOptions.daily'),
    weekly: t('choresPage.frequencyOptions.weekly'),
    monthly: t('choresPage.frequencyOptions.monthly'),
    custom: t('choresPage.frequencyOptions.custom')
  };
  return options[frequency] || frequency;
};

const getFrequencyBadgeVariant = (frequency: ChoreFrequency) => {
  const colorMap: Record<ChoreFrequency, string> = {
    one_time: 'neutral',
    daily: 'info',
    weekly: 'success',
    monthly: 'accent',
    custom: 'warning'
  };
  return colorMap[frequency] || 'secondary';
};









const toggleMemberMenu = (memberId: number) => {
  if (activeMemberMenu.value === memberId) {
    activeMemberMenu.value = null;
  } else {
    activeMemberMenu.value = memberId;
    showInviteUI.value = false;
  }
};

const toggleInviteUI = () => {
  showInviteUI.value = !showInviteUI.value;
  if (showInviteUI.value) {
    activeMemberMenu.value = null;
  }
};

const openChoreDetailModal = async (chore: Chore) => {
  selectedChore.value = chore;
  showChoreDetailModal.value = true;

  loadingAssignments.value = true;
  try {
    selectedChoreAssignments.value = await choreService.getChoreAssignments(chore.id);
  } catch (error) {
    console.error('Failed to load chore assignments:', error);
    notificationStore.addNotification({
      message: 'Failed to load chore assignments.',
      type: 'error'
    });
  } finally {
    loadingAssignments.value = false;
  }

  if (!chore.history || chore.history.length === 0) {
    try {
      const history = await choreService.getChoreHistory(chore.id);
      selectedChore.value = {
        ...selectedChore.value,
        history: history
      };
    } catch (error) {
      console.error('Failed to load chore history:', error);
      notificationStore.addNotification({
        message: 'Failed to load chore history.',
        type: 'error'
      });
    }
  }
};

const startAssignmentEdit = (assignment: ChoreAssignment) => {
  editingAssignment.value = { ...assignment, due_date: format(new Date(assignment.due_date), 'yyyy-MM-dd') };
};

const cancelAssignmentEdit = () => {
  editingAssignment.value = null;
};

const saveAssignmentEdit = async (assignmentId: number) => {
  if (!editingAssignment.value || !editingAssignment.value.due_date) {
    notificationStore.addNotification({ message: 'Due date is required.', type: 'error' });
    return;
  }
  try {
    const updatedAssignment = await choreService.updateAssignment(assignmentId, {
      due_date: editingAssignment.value.due_date,
      assigned_to_user_id: editingAssignment.value.assigned_to_user_id
    });
    loadUpcomingChores();
    cancelAssignmentEdit();
    notificationStore.addNotification({ message: 'Assignment updated', type: 'success' });
  } catch (error) {
    notificationStore.addNotification({ message: 'Failed to update assignment', type: 'error' });
  }
};

const handleGenerateSchedule = async () => {
  generatingSchedule.value = true;
  try {
    await groupService.generateSchedule(String(groupId.value), scheduleForm);
    notificationStore.addNotification({ message: 'Schedule generated successfully', type: 'success' });
    showGenerateScheduleModal.value = false;
    loadUpcomingChores();
  } catch (error) {
    notificationStore.addNotification({ message: 'Failed to generate schedule', type: 'error' });
  } finally {
    generatingSchedule.value = false;
  }
};

const loadGroupChoreHistory = async () => {
  if (!groupId.value) return;
  groupHistoryLoading.value = true;
  try {
    groupChoreHistory.value = await groupService.getGroupChoreHistory(String(groupId.value));
  } catch (err) {
    console.error("Failed to load group chore history", err);
    notificationStore.addNotification({ message: 'Could not load group activity.', type: 'error' });
  } finally {
    groupHistoryLoading.value = false;
  }
};

const formatHistoryEntry = (entry: ChoreHistory | ChoreAssignmentHistory): string => {
  const user = entry.changed_by_user?.email || 'System';
  const eventType = entry.event_type.toLowerCase().replace(/_/g, ' ');

  let action = '';
  switch (entry.event_type) {
    case 'created':
      action = 'created this chore';
      break;
    case 'updated':
      action = 'updated this chore';
      break;
    case 'completed':
      action = 'completed the assignment';
      break;
    case 'reopened':
      action = 'reopened the assignment';
      break;
    case 'assigned':
      action = 'was assigned to this chore';
      break;
    case 'unassigned':
      action = 'was unassigned from this chore';
      break;
    case 'reassigned':
      action = 'was reassigned this chore';
      break;
    case 'due_date_changed':
      action = 'changed the due date';
      break;
    case 'deleted':
      action = 'deleted this chore';
      break;
    default:
      action = eventType;
  }

  let details = '';
  if (entry.event_data) {
    const changes = Object.entries(entry.event_data).map(([key, value]) => {
      if (typeof value === 'object' && value !== null && 'old' in value && 'new' in value) {
        const fieldName = key.replace(/_/g, ' ');
        return `${fieldName}: "${value.old}" → "${value.new}"`;
      }
      return `${key}: ${JSON.stringify(value)}`;
    });
    if (changes.length > 0) {
      details = ` (${changes.join(', ')})`;
    }
  }

  return `${user} ${action}${details}`;
};

const isAssignmentOverdue = (assignment: ChoreAssignment): boolean => {
  const dueDate = new Date(assignment.due_date);
  const today = startOfDay(new Date());
  return dueDate < today;
};

function goToSettings() {
  if (groupId.value) {
    router.push(`/groups/${groupId.value}/settings`);
  }
}

onMounted(() => {
  fetchGroupDetails();
  loadUpcomingChores();
  loadGroupChoreHistory();
});

// UI State for new template
const activeTab = ref('chores');
const memberMenuPosition = ref({});
const inviteUIPosition = ref({});

// Tabs configuration
const tabs = ref([
  {
    id: 'chores',
    label: t('groupDetailPage.tabs.chores', 'Chores'),
    icon: '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg>'
  },
  {
    id: 'lists',
    label: t('groupDetailPage.tabs.lists', 'Lists'),
    icon: '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg>'
  },
  {
    id: 'expenses',
    label: t('groupDetailPage.tabs.expenses', 'Expenses'),
    icon: '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"></path></svg>'
  },
  {
    id: 'activity',
    label: t('groupDetailPage.tabs.activity', 'Activity'),
    icon: '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>'
  }
]);

const getMemberById = (memberId: number): GroupMember | undefined => {
  return group.value?.members?.find(m => m.id === memberId);
};
</script>

<style scoped>
.page-padding {
  padding: 1rem;
  padding-block-end: 3rem;
  max-width: 1200px;
  margin: 0 auto;
}

.mt-1 {
  margin-top: 0.5rem;
}

.mt-2 {
  margin-top: 1rem;
}

.mt-3 {
  margin-top: 1.5rem;
}

.mt-4 {
  margin-top: 2rem;
}

.mb-3 {
  margin-bottom: 1.5rem;
}

.ml-1 {
  margin-left: 0.25rem;
}

.w-full {
  width: 100%;
}

.neo-section-container {
  border: 3px solid #111;
  border-radius: 18px;
  background: rgb(255, 248, 240);
  box-shadow: 6px 6px 0 #111;
  overflow: hidden;
}

.neo-section {
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
}

.neo-section:last-child {
  border-bottom: none;
}

.neo-section-header {
  font-weight: 900;
  font-size: 1.25rem;
  margin: 0;
  margin-bottom: 1rem;
  letter-spacing: 0.5px;
}

.neo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 0;
  border-bottom: 1px solid #eee;
}

.neo-grid .neo-section {
  border-bottom: none;
}

.neo-grid .neo-section:first-child {
  border-right: 1px solid #eee;
}

@media (max-width: 620px) {
  .neo-grid {
    grid-template-columns: 1fr;
  }

  .neo-grid .neo-section:first-child {
    border-right: none;
    border-bottom: 1px solid #eee;
  }
}

.member-avatar-list {
  display: flex;
  align-items: flex-end;
}

.member-avatars {
  display: flex;
  padding-left: 12px;
}

.member-avatar {
  position: relative;
  margin-left: -12px;
}

.avatar-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: var(--primary);
  color: var(--dark);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 900;
  border: 2px solid var(--light);
  cursor: pointer;
  transition: transform 0.2s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.avatar-circle:hover {
  transform: scale(1.1);
  z-index: 10;
}

.member-menu {
  position: absolute;
  top: 110%;
  right: -10px;
  background: white;
  border-radius: 8px;
  border: 2px solid var(--dark);
  box-shadow: var(--shadow-md);
  width: 220px;
  z-index: 100;
  overflow: hidden;
  /* padding: 0.5rem; */
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 0.5rem 0.5rem 1rem;
  border-bottom: 2px solid #eee;
}

.member-menu-content {
  padding: 0.75rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.add-member-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: var(--light);
  border: 2px dashed var(--dark);
  color: var(--dark);
  font-size: 1.5rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  margin-left: -8px;
  z-index: 1;
}

.add-member-btn:hover {
  background: var(--secondary);
  transform: scale(1.1);
  border-style: solid;
}

.header-title-text {
  margin: 0;
}

.invite-popup {
  position: absolute;
  top: calc(16%);
  right: 10%;
  width: 27%;
  background: white;
  border-radius: 12px;
  border: 2px solid var(--dark);
  box-shadow: var(--shadow-md);
  z-index: 100;
  padding: 0.75rem;
}

/* Members List Styles */
.neo-members-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.neo-member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-radius: 12px;
  background: #fafafa;
  border: 2px solid #111;
  transition: transform 0.1s ease-in-out;
}

.neo-member-item:hover {
  transform: translateY(-2px);
}

.neo-member-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.neo-member-name {
  font-weight: 600;
  font-size: 1.1rem;
}

.neo-member-role {
  font-size: 0.875rem;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  background: #e0e0e0;
  font-weight: 600;
}

.neo-member-role.owner {
  background: #111;
  color: white;
}

/* Invite Code Styles */
.neo-invite-code {
  background: #fafafa;
  padding: 1rem;
  border-radius: 12px;
  border: 2px solid #111;
}

.neo-label {
  display: block;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.neo-input-group {
  display: flex;
  gap: 0.5rem;
}

.neo-input {
  flex: 1;
  padding: 0.75rem;
  border: 2px solid #111;
  border-radius: 8px;
  font-family: monospace;
  font-size: 1rem;
  background: white;
}

.neo-success-text {
  color: var(--success);
  font-size: 0.9rem;
  font-weight: 600;
  margin-top: 0.5rem;
}

/* Empty State Styles */
.neo-empty-state {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.neo-empty-state .icon {
  width: 3rem;
  height: 3rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

/* Responsive Adjustments */
@media (max-width: 900px) {
  .neo-grid {
    /* The gap is removed to allow for border-based separators */
  }
}

@media (max-width: 600px) {
  .page-padding {
    padding: 0.5rem;
  }

  .neo-member-item {
    flex-direction: column;
    gap: 0.75rem;
    align-items: flex-start;
  }

  .neo-member-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}

/* Chores List Styles */
.neo-chores-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.neo-chore-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-radius: 12px;
  background: #fafafa;
  border: 2px solid #111;
  transition: transform 0.1s ease-in-out;
}

.neo-chore-item:hover {
  transform: translateY(-2px);
}

.neo-chore-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.neo-chore-name {
  font-weight: 600;
  font-size: 1.1rem;
}

.neo-chore-due {
  font-size: 0.875rem;
  color: #666;
}

/* Expenses List Styles */
.neo-expenses-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.neo-expense-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-radius: 12px;
  background: #fafafa;
  border: 2px solid #111;
  transition: transform 0.1s ease-in-out;
}

.neo-expense-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.neo-expense-name {
  font-weight: 600;
  font-size: 1.1rem;
}

.neo-expense-date {
  font-size: 0.875rem;
  color: #666;
}

.neo-expense-details {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.neo-expense-amount {
  font-weight: 600;
  font-size: 1.1rem;
}

.neo-chip {
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.875rem;
  font-weight: 600;
  background: #e0e0e0;
}

.neo-chip.blue {
  background: #e3f2fd;
  color: #1976d2;
}

.neo-chip.green {
  background: #e8f5e9;
  color: #2e7d32;
}

.neo-chip.purple {
  background: #f3e5f5;
  color: #7b1fa2;
}

.neo-chip.orange {
  background: #fff3e0;
  color: #f57c00;
}

.neo-chip.teal {
  background: #e0f2f1;
  color: #00796b;
}

.neo-chip.grey {
  background: #f5f5f5;
  color: #616161;
}

.neo-expense-list {
  background-color: rgb(255, 248, 240);
  /* Container for expense items */
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #f0e5d8;
}

.neo-expense-item-wrapper {
  border-bottom: 1px solid #f0e5d8;
  margin-bottom: 0.5rem;
}

.neo-expense-item-wrapper:last-child {
  border-bottom: none;
}

.neo-expense-item {
  padding: 1rem 1.2rem;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.2s ease;
}

.neo-expense-item:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.neo-expense-item.is-expanded .expense-toggle-icon {
  transform: rotate(180deg);
}

.expense-main-content {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.expense-icon-container {
  color: #d99a53;
}

.expense-text-content {
  display: flex;
  flex-direction: column;
}

.expense-side-content {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.expense-toggle-icon {
  color: #888;
  transition: transform 0.3s ease;
}

.neo-expense-header {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0.1rem;
}

.neo-expense-details,
.neo-split-details {
  font-size: 0.9rem;
  color: #555;
  margin-bottom: 0.3rem;
}

.neo-expense-details strong,
.neo-split-details strong {
  color: #111;
}

.neo-expense-status {
  display: inline-block;
  padding: 0.25em 0.6em;
  font-size: 0.85em;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
  border-radius: 0.375rem;
  margin-left: 0.5rem;
  color: #22c55e;
}

.status-unpaid {
  background-color: #fee2e2;
  color: #dc2626;
}

.status-partially_paid {
  background-color: #ffedd5;
  color: #f97316;
}

.status-paid {
  background-color: #dcfce7;
  color: #22c55e;
}

.neo-splits-container {
  padding: 0.5rem 1.2rem 1.2rem;
  background-color: rgba(255, 255, 255, 0.5);
}

.neo-splits-list {
  margin-top: 0rem;
  padding-left: 0;
  border-left: none;
}

.neo-split-item {
  padding: 0.75rem 0;
  border-bottom: 1px dashed #f0e5d8;
  display: grid;
  grid-template-areas:
    "user owes status paid action"
    "activities activities activities activities activities";
  grid-template-columns: 1.5fr 1fr 1fr 1.5fr auto;
  gap: 0.5rem 1rem;
  align-items: center;
}

.neo-split-item:last-child {
  border-bottom: none;
}

.split-col.split-user {
  grid-area: user;
}

.split-col.split-owes {
  grid-area: owes;
}

.split-col.split-status {
  grid-area: status;
}

.split-col.split-paid-info {
  grid-area: paid;
}

.split-col.split-action {
  grid-area: action;
  justify-self: end;
}

.split-col.neo-settlement-activities {
  grid-area: activities;
  font-size: 0.8em;
  color: #555;
  padding-left: 1em;
  list-style-type: disc;
  margin-top: 0.5em;
}

.neo-settlement-activities {
  font-size: 0.8em;
  color: #555;
  padding-left: 1em;
  list-style-type: disc;
  margin-top: 0.5em;
}

.neo-settlement-activities li {
  margin-top: 0.2em;
}

/* Enhanced Chores List Styles */
.enhanced-chores-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.enhanced-chore-item {
  background: #fafafa;
  border: 2px solid #111;
  border-radius: 12px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.enhanced-chore-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.enhanced-chore-item.status-overdue {
  border-left: 6px solid #ef4444;
}

.enhanced-chore-item.status-due-today {
  border-left: 6px solid #f59e0b;
}

.enhanced-chore-item.completed {
  opacity: 0.8;
  background: #f0f9ff;
}

.chore-main-content {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
}

.chore-icon-container {
  flex-shrink: 0;
}

.chore-status-indicator {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  background: #e5e7eb;
}

.chore-status-indicator.overdue {
  background: #fee2e2;
  color: #dc2626;
}

.chore-status-indicator.due-today {
  background: #fef3c7;
  color: #d97706;
}

.chore-status-indicator.completed {
  background: #d1fae5;
  color: #059669;
}

.chore-text-content {
  flex: 1;
  min-width: 0;
}

.chore-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.neo-chore-name {
  font-weight: 600;
  font-size: 1.1rem;
  color: #111;
}

.neo-chore-name.completed {
  text-decoration: line-through;
  opacity: 0.7;
}

.chore-badges {
  display: flex;
  gap: 0.25rem;
  flex-wrap: wrap;
}

.chore-details {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  font-size: 0.9rem;
  color: #666;
}

.chore-due-info,
.chore-assignment-info {
  display: flex;
  gap: 0.5rem;
}

.due-label,
.assignment-label {
  font-weight: 600;
  color: #374151;
}

.due-date.overdue {
  color: #dc2626;
  font-weight: 600;
}

.due-date.due-today {
  color: #d97706;
  font-weight: 600;
}

.today-indicator,
.overdue-indicator {
  font-size: 0.8rem;
  font-weight: 500;
}

.chore-description {
  margin-top: 0.25rem;
  font-style: italic;
  color: #6b7280;
}

.completion-info {
  margin-top: 0.25rem;
  color: #059669;
  font-weight: 500;
  font-size: 0.85rem;
}

.chore-actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* Chore Detail Modal Styles */
.chore-detail-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.chore-overview-section {
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 1rem;
}

.chore-status-summary {
  margin-bottom: 1rem;
}

.status-badges {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.chore-meta-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 0.75rem;
}

.meta-item {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.meta-item .label {
  font-weight: 600;
  color: #374151;
  font-size: 0.9rem;
}

.meta-item .value {
  color: #111;
}

.meta-item .value.overdue {
  color: #dc2626;
  font-weight: 600;
}

.chore-description-full {
  margin-top: 1rem;
}

.chore-description-full p {
  color: #374151;
  line-height: 1.6;
}

.assignments-section,
.assignment-history-section,
.chore-history-section {
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 1rem;
}

.assignments-section:last-child,
.assignment-history-section:last-child,
.chore-history-section:last-child {
  border-bottom: none;
}

.assignments-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.assignment-card {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 1rem;
}

.editing-assignment {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.editing-actions {
  display: flex;
  gap: 0.5rem;
}

.assignment-info {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.assignment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.assigned-user-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.user-name {
  font-weight: 600;
  color: #111;
}

.assignment-actions {
  display: flex;
  gap: 0.5rem;
}

.assignment-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.detail-item {
  display: flex;
  gap: 0.5rem;
}

.detail-item .label {
  font-weight: 600;
  color: #374151;
  min-width: 80px;
}

.detail-item .value {
  color: #111;
}

.no-assignments,
.no-history {
  color: #6b7280;
  font-style: italic;
  text-align: center;
  padding: 1rem;
}

.history-timeline {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.assignment-history-header {
  font-weight: 600;
  color: #374151;
  margin-bottom: 0.5rem;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 0.25rem;
}

.history-entry {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  padding: 0.75rem;
  background: #f9fafb;
  border-radius: 6px;
  border-left: 3px solid #d1d5db;
}

.history-timestamp {
  font-size: 0.8rem;
  color: #6b7280;
  font-weight: 500;
}

.history-event {
  color: #374151;
}

.history-user {
  font-size: 0.85rem;
  color: #6b7280;
  font-style: italic;
}

@media (max-width: 768px) {
  .chore-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .chore-meta-info {
    grid-template-columns: 1fr;
  }

  .assignment-header {
    flex-direction: column;
    gap: 0.5rem;
  }
}

.loading-assignments {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  color: #6b7280;
  font-style: italic;
}
</style>
