import { useEffect, useState } from "react";
import { Modal, Button, Form } from 'react-bootstrap';
import { FinancialYearField } from "../CarbonFootPrinting/common/FormComponents";
import { generateTimePeriodOptions, getStartingMonth } from "../CarbonFootPrinting/utils/PeriodCalculationUtils";
import { fetchFrequency, getFinancialYear } from "../Training/training-dashboard/services/trainingService";
import "./EmailReminder.css";
import config from "../../config/config";
import { apiCall } from "../../_services/apiCall";
import {
    SettingLayout,
    SettingsFilterCard,
    SettingsCard, SettingsSectionHeader, SettingsSectionTitle, SettingsCountChip,
    SettingsTable, SettingsTh, SettingsTr, SettingsTd,
    SettingsActionsCell, SettingsActionBtn,
    SettingsStatusBadge,
    SettingsEmptyState,
    SettingsModalBody, SettingsModalFooter,
    SettingsFormGroup, SettingsFormLabel, SettingsFormSelect,
    SettingsWarningBlock,
} from "./SettingShell";
import { Modal as ShellModal, ModalHeader } from "../../globalComponents/ui/Modal";
import { PrimaryButton, SecondaryButton, DangerButton } from "../../globalComponents/ui/Button";
import styled from "styled-components";

// ─── Local styled extras ──────────────────────────────────────────────────────

const FilterGroup = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 200px;
`;

const FilterLabel = styled.span`
  font-size: 10px;
  font-weight: 700;
  color: #64748b;
  text-transform: uppercase;
  letter-spacing: 0.4px;
`;

const FilterSelect = styled.select`
  padding: 7px 10px;
  border: 1.5px solid #e2e8f0;
  border-radius: 9px;
  font-size: 13px;
  color: #1e293b;
  background: #fff;
  outline: none;
  transition: border-color 0.15s;
  &:focus {
    border-color: #3f88a5;
    box-shadow: 0 0 0 3px rgba(63,136,165,0.08);
  }
`;

const DateRangeChip = styled.div`
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 5px 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  color: #0369a1;
  white-space: nowrap;
`;

const PeriodLabel = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
  font-weight: 600;
  color: #1e293b;
`;

const PeriodIcon = styled.div`
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background: linear-gradient(135deg, #3f88a5, #2c6b84);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  flex-shrink: 0;
`;

const ActionGroup = styled.div`
  display: flex;
  gap: 6px;
  justify-content: flex-end;
  flex-wrap: wrap;
`;

const LockBtn = styled.button`
  padding: 5px 12px;
  border: none;
  border-radius: 7px;
  font-size: 11px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.15s;
  display: flex;
  align-items: center;
  gap: 5px;
  background: ${({ $variant }) =>
        $variant === 'lock' ? '#fee2e2' :
            $variant === 'unlock' ? '#fef3c7' :
                '#ede9fe'};
  color: ${({ $variant }) =>
        $variant === 'lock' ? '#dc2626' :
            $variant === 'unlock' ? '#d97706' :
                '#7c3aed'};
  &:hover {
    filter: brightness(0.93);
  }
`;

// User list in modals
const UserListWrap = styled.div`
  max-height: 320px;
  overflow-y: auto;
  border: 1.5px solid #e2e8f0;
  border-radius: 10px;
  background: #f8fafc;
`;

const UserItem = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 14px;
  border-bottom: 1px solid #f1f5f9;
  background: ${({ $selected, $color }) =>
        $selected
            ? $color === 'green' ? '#ecfdf5'
                : $color === 'amber' ? '#fef3c7'
                    : '#e0f5f9'
            : 'transparent'};
  transition: background 0.12s;
  &:last-child { border-bottom: none; }
`;

const UserAvatar = styled.div`
  width: 34px;
  height: 34px;
  border-radius: 8px;
  background: ${({ $color }) =>
        $color === 'green' ? 'linear-gradient(135deg,#10b981,#059669)' :
            $color === 'red' ? 'linear-gradient(135deg,#ef4444,#dc2626)' :
                $color === 'amber' ? 'linear-gradient(135deg,#f59e0b,#d97706)' :
                    'linear-gradient(135deg,#3f88a5,#2c6b84)'};
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 700;
  flex-shrink: 0;
`;

const UserName = styled.div`
  font-size: 13px;
  font-weight: 600;
  color: #1e293b;
`;

const UserEmail = styled.div`
  font-size: 11px;
  color: #64748b;
