import React, { useState, useCallback, useMemo, useRef } from 'react';
import { View, Text, StyleSheet, Animated, RefreshControl, Alert, TouchableOpacity } from 'react-native';
import { useTasks } from '@/hooks/useTasks';
import { useSubtasks } from '@/hooks/useSubtasks';
import { useCategories } from '@/hooks/useDatabase';
import { useTaskModals } from '@/hooks/useTaskModals';
import { useFocusEffect } from 'expo-router';
import { TaskItem } from './TaskItem';
import { SubtaskItem } from './SubtaskItem';
import { TaskData, SubtaskData, parseTaskTags } from '@/types';
import Task from '@/models/Task';
import { useSettings } from '@/theme';
import {
  toggleTaskComplete,
  deleteTask,
  setTaskCompleted,
  convertTaskToSubtask,
  convertSubtaskToTask,
  moveSubtaskToTask,
  setSubtaskParent,
  toggleSubtaskComplete,
} from '@/utils/taskActions';
import Svg, { Path } from 'react-native-svg';

interface TaskListProps {
  categoryIds?: string[];
  showCompleted?: boolean;
  onSelectionChange?: (active: boolean) => void;
}

const PRIORITY_RANK: Record<string, number> = { none: 0, low: 1, medium: 2, high: 3, critical: 4 };

const SEPARATOR = () => <View style={styles.separator} />;
const MemoSeparator = React.memo(SEPARATOR);

const DropIndicator = ({ theme }: { theme: any }) => (
  <View style={styles.dropIndicatorContainer}>
    <View style={[styles.dropIndicator, { backgroundColor: theme.accent }]} />
    <View style={[styles.dropIndicatorDot, { backgroundColor: theme.accent }]} />
    <View style={[styles.dropIndicatorDot, { backgroundColor: theme.accent }]} />
  </View>
);

export function TaskList({ categoryIds = [], showCompleted = false, onSelectionChange }: TaskListProps) {
  const { theme, sortBy, todoAheadDays } = useSettings();

  const { tasks, loading, refresh: refreshTasks } = useTasks(categoryIds, showCompleted ? 'all' : false, todoAheadDays);

  const categories = useCategories();
  const categoryColors = useMemo(() => {
    const map = new Map<string, string>();
    for (const c of categories) {
      map.set(c.id, c.color);
    }
    return map;
  }, [categories]);

  const [refreshing, setRefreshing] = useState(false);
  const [selectionMode, setSelectionMode] = useState(false);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [hoverTaskId, setHoverTaskId] = useState<string | null>(null);
  const [expandedTasks, setExpandedTasks] = useState<Set<string>>(new Set());
  const { map: subtasksMap, refresh: refreshSubtasks } = useSubtasks();
  const [dropIndicator, setDropIndicator] = useState<{ targetId: string | null; position: 'above' | 'below' } | null>(null);
  const itemRefs = useRef<Map<string, View>>(new Map());
  const subtaskRefs = useRef<Map<string, { ref: View; parentTaskId: string }>>(new Map());
  const dragStateRef = useRef<{ taskId: string; positions: Record<string, { top: number; bottom: number }>; subPositions: Record<string, { top: number; bottom: number }> } | null>(null);
  const subtaskDragRef = useRef<{ subtaskId: string; parentTaskId: string; positions: Record<string, { top: number; bottom: number }>; subPositions: Record<string, { top: number; bottom: number }> } | null>(null);
   const {
      modals,
      openTaskDelete,
      openSubtaskDelete,
      openSubtaskEdit,
      openTaskEdit,
    } = useTaskModals();

  const registerRef = useCallback((taskId: string, ref: View | null) => {
    if (ref) {
      itemRefs.current.set(taskId, ref);
    } else {
      itemRefs.current.delete(taskId);
    }
  }, []);

  const registerSubtaskRef = useCallback((subtaskId: string, parentTaskId: string, ref: View | null) => {
    if (ref) {
      subtaskRefs.current.set(subtaskId, { ref, parentTaskId });
    } else {
      subtaskRefs.current.delete(subtaskId);
    }
  }, []);

  const categoryColorResolver = useCallback(
    (categoryId: string | undefined) => (categoryId ? categoryColors.get(categoryId) : undefined),
    [categoryColors]
  );

  const sortedTasks = useMemo(() => {
    const sorted = [...tasks];
    switch (sortBy) {
      case 'date':
        sorted.sort((a, b) => (a.dueDate || Number.MAX_SAFE_INTEGER) - (b.dueDate || Number.MAX_SAFE_INTEGER));
        break;
      case 'priority':
        sorted.sort((a, b) => PRIORITY_RANK[b.priority] - PRIORITY_RANK[a.priority]);
        break;
      case 'alpha':
        sorted.sort((a, b) => a.title.localeCompare(b.title));
        break;
      case 'created':
        sorted.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
        break;
    }
    const active: typeof sorted = [];
    const done: typeof sorted = [];
    for (const t of sorted) {
      (t.completed ? done : active).push(t);
    }
    return [...active, ...done];
  }, [tasks, sortBy]);

  useFocusEffect(
    useCallback(() => {
      refreshTasks();
      refreshSubtasks();
    }, [refreshTasks, refreshSubtasks])
  );

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    refreshTasks();
    refreshSubtasks();
    setTimeout(() => setRefreshing(false), 600);
  }, [refreshTasks, refreshSubtasks]);

  const exitSelection = useCallback(() => {
    setSelectionMode(false);
    setSelectedIds(new Set());
    onSelectionChange?.(false);
  }, [onSelectionChange]);

  const enterSelection = useCallback((taskId: string) => {
    setSelectionMode(true);
    setSelectedIds(new Set([taskId]));
    onSelectionChange?.(true);
  }, [onSelectionChange]);

  const toggleSelect = useCallback((taskId: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(taskId)) {
        next.delete(taskId);
      } else {
        next.add(taskId);
      }
      if (next.size === 0) {
        setSelectionMode(false);
        onSelectionChange?.(false);
      }
      return next;
    });
  }, [onSelectionChange]);

  const handleToggle = useCallback(async (taskId: string) => {
    await toggleTaskComplete(taskId);
    refreshTasks();
  }, [refreshTasks]);

  const toggleExpand = useCallback(async (taskId: string) => {
    setExpandedTasks((prev) => {
      const next = new Set(prev);
      if (next.has(taskId)) {
        next.delete(taskId);
      } else {
        next.add(taskId);
      }
      return next;
    });
  }, []);

  const handleSubtaskToggle = useCallback(async (subtaskId: string) => {
    await toggleSubtaskComplete(subtaskId);
    refreshTasks();
    refreshSubtasks();
  }, [refreshTasks, refreshSubtasks]);

  const handleBulkDelete = useCallback(() => {
    Alert.alert(`Delete ${selectedIds.size} task${selectedIds.size > 1 ? 's' : ''}?`, 'This cannot be undone.', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          await Promise.all(Array.from(selectedIds).map(taskId => deleteTask(taskId)));
          exitSelection();
        },
      },
    ]);
  }, [selectedIds, exitSelection]);

  const handleBulkComplete = useCallback(async () => {
    await Promise.all(Array.from(selectedIds).map(taskId => setTaskCompleted(taskId, true)));
    exitSelection();
  }, [selectedIds, exitSelection]);

  const measureItems = useCallback(async () => {
    const positions: Record<string, { top: number; bottom: number }> = {};
    const entries = Array.from(itemRefs.current.entries());
    await Promise.all(entries.map(([id, ref]) => {
      return new Promise<void>((resolve) => {
        ref?.measureInWindow((_x, y, _w, h) => {
          positions[id] = { top: y, bottom: y + h };
          resolve();
        });
      });
    }));
    return positions;
  }, []);

  const measureAll = useCallback(async () => {
    const positions = await measureItems();
    const subPositions: Record<string, { top: number; bottom: number }> = {};
    const entries = Array.from(subtaskRefs.current.entries());
    await Promise.all(entries.map(([id, entry]) => {
      return new Promise<void>((resolve) => {
        entry.ref?.measureInWindow((_x, y, _w, h) => {
          subPositions[id] = { top: y, bottom: y + h };
          resolve();
        });
      });
    }));
    return { positions, subPositions };
  }, [measureItems]);

  const findHoverTarget = useCallback((absoluteY: number, draggedId: string, positions: Record<string, { top: number; bottom: number }>, subPositions: Record<string, { top: number; bottom: number }>) => {
    const subEntries = Object.entries(subPositions);
    for (let i = subEntries.length - 1; i >= 0; i--) {
      const [id, p] = subEntries[i];
      if (id === draggedId) continue;
      if (absoluteY >= p.top && absoluteY <= p.bottom) {
        return id;
      }
    }
    for (const [id, p] of Object.entries(positions)) {
      if (id === draggedId) continue;
      if (absoluteY >= p.top && absoluteY <= p.bottom) {
        return id;
      }
    }
    return null;
  }, []);

  const calculateDropPosition = useCallback((absoluteY: number, targetId: string, positions: Record<string, { top: number; bottom: number }>) => {
    const target = positions[targetId];
    if (!target) return 'below' as const;
    const middle = (target.top + target.bottom) / 2;
    return absoluteY < middle ? 'above' : 'below';
  }, []);

  const handleDragStart = useCallback(async (taskId: string) => {
    dragStateRef.current = { taskId, ...(await measureAll()) };
  }, [measureAll]);

  const refreshDragPositions = useCallback(() => {
    measureAll().then((m) => {
      if (subtaskDragRef.current) {
        subtaskDragRef.current = { ...subtaskDragRef.current, ...m };
      } else if (dragStateRef.current) {
        dragStateRef.current = { ...dragStateRef.current, ...m };
      }
    });
  }, [measureAll]);

  const updateHoverTarget = useCallback((target: string | null) => {
    let changed = false;
    setHoverTaskId((prev) => {
      if (prev === target) return prev;
      changed = true;
      return target;
    });
    if (changed && target) {
      setTimeout(refreshDragPositions, 80);
    }
  }, [refreshDragPositions]);

  const handleDragUpdate = useCallback((absoluteY: number) => {
    const state = dragStateRef.current;
    if (!state) return;
    const target = findHoverTarget(absoluteY, state.taskId, state.positions, state.subPositions);
    updateHoverTarget(target);
    if (target) {
      if (state.subPositions[target]) {
        setDropIndicator(null);
      } else {
        const position = calculateDropPosition(absoluteY, target, state.positions);
        setDropIndicator({ targetId: target, position });
      }
    } else {
      // Check if below last item
      const positions = state.positions;
      const lastItem = Object.values(positions).reduce((max, p) => p.bottom > max.bottom ? p : max, { bottom: 0 });
      if (absoluteY > lastItem.bottom) {
        setDropIndicator({ targetId: null, position: 'below' });
      } else {
        setDropIndicator(null);
      }
    }
  }, [findHoverTarget, calculateDropPosition, updateHoverTarget]);

  const handleDragEnd = useCallback((absoluteY: number) => {
    const state = dragStateRef.current;
    dragStateRef.current = null;
    setHoverTaskId(null);
    setDropIndicator(null);
    if (!state) return;

    const target = findHoverTarget(absoluteY, state.taskId, state.positions, state.subPositions);
    if (target) {
      if (state.subPositions[target]) {
        const parentTaskId = subtaskRefs.current.get(target)?.parentTaskId ?? state.taskId;
        (async () => {
          await convertTaskToSubtask(state.taskId, parentTaskId, target);
        })();
      } else {
        (async () => {
          await convertTaskToSubtask(state.taskId, target);
        })();
      }
    }
  }, [findHoverTarget]);

  const handleSubtaskDragStart = useCallback(async (subtaskId: string, parentTaskId: string) => {
    subtaskDragRef.current = { subtaskId, parentTaskId, ...(await measureAll()) };
  }, [measureAll]);

  const handleSubtaskDragUpdate = useCallback((absoluteY: number) => {
    const state = subtaskDragRef.current;
    if (!state) return;
    const target = findHoverTarget(absoluteY, state.subtaskId, state.positions, state.subPositions);
    updateHoverTarget(target);
    if (target) {
      if (state.subPositions[target]) {
        setDropIndicator(null);
      } else {
        const position = calculateDropPosition(absoluteY, target, state.positions);
        setDropIndicator({ targetId: target, position });
      }
    } else {
      const positions = state.positions;
      const lastItem = Object.values(positions).reduce((max, p) => p.bottom > max.bottom ? p : max, { bottom: 0 });
      if (absoluteY > lastItem.bottom) {
        setDropIndicator({ targetId: null, position: 'below' });
      } else {
        setDropIndicator(null);
      }
    }
  }, [findHoverTarget, calculateDropPosition, updateHoverTarget]);

  const handleSubtaskDragEnd = useCallback(async (absoluteY: number) => {
    const state = subtaskDragRef.current;
    subtaskDragRef.current = null;
    setHoverTaskId(null);
    setDropIndicator(null);
    if (!state) return;

    const target = findHoverTarget(absoluteY, state.subtaskId, state.positions, state.subPositions);
    if (target === state.subtaskId) return;

    if (target) {
      if (state.subPositions[target]) {
        await setSubtaskParent(state.subtaskId, target);
      } else if (target !== state.parentTaskId) {
        await moveSubtaskToTask(state.subtaskId, target);
      }
    } else {
      await convertSubtaskToTask(state.subtaskId);
    }
  }, [findHoverTarget]);

  const renderItem = useCallback(
    ({ item, index }: { item: Task; index: number }) => {
      const isExpanded = expandedTasks.has(item.id);
      const itemSubtasks = subtasksMap.get(item.id) ?? [];
      const showDropAbove = dropIndicator?.targetId === item.id && dropIndicator?.position === 'above';
      const showDropBelow = dropIndicator?.targetId === item.id && dropIndicator?.position === 'below';
      const tagColors = parseTaskTags(item.tags, item.categoryId).map((id) => categoryColors.get(id));
      return (
        <View>
          {showDropAbove && <DropIndicator theme={theme} />}
          <TaskRow
            task={item}
            expanded={isExpanded}
            subtasks={itemSubtasks}
            selected={selectedIds.has(item.id)}
            selectionMode={selectionMode}
            hovered={hoverTaskId === item.id}
            registerRef={registerRef}
            registerSubtaskRef={registerSubtaskRef}
            hoverTaskId={hoverTaskId}
            onToggle={handleToggle}
            onDelete={openTaskDelete}
            onExpand={toggleExpand}
            onSelect={toggleSelect}
            onEnterSelection={enterSelection}
            onMenuOpen={(task) => openTaskEdit(task.id)}
            onSubtaskToggle={handleSubtaskToggle}
            onSubtaskDelete={openSubtaskDelete}
            onSubtaskMenuOpen={(subtask) => openSubtaskEdit(subtask.id)}
            onDragStart={handleDragStart}
            onDragUpdate={handleDragUpdate}
            onDragEnd={handleDragEnd}
            onSubtaskDragStart={handleSubtaskDragStart}
            onSubtaskDragUpdate={handleSubtaskDragUpdate}
            onSubtaskDragEnd={handleSubtaskDragEnd}
            onReorderStart={() => handleDragStart(item.id)}
            onReorderUpdate={handleDragUpdate}
            onReorderEnd={handleDragEnd}
            selectedIds={selectedIds}
            categoryColor={categoryColors.get(item.categoryId)}
            categoryColors={tagColors}
            categoryColorResolver={categoryColorResolver}
          />
          {showDropBelow && <DropIndicator theme={theme} />}
        </View>
      );
    },
    [
      expandedTasks,
      subtasksMap,
      selectedIds,
      selectionMode,
      hoverTaskId,
      dropIndicator,
      theme,
      registerRef,
      handleToggle,
      openTaskDelete,
      toggleExpand,
      toggleSelect,
      enterSelection,
      openTaskEdit,
      handleSubtaskToggle,
      openSubtaskDelete,
      openSubtaskEdit,
      handleDragStart,
      handleDragUpdate,
      handleDragEnd,
      handleSubtaskDragStart,
      handleSubtaskDragUpdate,
      handleSubtaskDragEnd,
      registerSubtaskRef,
      categoryColorResolver,
      categoryColors,
    ]
  );

  const listHeader = useMemo(() => {
    if (sortedTasks.length > 0) return null;
    return (
      <View style={styles.emptyState}>
        <Text style={[styles.emptyText, { color: theme.textSecondary }]}>No tasks yet</Text>
        <Text style={[styles.emptySubtext, { color: theme.textMuted }]}>Tap + to add your first task</Text>
      </View>
    );
  }, [sortedTasks.length, theme.textSecondary, theme.textMuted]);

  const listFooter = useMemo(() => {
    const showDropAtEnd = dropIndicator && dropIndicator.targetId === null;
    return showDropAtEnd ? <DropIndicator theme={theme} /> : null;
  }, [dropIndicator, theme]);

  if (loading && !refreshing) {
    return (
      <View style={styles.loadingContainer}>
        <Text style={[styles.loadingText, { color: theme.textFaint }]}>Loading tasks...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Animated.FlatList
        data={sortedTasks}
        keyExtractor={(item) => item.id}
        renderItem={renderItem}
        extraData={{ expandedTasks, subtasksMap, selectedIds, selectionMode, hoverTaskId, dropIndicator }}
        ItemSeparatorComponent={MemoSeparator}
        ListHeaderComponent={listHeader}
        ListFooterComponent={listFooter}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={theme.accent}
            colors={[theme.accent]}
            progressBackgroundColor={theme.card}
          />
        }
        contentContainerStyle={styles.listContent}
      />

      {modals(() => {})}

      {selectionMode && (
        <View style={[styles.selectionBar, { backgroundColor: theme.sheetBg, borderTopColor: theme.border }]}>
          <TouchableOpacity onPress={exitSelection} style={styles.selectionCancel} activeOpacity={0.7}>
            <Svg width={20} height={20} viewBox="0 0 24 24">
              <Path d="M18 6L6 18M6 6l12 12" stroke={theme.textSecondary} strokeWidth={2.2} strokeLinecap="round" />
            </Svg>
            <Text style={[styles.selectionCancelText, { color: theme.textFaint }]}>Cancel</Text>
          </TouchableOpacity>
          <Text style={[styles.selectionCount, { color: theme.text }]}>{selectedIds.size} selected</Text>
          <View style={styles.selectionActions}>
            <SelectionButton label="Complete" color="#43A047" onPress={handleBulkComplete} />
            <SelectionButton label="Delete" color="#E53935" onPress={handleBulkDelete} />
          </View>
        </View>
      )}
    </View>
  );
}