`;

const SearchInput = styled.input`
  width: 100%;
  padding: 7px 12px 7px 34px;
  border: 1.5px solid #e2e8f0;
  border-radius: 9px;
  font-size: 13px;
  color: #1e293b;
  background: #fff;
  outline: none;
  transition: border-color 0.15s;
  &:focus {
    border-color: #3f88a5;
    box-shadow: 0 0 0 3px rgba(63,136,165,0.08);
  }
  &::placeholder { color: #cbd5e1; font-size: 12px; }
`;

const SearchWrap = styled.div`
  position: relative;
  margin-bottom: 10px;
  i {
    position: absolute;
    left: 11px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 11px;
    color: #94a3b8;
  }
`;

const SelectionBar = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 12px;
  color: #64748b;
`;

const SelectionActions = styled.div`
  display: flex;
  gap: 6px;
`;

const SelectionActionBtn = styled.button`
  padding: 4px 10px;
  border: 1.5px solid #e2e8f0;
  border-radius: 7px;
  font-size: 11px;
  font-weight: 600;
  cursor: pointer;
  background: #fff;
  color: #475569;
  transition: all 0.12s;
  &:hover { border-color: #3f88a5; color: #3f88a5; }
`;

const SelectionSummary = styled.div`
  margin-top: 10px;
  padding: 8px 14px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 9px;
  font-size: 12px;
  color: #0369a1;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
`;

const ViewGrid = styled.div`
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  @media (max-width: 600px) { grid-template-columns: 1fr; }
`;

const ViewColumn = styled.div``;

const ViewColumnHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  font-size: 13px;
  font-weight: 700;
  color: ${({ $color }) => $color === 'green' ? '#059669' : '#dc2626'};
`;

const ViewListWrap = styled.div`
  max-height: 340px;
  overflow-y: auto;
  border: 1.5px solid ${({ $color }) => $color === 'green' ? '#6ee7b7' : '#fca5a5'};
  border-radius: 10px;
  background: ${({ $color }) => $color === 'green' ? '#f0fdf4' : '#fff5f5'};
`;

// ─── SearchBar sub-component ──────────────────────────────────────────────────

const SearchBar = ({ searchQuery, setSearchQuery, placeholder, autoFocus = false }) => (
    <SearchWrap>
        <i className="fas fa-search" />
        <SearchInput
            type="text"
            placeholder={placeholder}
            value={searchQuery || ''}
            onChange={(e) => setSearchQuery(e.target.value)}
            autoFocus={autoFocus}
        />
    </SearchWrap>
);

// ─── Component ────────────────────────────────────────────────────────────────

const LockQuestion = () => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [actionLoading, setActionLoading] = useState({});
    const [dataLoading, setDataLoading] = useState({});
    const [selectedFinancialYear, setSelectedFinancialYear] = useState("");
    const [financialYearOptions, setFinancialYearOptions] = useState([]);
    const [financialYear, setFinancialYear] = useState([]);
    const [financialYearId, setFinancialYearId] = useState(null);

    const [timePeriodOptions, setTimePeriodOptions] = useState([]);
    const [frequency, setFrequency] = useState('MONTHLY');

    const [lockedPeriods, setLockedPeriods] = useState(new Set());
    const [periodLockData, setPeriodLockData] = useState([]);
    const [selectedPeriods, setSelectedPeriods] = useState(new Set());

    const [users, setUsers] = useState([]);
    const [usersLoading, setUsersLoading] = useState(false);
    const [showUserModal, setShowUserModal] = useState(false);
    const [showViewModal, setShowViewModal] = useState(false);
    const [showUnlockModal, setShowUnlockModal] = useState(false);
    const [selectedUsersForLock, setSelectedUsersForLock] = useState([]);
    const [selectedUsersForUnlock, setSelectedUsersForUnlock] = useState([]);
    const [currentLockingPeriod, setCurrentLockingPeriod] = useState(null);
    const [currentViewingPeriod, setCurrentViewingPeriod] = useState(null);
    const [currentUnlockingPeriod, setCurrentUnlockingPeriod] = useState(null);
    const [currectFromDateToDate, setCurrectFromDateToDate] = useState(null);

    const [modalType, setModalType] = useState('');

    const [userSearchQuery, setUserSearchQuery] = useState('');
    const [unlockSearchQuery, setUnlockSearchQuery] = useState('');
    const [allowedUsersSearchQuery, setAllowedUsersSearchQuery] = useState('');
    const [unallowedUsersSearchQuery, setUnallowedUsersSearchQuery] = useState('');

    // ─── All original logic unchanged ──────────────────────────────────────────

    const getFinancialYearById = (id) => {
        const result = financialYear.find(item => item.id === id);
        return result ? result.financial_year_value : null;
    };

    const calculateDateRange = (type, period, startingMonth, year) => {
        const startMonth = ((startingMonth - 1 + (period - 1) * type) % 12) + 1;
        const startYear = year + Math.floor((startingMonth - 1 + (period - 1) * type) / 12);
        const endMonth = ((startMonth - 1 + type) % 12) + 1;
        const endYear = startYear + Math.floor((startMonth - 1 + type) / 12);
        const formatDate = (month, year) => `${year}-${month < 10 ? `0${month}` : month}`;
        return {
            period: Number(period),
            fromDate: formatDate(startMonth, startYear),
            toDate: formatDate(endMonth, endYear),
        };
    };

    const fetchUsers = async () => {
        setUsersLoading(true);
        try {
            const { isSuccess, data } = await apiCall(`${config.POSTLOGIN_API_URL_COMPANY}getSubUser`, {}, {}, "GET");
            if (isSuccess) setUsers(data?.data?.reverse() || []);
            else setUsers([]);
        } catch (error) {
            console.error('Error fetching users:', error);
            setUsers([]);
        } finally {
            setUsersLoading(false);
        }
    };

    const openLockModal = (obj) => {
        setCurrentLockingPeriod(obj);
        setCurrectFromDateToDate(obj);
        setSelectedUsersForLock([]);
        setUserSearchQuery('');
        setModalType('lock');
        setShowUserModal(true);
    };

    const openUnlockModal = (obj) => {
        setCurrentUnlockingPeriod(obj);
        setCurrectFromDateToDate(obj);
        setSelectedUsersForUnlock([]);
        setUnlockSearchQuery('');
        setModalType('unlock');
        setShowUnlockModal(true);
    };

    const openViewModal = (obj) => {
        setCurrentViewingPeriod(obj);
        setAllowedUsersSearchQuery('');
        setUnallowedUsersSearchQuery('');
        setModalType('view');
        setShowViewModal(true);
    };

    const handleUserSelect = (userId, isSelected, type = 'lock') => {
        if (type === 'lock') {
            setSelectedUsersForLock(prev => isSelected ? [...prev, userId] : prev.filter(id => id !== userId));
        } else if (type === 'unlock') {
            setSelectedUsersForUnlock(prev => isSelected ? [...prev, userId] : prev.filter(id => id !== userId));
        }
    };

    const handleSelectAllUsers = (type = 'lock') => {
        if (type === 'lock') {
            const filteredUsers = users.filter(user => {
                if (!userSearchQuery) return true;
                const query = userSearchQuery.toLowerCase();
                const fullName = `${user.firstName} ${user.lastName}`.toLowerCase();
                const email = user.email?.toLowerCase() || '';
                return fullName.includes(query) || email.includes(query);
            });
            setSelectedUsersForLock(filteredUsers.map(user => user.userId));
        } else if (type === 'unlock') {
            const filteredUsers = getAllowedUsersForPeriod(currentUnlockingPeriod).filter(user => {
                if (!unlockSearchQuery) return true;
                const query = unlockSearchQuery.toLowerCase();
                const fullName = `${user.firstName} ${user.lastName}`.toLowerCase();
                const email = user.email?.toLowerCase() || '';
                return fullName.includes(query) || email.includes(query);
            });
            setSelectedUsersForUnlock(filteredUsers.map(user => user.userId));
        }
    };

    const handleDeselectAllUsers = (type = 'lock') => {
        if (type === 'lock') setSelectedUsersForLock([]);
        else if (type === 'unlock') setSelectedUsersForUnlock([]);
    };

    const generateAllPeriodsData = () => {
        if (!financialYearId || !timePeriodOptions.length) return [];
        const selectedYear = getFinancialYearById(financialYearId);
        if (!selectedYear) return [];
        const year = parseInt(selectedYear.split("-")[0]);
        const start = getStartingMonth();
        return timePeriodOptions.map(period => {
            let dateRange;
            if (frequency === "HALF_YEARLY") dateRange = calculateDateRange(6, period.value, start, year);
            else if (frequency === "QUARTERLY") dateRange = calculateDateRange(3, period.value, start, year);
            else if (frequency === "MONTHLY") dateRange = calculateDateRange(1, period.value, start, year);
            else if (frequency === "YEARLY") dateRange = calculateDateRange(12, 1, start, year);
            return {
                periodValue: period.value,
                periodLabel: period.label,
                fromDate: dateRange?.fromDate,
                toDate: dateRange?.toDate,
                isLocked: lockedPeriods.has(period.value)
            };
        });
    };

    const handleLockPeriod = async (obj) => { openLockModal(obj); };
    const handleSelectiveUnlock = async (obj) => { openUnlockModal(obj); };

    const confirmLockWithUsers = async (allowedUsers, key) => {
        try {
            const { isSuccess } = await apiCall(
                `${config.POSTLOGIN_API_URL_COMPANY}periods/lock`, {},
                {
                    financialYearId,
                    fromDate: currectFromDateToDate.fromDate,
                    toDate: currectFromDateToDate.toDate,
                    reason: 'Manual lock operation',
                    allowedUsers: allowedUsers,
                    type: key
                },
                "POST"
            );
            if (isSuccess) { fetchData(financialYearId); closeAllModals(); }
        } catch (err) {
            console.error('Lock error:', err);
        } finally {
            setActionLoading(prev => ({ ...prev, [currentLockingPeriod]: false }));
        }
    };

    const fetchData = async (financialYearId) => {
        setDataLoading(true);
        try {
            const { isSuccess, data } = await apiCall(
                `${config.POSTLOGIN_API_URL_COMPANY}periods/locked`, {}, { financialYearId }, "GET"
            );
            if (isSuccess) setPeriodLockData(data?.data);
            else setPeriodLockData([]);
        } catch (error) {
            console.error('Error fetching users:', error);
            setPeriodLockData([]);
        } finally {
            setDataLoading(false);
        }
    };

    const getAllowedUsersForPeriod = (obj) => {
        return users.filter(user => obj?.allowedUsers.indexOf(user.userId) === -1) || [];
    };

    const getUnallowedUsersForPeriod = (obj) => {
        const allowedUsers = getAllowedUsersForPeriod(obj);
        const allowedUserIds = allowedUsers.map(user => user.userId);
        return users.filter(user => !allowedUserIds.some(id => id === user.userId));
    };

    const closeAllModals = () => {
        setShowUserModal(false);
        setShowViewModal(false);
        setShowUnlockModal(false);
        setCurrentLockingPeriod(null);
        setCurrentViewingPeriod(null);
        setCurrentUnlockingPeriod(null);
        setModalType('');
        setUserSearchQuery('');
        setUnlockSearchQuery('');
        setAllowedUsersSearchQuery('');
        setUnallowedUsersSearchQuery('');
    };

    const filterUsers = (userList, searchQuery) => {
        if (!searchQuery) return userList;
        const query = searchQuery.toLowerCase();
        return userList.filter(user => {
            const fullName = `${user.firstName} ${user.lastName}`.toLowerCase();
            const email = user.email?.toLowerCase() || '';
            return fullName.includes(query) || email.includes(query);
        });
    };

    useEffect(() => {
        const initializeData = async () => {
            try {
                setLoading(true);
                const financialYearResult = await getFinancialYear();
                if (financialYearResult) {
                    setFinancialYear(financialYearResult.data);
                    setFinancialYearId(financialYearResult.currentId);
                    const fyOptions = financialYearResult.data.map(fy => ({ value: fy.id, label: fy.financial_year_value }));
                    setFinancialYearOptions(fyOptions);
                    setSelectedFinancialYear(financialYearResult.currentId);
                    const [frequencyData] = await Promise.all([fetchFrequency(financialYearResult.currentId)]);
                    await fetchUsers();
                    fetchData(financialYearResult.currentId);
                    setFrequency(frequencyData);
                }
            } catch (err) {
                setError(err.message);
            } finally {
                setLoading(false);
            }
        };
        initializeData();
    }, []);

    useEffect(() => {
        if (frequency) {
            const start = getStartingMonth();
            const options = generateTimePeriodOptions(frequency, start);
            setTimePeriodOptions(options);
        }
    }, [frequency]);

    const handleFinancialYearChange = async (newFinancialYearId) => {
        setSelectedFinancialYear(newFinancialYearId);
        setFinancialYearId(newFinancialYearId);
        setSelectedPeriods(new Set());
        try {
            const frequencyData = await fetchFrequency(newFinancialYearId);
            setFrequency(frequencyData);
        } catch (err) {
            console.error('Error fetching frequency:', err);
        }
    };

    const periodsData = generateAllPeriodsData();
    const lockedCount = periodsData.filter(p =>
        periodLockData.some(item => item.fromDate === p.fromDate && item.toDate === p.toDate)
    ).length;

    // ─── Render ───────────────────────────────────────────────────────────────────
    return (
        <SettingLayout
            title="Period Lock Management"
            subtitle="Lock reporting periods and manage user access per period"
        >
            {/* ── Financial Year filter ─────────────────────────────────────────────── */}
            <SettingsFilterCard>
                <FilterGroup>
                    <FilterLabel>Financial Year</FilterLabel>
                    <FilterSelect
                        value={selectedFinancialYear}
                        onChange={(e) => handleFinancialYearChange(e.target.value)}
                    >
                        <option value="">Select Financial Year</option>
                        {financialYearOptions.map((opt) => (
                            <option key={opt.value} value={opt.value}>{opt.label}</option>
                        ))}
                    </FilterSelect>
                </FilterGroup>
            </SettingsFilterCard>

            {/* ── Periods table ────────────────────────────────────────────────────────── */}
            {periodsData.length > 0 && (
                <SettingsCard>
                    <SettingsSectionHeader>
                        <i className="fas fa-lock" style={{ fontSize: 12, color: "#3f88a5" }} aria-hidden="true" />
                        <SettingsSectionTitle>Reporting Periods</SettingsSectionTitle>
                        <SettingsCountChip>{periodsData.length}</SettingsCountChip>
                        {lockedCount > 0 && (
                            <SettingsCountChip style={{ background: "#fee2e2", color: "#dc2626", marginLeft: 4 }}>
                                {lockedCount} locked
                            </SettingsCountChip>
                        )}
                    </SettingsSectionHeader>

                    <div style={{ overflowX: "auto" }}>
                        <SettingsTable>
                            <thead>
                                <tr>
                                    <SettingsTh style={{ width: 48 }}>#</SettingsTh>
                                    <SettingsTh style={{ minWidth: 160 }}>Period</SettingsTh>
                                    <SettingsTh style={{ minWidth: 180 }}>Date Range</SettingsTh>
                                    <SettingsTh>Status</SettingsTh>
                                    <SettingsTh style={{ textAlign: "right", minWidth: 200 }}>Actions</SettingsTh>
                                </tr>
                            </thead>
                            <tbody>
                                {periodsData.map((period, index) => {
                                    const isLocked = periodLockData.some(
                                        item => item.fromDate === period.fromDate && item.toDate === period.toDate
                                    );
                                    return (
                                        <SettingsTr key={period.periodValue}>
                                            <SettingsTd style={{ color: "#94a3b8", fontSize: 11 }}>{index + 1}</SettingsTd>
                                            <SettingsTd>
                                                <PeriodLabel>
                                                    <PeriodIcon>
                                                        <i className="fas fa-calendar-alt" style={{ fontSize: 12 }} />
                                                    </PeriodIcon>
                                                    {period.periodLabel}
                                                </PeriodLabel>
                                            </SettingsTd>
                                            <SettingsTd>
                                                {period.fromDate && period.toDate && (
                                                    <DateRangeChip>
                                                        <i className="fas fa-calendar" style={{ fontSize: 10 }} />
                                                        {period.fromDate}
                                                        <span style={{ color: "#94a3b8" }}>→</span>
                                                        {period.toDate}
                                                    </DateRangeChip>
                                                )}
                                            </SettingsTd>
                                            <SettingsTd>
                                                <SettingsStatusBadge $active={!isLocked}>
                                                    {isLocked ? "Locked" : "Open"}
                                                </SettingsStatusBadge>
                                            </SettingsTd>
                                            <SettingsTd>
                                                <ActionGroup>
                                                    <LockBtn
                                                        $variant="lock"
                                                        onClick={() => handleLockPeriod({ fromDate: period.fromDate, toDate: period.toDate })}
                                                    >
                                                        <i className="fas fa-lock" style={{ fontSize: 10 }} />
                                                        Lock
                                                    </LockBtn>

                                                    {isLocked && (
                                                        <>
                                                            <LockBtn
                                                                $variant="unlock"
                                                                onClick={() => {
                                                                    const matchedObj = periodLockData.find(
                                                                        item => item.fromDate === period.fromDate && item.toDate === period.toDate
                                                                    );
                                                                    handleSelectiveUnlock(matchedObj);
                                                                }}
                                                            >
                                                                <i className="fas fa-unlock" style={{ fontSize: 10 }} />
                                                                Unlock Users
                                                            </LockBtn>

                                                            <LockBtn
                                                                $variant="view"
                                                                onClick={() => {
                                                                    const matchedObj = periodLockData.find(
                                                                        item => item.fromDate === period.fromDate && item.toDate === period.toDate
                                                                    );
                                                                    openViewModal(matchedObj);
                                                                }}
                                                            >
                                                                <i className="fas fa-eye" style={{ fontSize: 10 }} />
                                                                View Users
                                                            </LockBtn>
                                                        </>
                                                    )}
                                                </ActionGroup>
                                            </SettingsTd>
                                        </SettingsTr>
                                    );
                                })}
                            </tbody>
                        </SettingsTable>
                    </div>
                </SettingsCard>
            )}

            {periodsData.length === 0 && !loading && (
                <SettingsCard>
                    <SettingsEmptyState>
                        <i className="fas fa-calendar-times s-empty-icon" />
                        <div className="s-empty-title">No periods available</div>
                        <div className="s-empty-sub">Select a financial year to view reporting periods.</div>
                    </SettingsEmptyState>
                </SettingsCard>
            )}

            {/* ── Lock Users Modal ──────────────────────────────────────────────────── */}
            <ShellModal
                show={showUserModal && modalType === 'lock'}
                onClose={closeAllModals}
                maxWidth={520}
            >
                <ModalHeader
                    icon="fas fa-lock"
                    title="Lock Period"
                    subtitle="Select users who will still have access to this period"
                    onClose={closeAllModals}
                />
                <SettingsModalBody>
                    <SettingsWarningBlock>
                        Selected users will retain access to modify data. Leave empty to lock for all users.
                    </SettingsWarningBlock>

                    {!usersLoading && users.length > 0 && (
                        <>
                            <SearchBar
                                searchQuery={userSearchQuery}
                                setSearchQuery={setUserSearchQuery}
                                placeholder="Search users by name or email…"
                                autoFocus
                            />
                            <SelectionBar>
                                <span>{filterUsers(users, userSearchQuery).length} users shown</span>
                                <SelectionActions>
                                    <SelectionActionBtn onClick={() => handleSelectAllUsers('lock')}>
                                        Select all{userSearchQuery && ' (filtered)'}
                                    </SelectionActionBtn>
                                    <SelectionActionBtn onClick={() => handleDeselectAllUsers('lock')}>
                                        Deselect all
                                    </SelectionActionBtn>
                                </SelectionActions>
                            </SelectionBar>
                        </>
                    )}

                    {usersLoading ? (
                        <div style={{ padding: "24px", textAlign: "center", color: "#94a3b8", fontSize: 13 }}>
                            Loading users…
                        </div>
                    ) : users.length === 0 ? (
                        <div style={{ padding: "24px", textAlign: "center", color: "#94a3b8", fontSize: 13 }}>
                            No users available
                        </div>
                    ) : (
                        <UserListWrap>
                            {filterUsers(users, userSearchQuery).map((user) => (
                                <UserItem
                                    key={user.userId}
                                    $selected={selectedUsersForLock.some(id => id === user.userId)}
                                >
                                    <Form.Check
                                        type="checkbox"
                                        id={`lock-user-${user.userId}`}
                                        checked={selectedUsersForLock.some(id => id === user.userId)}
                                        onChange={(e) => handleUserSelect(user.userId, e.target.checked, 'lock')}
                                    />
                                    <label
                                        htmlFor={`lock-user-${user.userId}`}
                                        style={{ cursor: "pointer", display: "flex", alignItems: "center", gap: 10, flex: 1 }}
                                    >
                                        <UserAvatar>
                                            {user.firstName?.[0] || 'U'}{user.lastName?.[0] || ''}
                                        </UserAvatar>
                                        <div>
                                            <UserName>{user.firstName} {user.lastName}</UserName>
                                            <UserEmail>{user.email}</UserEmail>
                                        </div>
                                    </label>
                                </UserItem>
                            ))}
                            {userSearchQuery && filterUsers(users, userSearchQuery).length === 0 && (
                                <div style={{ padding: "20px", textAlign: "center", color: "#94a3b8", fontSize: 12 }}>
                                    No users match "{userSearchQuery}"
                                </div>
                            )}
                        </UserListWrap>
                    )}

                    {!usersLoading && users.length > 0 && (
                        <SelectionSummary>
                            <i className="fas fa-users" style={{ fontSize: 11 }} />
                            {selectedUsersForLock.length} of {users.length} users selected
                            {selectedUsersForLock.length === 0 && (
                                <span style={{ color: "#dc2626", marginLeft: 6 }}>
                                    — period will be locked for everyone
                                </span>
                            )}
                        </SelectionSummary>
                    )}
                </SettingsModalBody>
                <SettingsModalFooter>
                    <SecondaryButton onClick={closeAllModals}>Cancel</SecondaryButton>
                    <DangerButton
                        onClick={() => confirmLockWithUsers(selectedUsersForLock, 'locked')}
                        disabled={actionLoading[currentLockingPeriod] || usersLoading}
                    >
                        <i className="fas fa-lock" style={{ marginRight: 6, fontSize: 11 }} />
                        {actionLoading[currentLockingPeriod] ? 'Locking…' : 'Lock Period'}
                    </DangerButton>
                </SettingsModalFooter>
            </ShellModal>

            {/* ── Unlock Users Modal ────────────────────────────────────────────────── */}
            <ShellModal
                show={showUnlockModal && modalType === 'unlock'}
                onClose={closeAllModals}
                maxWidth={520}
            >
                <ModalHeader
                    icon="fas fa-unlock"
                    title="Unlock Users"
                    subtitle="Select users to restore access for this locked period"
                    onClose={closeAllModals}
                />
                <SettingsModalBody>
                    <SearchBar
                        searchQuery={unlockSearchQuery}
                        setSearchQuery={setUnlockSearchQuery}
                        placeholder="Search users to unlock…"
                        autoFocus
                    />
                    <SelectionBar>
                        <span>
                            {filterUsers(getAllowedUsersForPeriod(currentUnlockingPeriod) || [], unlockSearchQuery).length} users shown
                        </span>
                        <SelectionActions>
                            <SelectionActionBtn onClick={() => handleSelectAllUsers('unlock')}>
                                Select all{unlockSearchQuery && ' (filtered)'}
                            </SelectionActionBtn>
                            <SelectionActionBtn onClick={() => handleDeselectAllUsers('unlock')}>
                                Deselect all
                            </SelectionActionBtn>
                        </SelectionActions>
                    </SelectionBar>

                    <UserListWrap>
                        {filterUsers(getAllowedUsersForPeriod(currentUnlockingPeriod) || [], unlockSearchQuery).map((user) => (
                            <UserItem
                                key={user.userId}
                                $selected={selectedUsersForUnlock.some(id => id === user.userId)}
                                $color="amber"
                            >
                                <Form.Check
                                    type="checkbox"
                                    id={`unlock-user-${user.userId}`}
                                    checked={selectedUsersForUnlock.some(id => id === user.userId)}
                                    onChange={(e) => handleUserSelect(user.userId, e.target.checked, 'unlock')}
                                />
                                <label
                                    htmlFor={`unlock-user-${user.userId}`}
                                    style={{ cursor: "pointer", display: "flex", alignItems: "center", gap: 10, flex: 1 }}
                                >
                                    <UserAvatar $color="amber">
                                        {user.firstName?.[0] || 'U'}{user.lastName?.[0] || ''}
                                    </UserAvatar>
                                    <div>
                                        <UserName>{user.firstName} {user.lastName}</UserName>
                                        <UserEmail>{user.email}</UserEmail>
                                    </div>
                                </label>
                            </UserItem>
                        ))}

                        {unlockSearchQuery && filterUsers(getAllowedUsersForPeriod(currentUnlockingPeriod) || [], unlockSearchQuery).length === 0 && (
                            <div style={{ padding: "20px", textAlign: "center", color: "#94a3b8", fontSize: 12 }}>
                                No users match "{unlockSearchQuery}"
                            </div>
                        )}

                        {(!currentUnlockingPeriod || getAllowedUsersForPeriod(currentUnlockingPeriod).length === 0) && (
                            <div style={{ padding: "20px", textAlign: "center", color: "#94a3b8", fontSize: 12 }}>
                                No locked users available to unlock
                            </div>
                        )}
                    </UserListWrap>

                    {selectedUsersForUnlock.length > 0 && (
                        <SelectionSummary>
                            <i className="fas fa-unlock" style={{ fontSize: 11 }} />
                            {selectedUsersForUnlock.length} user{selectedUsersForUnlock.length !== 1 ? 's' : ''} selected for unlock
                        </SelectionSummary>
                    )}
                </SettingsModalBody>
                <SettingsModalFooter>
                    <SecondaryButton onClick={closeAllModals}>Cancel</SecondaryButton>
                    <PrimaryButton
                        onClick={() =>
                            confirmLockWithUsers([
                                ...selectedUsersForUnlock,
                                ...getUnallowedUsersForPeriod(currentUnlockingPeriod).map(user => user.userId),
                            ], 'unlocked')
                        }
                        disabled={actionLoading[currentUnlockingPeriod] || selectedUsersForUnlock.length === 0}
                    >
                        <i className="fas fa-unlock" style={{ marginRight: 6, fontSize: 11 }} />
                        {actionLoading[currentUnlockingPeriod] ? 'Unlocking…' : 'Unlock Selected'}
                    </PrimaryButton>
                </SettingsModalFooter>
            </ShellModal>

            {/* ── View Users Modal ──────────────────────────────────────────────────── */}
            <ShellModal
                show={showViewModal && modalType === 'view'}
                onClose={closeAllModals}
                maxWidth={680}
            >
                <ModalHeader
                    icon="fas fa-users"
                    title="Period Users Status"
                    subtitle="Users allowed vs restricted for this locked period"
                    onClose={closeAllModals}
                />
                <SettingsModalBody>
                    <ViewGrid>
                        {/* Allowed Users */}
                        <ViewColumn>
                            <ViewColumnHeader $color="green">
                                <i className="fas fa-check-circle" style={{ fontSize: 13 }} />
                                Allowed Users
                                <SettingsCountChip style={{ background: "#dcfce7", color: "#15803d" }}>
                                    {(getUnallowedUsersForPeriod(currentViewingPeriod) || []).length}
                                </SettingsCountChip>
                            </ViewColumnHeader>

                            <SearchBar
                                searchQuery={allowedUsersSearchQuery}
                                setSearchQuery={setAllowedUsersSearchQuery}
                                placeholder="Search allowed users…"
                                autoFocus
                            />

                            <ViewListWrap $color="green">
                                {!currentViewingPeriod || getUnallowedUsersForPeriod(currentViewingPeriod).length === 0 ? (
                                    <div style={{ padding: "24px", textAlign: "center", color: "#94a3b8", fontSize: 12 }}>
                                        <i className="fas fa-lock" style={{ fontSize: 20, marginBottom: 8, display: "block", color: "#cbd5e1" }} />
                                        No users allowed — fully locked
                                    </div>
                                ) : (
                                    <>
                                        {filterUsers(getUnallowedUsersForPeriod(currentViewingPeriod), allowedUsersSearchQuery).map((user) => (
                                            <UserItem key={user.userId} $color="green">
                                                <UserAvatar $color="green">
                                                    {user.firstName?.[0] || 'U'}{user.lastName?.[0] || ''}
                                                </UserAvatar>
                                                <div>
                                                    <UserName>{user.firstName} {user.lastName}</UserName>
                                                    <UserEmail>{user.email}</UserEmail>
                                                </div>
                                            </UserItem>
                                        ))}
                                        {allowedUsersSearchQuery && filterUsers(getUnallowedUsersForPeriod(currentViewingPeriod), allowedUsersSearchQuery).length === 0 && (
                                            <div style={{ padding: "16px", textAlign: "center", color: "#94a3b8", fontSize: 12 }}>
                                                No match for "{allowedUsersSearchQuery}"
                                            </div>
                                        )}
                                    </>
                                )}
                            </ViewListWrap>
                        </ViewColumn>

                        {/* Restricted Users */}
                        <ViewColumn>
                            <ViewColumnHeader $color="red">
                                <i className="fas fa-times-circle" style={{ fontSize: 13 }} />
                                Restricted Users
                                <SettingsCountChip style={{ background: "#fee2e2", color: "#dc2626" }}>
                                    {(getAllowedUsersForPeriod(currentViewingPeriod) || []).length}
                                </SettingsCountChip>
                            </ViewColumnHeader>

                            <SearchBar
                                searchQuery={unallowedUsersSearchQuery}
                                setSearchQuery={setUnallowedUsersSearchQuery}
                                placeholder="Search restricted users…"
                            />

                            <ViewListWrap $color="red">
                                {!currentViewingPeriod || getAllowedUsersForPeriod(currentViewingPeriod).length === 0 ? (
                                    <div style={{ padding: "24px", textAlign: "center", color: "#94a3b8", fontSize: 12 }}>
                                        <i className="fas fa-unlock" style={{ fontSize: 20, marginBottom: 8, display: "block", color: "#cbd5e1" }} />
                                        All users have access
                                    </div>
                                ) : (
                                    <>
                                        {filterUsers(getAllowedUsersForPeriod(currentViewingPeriod), unallowedUsersSearchQuery).map((user) => (
                                            <UserItem key={user.userId} $color="red">
                                                <UserAvatar $color="red">
                                                    {user.firstName?.[0] || 'U'}{user.lastName?.[0] || ''}
                                                </UserAvatar>
                                                <div>
                                                    <UserName>{user.firstName} {user.lastName}</UserName>
                                                    <UserEmail>{user.email}</UserEmail>
                                                </div>
                                            </UserItem>
                                        ))}
                                        {unallowedUsersSearchQuery && filterUsers(getAllowedUsersForPeriod(currentViewingPeriod), unallowedUsersSearchQuery).length === 0 && (
                                            <div style={{ padding: "16px", textAlign: "center", color: "#94a3b8", fontSize: 12 }}>
                                                No match for "{unallowedUsersSearchQuery}"
                                            </div>
                                        )}
                                    </>
                                )}
                            </ViewListWrap>
                        </ViewColumn>
                    </ViewGrid>
                </SettingsModalBody>
                <SettingsModalFooter>
                    <SecondaryButton onClick={closeAllModals}>Close</SecondaryButton>
                </SettingsModalFooter>
            </ShellModal>
        </SettingLayout>
    );
};

export default LockQuestion;