const SelectionButton = React.memo(function SelectionButton({ label, color, onPress }: { label: string; color: string; onPress: () => void }) {
  return (
    <TouchableOpacity
      style={[styles.selectionButton, { backgroundColor: color }]}
      onPress={onPress}
      activeOpacity={0.8}
    >
      <Text style={styles.selectionButtonText}>{label}</Text>
    </TouchableOpacity>
  );
});

interface TaskRowProps {
  task: Task;
  expanded: boolean;
  subtasks: SubtaskData[];
  selected: boolean;
  selectionMode: boolean;
  hovered: boolean;
  registerRef: (taskId: string, ref: View | null) => void;
  registerSubtaskRef: (subtaskId: string, parentTaskId: string, ref: View | null) => void;
  hoverTaskId: string | null;
  onToggle: (taskId: string) => void | Promise<void>;
  onDelete: (task: Task) => void;
  onExpand: (taskId: string) => void | Promise<void>;
  onSelect: (taskId: string) => void;
  onEnterSelection: (taskId: string) => void;
  onMenuOpen: (task: Task) => void;
  onSubtaskToggle: (subtaskId: string, taskId: string) => void;
  onSubtaskDelete: (subtask: SubtaskData) => void;
  onSubtaskMenuOpen: (subtask: SubtaskData) => void;
  onDragStart: (taskId: string) => void;
  onDragUpdate: (absoluteY: number) => void;
  onDragEnd: (absoluteY: number) => void;
  onSubtaskDragStart: (subtaskId: string, parentTaskId: string) => void;
  onSubtaskDragUpdate: (absoluteY: number) => void;
  onSubtaskDragEnd: (absoluteY: number) => void;
  onReorderStart: () => void;
  onReorderUpdate: (absoluteY: number) => void;
  onReorderEnd: (absoluteY: number, translationY: number) => void;
  selectedIds: Set<string>;
  categoryColor?: string;
  categoryColors?: (string | undefined)[];
  categoryColorResolver?: (categoryId: string | undefined) => string | undefined;
}

const TaskRow = React.memo(function TaskRow({
  task,
  expanded,
  subtasks,
  selected,
  selectionMode,
  hovered,
  hoverTaskId,
  registerRef,
  registerSubtaskRef,
  onToggle,
  onDelete,
  onExpand,
  onSelect,
  onEnterSelection,
  onMenuOpen,
  onSubtaskToggle,
  onSubtaskDelete,
  onSubtaskMenuOpen,
  onDragStart,
  onDragUpdate,
  onDragEnd,
  onSubtaskDragStart,
  onSubtaskDragUpdate,
  onSubtaskDragEnd,
  onReorderStart,
  onReorderUpdate,
  onReorderEnd,
  selectedIds,
  categoryColor,
  categoryColors,
  categoryColorResolver,
}: TaskRowProps) {
  const sortedSubtasks = useMemo(
    () => subtasks.slice().sort((a, b) => a.order - b.order),
    [subtasks]
  );
  return (
    <View
      ref={(ref) => registerRef(task.id, ref)}
      style={styles.dragContainer}
    >
      <TaskItem
        task={task as unknown as TaskData}
        onToggle={() => onToggle(task.id)}
        onDelete={() => onDelete(task)}
        onPress={() => (selectionMode ? onSelect(task.id) : onExpand(task.id))}
        onLongPress={selectionMode ? undefined : () => onEnterSelection(task.id)}
        onMenuOpen={() => onMenuOpen(task)}
        selected={selected}
        selectionMode={selectionMode}
        expanded={expanded}
        draggable
        hovered={hovered}
        onDragStart={() => onDragStart(task.id)}
        onDragUpdate={onDragUpdate}
        onDragEnd={onDragEnd}
        onReorderStart={onReorderStart}
        onReorderUpdate={onReorderUpdate}
        onReorderEnd={onReorderEnd}
        categoryColor={categoryColor}
        categoryColors={categoryColors}
      />
      {expanded && subtasks.length > 0 && (
        <View style={styles.subtaskList}>
          {sortedSubtasks.map((sub) => (
<SubtaskItem
                key={sub.id}
                subtask={sub}
                hoveredId={hoverTaskId}
                registerRef={registerSubtaskRef}
                onToggle={(sub) => onSubtaskToggle(sub.id, task.id)}
              onDelete={() => onSubtaskDelete(sub)}
              onMenuOpen={() => onSubtaskMenuOpen(sub)}
              selected={selectedIds.has(sub.id)}
              selectionMode={selectionMode}
              draggable
              onDragStart={(sub) => onSubtaskDragStart(sub.id, task.id)}
              onDragUpdate={onSubtaskDragUpdate}
              onDragEnd={onSubtaskDragEnd}
              categoryColor={categoryColor}
              categoryColorResolver={categoryColorResolver}
            />
          ))}
        </View>
      )}
     </View>
    );
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  listContent: {
    paddingHorizontal: 16,
    paddingTop: 8,
    paddingBottom: 12,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    fontSize: 16,
  },
  separator: {
    height: 8,
  },
  subtaskList: {
    paddingLeft: 8,
    paddingRight: 4,
    paddingTop: 8,
  },
  completedSubtasks: {
    paddingLeft: 8,
    paddingRight: 4,
    paddingTop: 4,
    marginBottom: 4,
  },
  dragContainer: {
  },
  dropIndicatorContainer: {
    height: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  dropIndicator: {
    width: '80%',
    height: 2,
    borderRadius: 1,
  },
  dropIndicatorDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    position: 'absolute',
  },
  emptyState: {
    alignItems: 'center',
    paddingVertical: 48,
  },
  emptyText: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 4,
  },
  emptySubtext: {
    fontSize: 14,
  },
  completedSection: {
    marginTop: 16,
    paddingBottom: 24,
  },
  completedHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 4,
    paddingVertical: 8,
  },
  completedTitle: {
    fontSize: 14,
    fontWeight: '600',
  },
  completedToggle: {
    fontSize: 14,
    fontWeight: '500',
  },
  completedList: {
    paddingTop: 8,
  },
  selectionBar: {
    position: 'absolute',
    left: 16,
    right: 16,
    bottom: 84,
    borderRadius: 20,
    borderWidth: 1,
    paddingHorizontal: 16,
    paddingVertical: 12,
    gap: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 12,
    elevation: 8,
  },
  selectionCancel: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    alignSelf: 'flex-start',
  },
  selectionCancelText: {
    fontSize: 14,
    fontWeight: '500',
  },
  selectionCount: {
    fontSize: 15,
    fontWeight: '700',
    textAlign: 'center',
  },
  selectionActions: {
    flexDirection: 'row',
    gap: 8,
  },
  selectionSecondRow: {
    flexDirection: 'row',
    gap: 8,
  },
  selectionButton: {
    flex: 1,
    paddingVertical: 10,
    borderRadius: 12,
    alignItems: 'center',
  },
  selectionButtonText: {
    color: '#FFFFFF',
    fontSize: 14,
    fontWeight: '600',
  },
});
