// Root component: owns ALL state + event handlers, and composes the screens/tabs/modals.
// Firestore reads/writes live here (search for `db.`) - see README "Connecting your backend".
function App() {
    const [lang, setLang] = useState('en');
    const strings = t[lang];

    const [currentUser, setCurrentUser] = useState(null);
    const [isAssistantView, setIsAssistantView] = useState(false);
    const [originalAdminUser, setOriginalAdminUser] = useState(null);
    const [loginUsername, setLoginUsername] = useState('');
    const [loginPassword, setLoginPassword] = useState('');
    const [loginError, setLoginError] = useState('');
    const [assistantLoginMode, setAssistantLoginMode] = useState(false);

    const [rawStaff, setDoctors] = useState([]);
    const staff = useMemo(() => rawStaff.map(normalizeStaff), [rawStaff]);
    const doctors = useMemo(() => staff.filter(d => d.role !== 'assistant'), [staff]);
    const [staffError, setStaffError] = useState('');
    const [staffBranchFilter, setStaffBranchFilter] = useState('all');
    const [doctorsLoaded, setDoctorsLoaded] = useState(false);
    const [inventory, setInventory] = useState([]);
    const [patients, setPatients] = useState([]);
    const [appointments, setAppointments] = useState([]);
    const [activityLogs, setActivityLogs] = useState([]);

    const [activeTab, setActiveTab] = useState('dashboard');

    const [patientSearch, setPatientSearch] = useState('');
    const [inventorySearch, setInventorySearch] = useState('');
    const [doctorSearch, setDoctorSearch] = useState('');
    const [appointmentSearch, setAppointmentSearch] = useState('');

    const [showAddPatient, setShowAddPatient] = useState(false);
    const [showAddInventory, setShowAddInventory] = useState(false);
    const [showAddDoctor, setShowAddDoctor] = useState(false);
    const [showPatientDetailModal, setShowPatientDetailModal] = useState(false);
    const [selectedPatient, setSelectedPatient] = useState(null);
    const [showPrescriptionModal, setShowPrescriptionModal] = useState(false);
    const [showProfileModal, setShowProfileModal] = useState(false);
    const [showAssistantPicker, setShowAssistantPicker] = useState(false);
    const [avatarNotice, setAvatarNotice] = useState('');

    const [showEditPatient, setShowEditPatient] = useState(false);
    const [editingPatient, setEditingPatient] = useState(null);
    const [showEditInventory, setShowEditInventory] = useState(false);
    const [editingInventory, setEditingInventory] = useState(null);

    const [showEditRxModal, setShowEditRxModal] = useState(false);
    const [editingRx, setEditingRx] = useState(null);
    const [showEditVisitModal, setShowEditVisitModal] = useState(false);
    const [editingVisit, setEditingVisit] = useState(null);
    const [showAssessmentModal, setShowAssessmentModal] = useState(false);
    
    // Print Prescription Modal State
    const [showPrintRxModal, setShowPrintRxModal] = useState(false);
    const [activePrescriptionToPrint, setActivePrescriptionToPrint] = useState(null);

    const [assessmentData, setAssessmentData] = useState({
        bodyComp: { weight: '', height: '', bmi: '', bodyFat: '', muscleMass: '', visceralFat: '', waist: '' },
        weightHistory: { currentWeight: '', highestWeight: '', previousLoss: '', regain: '' },
        medicalHistory: { conditions: '', surgeries: '', medications: '', allergies: '' },
        lifestyle: { meals: '', snacks: '', water: '', activity: '', sleep: '', habits: '' },
        prevTreatment: { diets: '', meds: '', response: '', sideEffects: '' },
        labs: { hba1c: '', glucose: '', lipids: '', tsh: '', organFunc: '', other: '' },
        doctorAssessment: { mainConcern: '', patientGoal: '', clinicalAssessment: '' },
        managementPlan: { nutritionPlan: false, lifestyleMod: false, pharmacotherapy: false, nutritionPharm: false, investigations: false, followUp: false, treatmentPlan: '', followUpDays: '' }
    });

    const [newPatient, setNewPatient] = useState({ name: '', age: '', phone: '', gender: 'Male', diagnosis: '', triage: 'Routine', notes: '' });
    const [newInventory, setNewInventory] = useState({ name: '', category: 'Antibiotics', stock: '', minStock: '', expiryDate: '', doctorId: 'personal', batch: '' });
    const [newDoctor, setNewDoctor] = useState({ role: 'doctor', branchId: 'mansoura', branchIds: ['mansoura'], name: '', specialty: '', email: '', username: '', password: '', avatar: 'https://images.unsplash.com/photo-1537368910025-700350fe46c7?w=150&auto=format&fit=crop&q=80' });
    
    const [assistantBooking, setAssistantBooking] = useState({
        patientName: '',
        phone: '',
        doctorId: '',
        date: new Date().toISOString().split('T')[0],
        time: '10:00 AM',
        status: 'Waiting',
        notes: ''
    });
    const [bookingNotice, setBookingNotice] = useState('');

    const [rxForm, setRxForm] = useState({ selectedItem: '', customMedication: '', dosage: '', instructions: '' });
    const [profileAvatarUrl, setProfileAvatarUrl] = useState('');

    const DEFAULT_LOGO = '828840397_122208223112912543_5718258203700920762_n.jpg';
    const [clinicLogo, setClinicLogo] = useState(() => { try { return localStorage.getItem('heptaLogo') || DEFAULT_LOGO; } catch (e) { return DEFAULT_LOGO; } });
    const [logoNotice, setLogoNotice] = useState('');

    // ===== Inventory categories (defaults + user-added, synced via Firestore with local fallback) =====
    const DEFAULT_CATEGORIES = ['Antibiotics', 'Analgesics', 'Dermatology', 'Pediatrics', 'Supplies'];
    const [customCategories, setCustomCategories] = useState(() => { try { return JSON.parse(localStorage.getItem('heptaCategories') || '[]'); } catch (e) { return []; } });
    const [addingCategory, setAddingCategory] = useState(false);
    const [newCategoryName, setNewCategoryName] = useState('');

    useEffect(() => {
        const unsub = db.collection("settings").doc("inventoryCategories").onSnapshot(doc => {
            const list = doc.exists && Array.isArray(doc.data().list) ? doc.data().list : null;
            if (list) { setCustomCategories(list); try { localStorage.setItem('heptaCategories', JSON.stringify(list)); } catch (e) {} }
        }, () => {});
        return () => unsub();
    }, []);

    useEffect(() => {
        if (!showAddInventory && !showEditInventory) { setAddingCategory(false); setNewCategoryName(''); }
    }, [showAddInventory, showEditInventory]);

    useEffect(() => {
        const unsub = db.collection("settings").doc("branding").onSnapshot(doc => {
            const logo = doc.exists ? doc.data().logo : null;
            if (logo) { setClinicLogo(logo); try { localStorage.setItem('heptaLogo', logo); } catch (e) {} }
        }, () => {});
        return () => unsub();
    }, []);

    // ===== Editable branch names =====
    const [, setBranchNamesVer] = useState(0);
    const [branchDraft, setBranchDraft] = useState({});
    const [branchNotice, setBranchNotice] = useState('');
    useEffect(() => {
        const unsub = db.collection("settings").doc("branches").onSnapshot(doc => {
            const names = doc.exists && doc.data().names && typeof doc.data().names === 'object' ? doc.data().names : null;
            if (names) {
                applyBranchNames(names);
                try { localStorage.setItem('heptaBranchNames', JSON.stringify(names)); } catch (e) {}
                setBranchNamesVer(v => v + 1);
            }
        }, () => {});
        return () => unsub();
    }, []);

    const saveBranchNames = async () => {
        const names = {};
        BRANCHES.forEach(b => {
            const v = (branchDraft[b.id] !== undefined ? branchDraft[b.id] : b.name).trim();
            names[b.id] = v || DEFAULT_BRANCH_NAMES[b.id];
        });
        applyBranchNames(names);
        try { localStorage.setItem('heptaBranchNames', JSON.stringify(names)); } catch (e) {}
        setBranchNamesVer(v => v + 1);
        setBranchDraft({});
        try {
            await db.collection("settings").doc("branches").set({ names });
            setBranchNotice(lang === 'ar' ? 'تم حفظ أسماء الفروع.' : 'Branch names saved.');
        } catch (err) {
            setBranchNotice(lang === 'ar' ? 'تم التغيير على هذا الجهاز فقط (تعذّر الحفظ السحابي).' : 'Changed on this device only (cloud save failed).');
        }
        setTimeout(() => setBranchNotice(''), 4000);
    };

    const saveLogo = async (data) => {
        setClinicLogo(data || DEFAULT_LOGO);
        try { data ? localStorage.setItem('heptaLogo', data) : localStorage.removeItem('heptaLogo'); } catch (e) {}
        try {
            await db.collection("settings").doc("branding").set({ logo: data || '' });
            setLogoNotice(lang === 'ar' ? 'تم حفظ الشعار.' : 'Logo saved.');
        } catch (err) {
            setLogoNotice(lang === 'ar' ? 'تم تغيير الشعار على هذا الجهاز فقط (تعذّر الحفظ السحابي).' : 'Logo changed on this device only (cloud save failed).');
        }
        setTimeout(() => setLogoNotice(''), 4000);
    };

    const handleLogoUpload = (e) => {
        const file = e.target.files && e.target.files[0];
        e.target.value = '';
        if (!file) return;
        if (!file.type.startsWith('image/')) { setLogoNotice(lang === 'ar' ? 'من فضلك اختر صورة.' : 'Please choose an image file.'); return; }
        const reader = new FileReader();
        reader.onload = (ev) => {
            const img = new Image();
            img.onload = () => {
                const ratio = Math.min(1, 320 / Math.max(img.width, img.height));
                const c = document.createElement('canvas');
                c.width = Math.round(img.width * ratio); c.height = Math.round(img.height * ratio);
                c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
                saveLogo(file.type === 'image/png' ? c.toDataURL('image/png') : c.toDataURL('image/jpeg', 0.9));
            };
            img.src = ev.target.result;
        };
        reader.readAsDataURL(file);
    };

    useEffect(() => {
        // Doc id from Firestore must ALWAYS win over any "id" field stored inside the data
        const toList = (snapshot) => snapshot.docs.map(doc => ({ ...doc.data(), id: doc.id }));

        const unsubDoctors = db.collection("doctors").onSnapshot(async snapshot => {
            if (snapshot.metadata.fromCache && snapshot.empty) return; // wait for real server data
            let list = toList(snapshot);
            if (list.length === 0) {
                for (let doc of INITIAL_DOCTORS) {
                    await db.collection("doctors").doc(doc.id).set(doc);
                }
                list = INITIAL_DOCTORS;
            }
            if (!list.some(d => d.id === 'doc-hassan')) {
                const hassan = INITIAL_DOCTORS.find(d => d.id === 'doc-hassan');
                await db.collection("doctors").doc('doc-hassan').set(hassan);
                list = [...list, hassan];
            }
            setDoctors(list);
            if (list.length > 0 && !assistantBooking.doctorId) {
                setAssistantBooking(prev => ({ ...prev, doctorId: list[0].id }));
            }
            setDoctorsLoaded(true);
        });

        // No demo data is ever written for these collections: whatever you delete stays deleted.
        // An EMPTY snapshot is only ignored while we are still waiting for the very first server answer.
        // Once the server has answered (or a local delete is pending), an empty list is real and must be shown.
        const makeListener = (name, initial, setter) => {
            let gotServerData = false;
            return db.collection(name).onSnapshot(snapshot => {
                if (!snapshot.metadata.fromCache) gotServerData = true;
                if (snapshot.empty && snapshot.metadata.fromCache && !gotServerData && !snapshot.metadata.hasPendingWrites) return;
                if (gotServerData) snapshot.docChanges().forEach(ch => { if (ch.type === 'added') console.warn('[SYNC] ' + name + ' doc appeared:', ch.doc.id, 'fromCache=' + snapshot.metadata.fromCache, 'pendingWrites=' + ch.doc.metadata.hasPendingWrites); });
                setter(toList(snapshot));
            }, err => console.error("Listener error on " + name + ":", err));
        };

        const unsubInventory = makeListener("inventory", null, setInventory);
        const unsubPatients = makeListener("patients", null, setPatients);
        const unsubAppointments = makeListener("appointments", null, setAppointments);

        return () => {
            unsubDoctors();
            unsubInventory();
            unsubPatients();
            unsubAppointments();
        };
    }, []);

    useEffect(() => {
        if (window.lucide) {
            window.lucide.createIcons();
        }
    });

    const logActivity = (text, type) => {
        const now = new Date();
        const timeStr = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;
        setActivityLogs(prev => [{ id: `log-${Date.now()}`, time: timeStr, text, type }, ...prev.slice(0, 9)]);
    };

    const handleImageUpload = (e, callback) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => callback(reader.result);
            reader.readAsDataURL(file);
        }
    };

    const handleLogin = (e) => {
        e.preventDefault();
        if (!doctorsLoaded) return;
        const found = staff.find(d => (d.username.trim().toLowerCase() === loginUsername.trim().toLowerCase() || d.email.trim().toLowerCase() === loginUsername.trim().toLowerCase()) && d.password === loginPassword && d.status === 'Active');
        if (found && assistantLoginMode && found.role !== 'assistant') {
            setLoginError(lang === 'ar' ? 'هذا الدخول للمساعدين فقط. استخدم تسجيل دخول الموظفين.' : 'This login is for assistants only. Please use the staff login.');
            return;
        }
        if (found && !assistantLoginMode && found.role === 'assistant') {
            setLoginError(lang === 'ar' ? 'المساعدون يدخلون من زر "دخول المساعد".' : 'Assistants must sign in with the "Assistant Login" button.');
            return;
        }
        if (found) {
            setCurrentUser(found);
            setOriginalAdminUser(null);
            setProfileAvatarUrl(found.avatar);
            setLoginError('');
            setIsAssistantView(false);
            setActiveTab('dashboard');
            logActivity(`${found.name} logged into portal`, 'system');
        } else {
            setLoginError(lang === 'ar' ? 'بيانات الاعتماد غير صالحة أو الحساب معطل.' : 'Invalid credentials or account disabled.');
        }
    };

    const handleLogout = () => {
        if (currentUser) logActivity(`${currentUser.name} logged out`, 'system');
        setCurrentUser(null);
        setOriginalAdminUser(null);
        setIsAssistantView(false);
        setAssistantLoginMode(false);
        setLoginUsername('');
        setLoginPassword('');
    };

    const handleImpersonateDoctor = (doc) => {
        if (currentUser.isAdmin && !originalAdminUser) {
            setOriginalAdminUser(currentUser);
        }
        setCurrentUser(doc);
        setProfileAvatarUrl(doc.avatar);
        setActiveTab('dashboard');
        logActivity(`Admin switched view to ${doc.name}`, 'system');
    };

    const handleReturnToAdmin = () => {
        if (originalAdminUser) {
            setCurrentUser(originalAdminUser);
            setProfileAvatarUrl(originalAdminUser.avatar);
            setActiveTab(originalAdminUser.isAdmin ? 'doctors' : 'dashboard');
            setOriginalAdminUser(null);
        }
    };

    // Opens the portal of the assistant chosen in the picker.
    // Admins can open any assistant; a doctor only the assistants of the doctor's own branches.
    const openAssistantPortal = (asst) => {
        if (!currentUser || currentUser.role === 'assistant') return;
        const viewerIsAdmin = !!((originalAdminUser || currentUser).isAdmin);
        if (!viewerIsAdmin && !(currentUser.branchIds || []).includes(asst.branchId)) return;
        if (!originalAdminUser) setOriginalAdminUser(currentUser);
        setCurrentUser(asst);
        setProfileAvatarUrl(asst.avatar);
        setShowAssistantPicker(false);
        logActivity(`${currentUser.name} opened the portal of assistant ${asst.name}`, 'system');
    };

    // An assistant uploads / changes her own profile picture (compressed to keep the record small).
    const handleAssistantAvatarUpload = (e) => {
        const file = e.target.files && e.target.files[0];
        e.target.value = '';
        if (!file || !currentUser || currentUser.role !== 'assistant') return;
        if (!file.type.startsWith('image/')) { setAvatarNotice(lang === 'ar' ? 'من فضلك اختر صورة.' : 'Please choose an image file.'); return; }
        const reader = new FileReader();
        reader.onload = (ev) => {
            const img = new Image();
            img.onload = async () => {
                const ratio = Math.min(1, 256 / Math.max(img.width, img.height));
                const c = document.createElement('canvas');
                c.width = Math.round(img.width * ratio); c.height = Math.round(img.height * ratio);
                c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
                const dataUrl = c.toDataURL('image/jpeg', 0.85);
                try {
                    await db.collection("doctors").doc(currentUser.id).update({ avatar: dataUrl });
                    setCurrentUser(prev => ({ ...prev, avatar: dataUrl }));
                    setProfileAvatarUrl(dataUrl);
                    setAvatarNotice(lang === 'ar' ? 'تم تحديث الصورة.' : 'Profile picture updated.');
                    logActivity(`${currentUser.name} updated profile avatar`, 'system');
                } catch (err) {
                    setAvatarNotice(lang === 'ar' ? 'تعذّر حفظ الصورة.' : 'Could not save the picture.');
                }
                setTimeout(() => setAvatarNotice(''), 4000);
            };
            img.src = ev.target.result;
        };
        reader.readAsDataURL(file);
    };

    const handleAssistantBookSubmit = async (e) => {
        e.preventDefault();
        const chosenDoctorId = bookingDoctorId;
        if (!assistantBooking.patientName || !chosenDoctorId) return;
        if (!currentUser || (currentUser.role !== 'assistant' && !currentUser.isAdmin)) return;

        const aptId = `apt-${Date.now()}`;
        const targetDoctor = doctors.find(d => d.id === chosenDoctorId);
        // Branch lock: an assistant can only book with a doctor of their own branch.
        if (currentUser.role === 'assistant' && (!targetDoctor || !targetDoctor.branchIds.includes(currentUser.branchId))) return;
        const newApt = {
            id: aptId,
            patientName: assistantBooking.patientName,
            phone: assistantBooking.phone || '',
            doctorId: chosenDoctorId,
            branchId: currentUser.role === 'assistant' ? currentUser.branchId : '',
            doctorName: targetDoctor ? targetDoctor.name : 'Doctor',
            date: assistantBooking.date,
            time: assistantBooking.time,
            status: assistantBooking.status || 'Waiting',
            notes: assistantBooking.notes || 'Booked by Assistant'
        };

        await db.collection("appointments").doc(aptId).set(newApt);
        logActivity(`Assistant booked appointment for ${assistantBooking.patientName} with ${targetDoctor ? targetDoctor.name : ''}`, 'patient');
        
        setBookingNotice(strings.bookingSuccess);
        setAssistantBooking({
            patientName: '',
            phone: '',
            doctorId: '',
            date: new Date().toISOString().split('T')[0],
            time: '10:00 AM',
            status: 'Waiting',
            notes: ''
        });

        setTimeout(() => setBookingNotice(''), 4000);
    };

    const handleUpdateAvatar = async (e) => {
        e.preventDefault();
        await db.collection("doctors").doc(currentUser.id).update({ avatar: profileAvatarUrl });
        setCurrentUser({ ...currentUser, avatar: profileAvatarUrl });
        setShowProfileModal(false);
        logActivity(`${currentUser.name} updated profile avatar`, 'system');
    };

    const handleUpdateAppointmentStatus = async (aptId, newStatus) => {
        if (currentUser?.role === 'assistant') {
            const apt = appointments.find(a => a.id === aptId);
            if (!apt || aptBranchId(apt) !== currentUser.branchId) return;
        }
        await db.collection("appointments").doc(aptId).update({ status: newStatus });
        logActivity(`Appointment ${aptId} status updated to ${newStatus}`, 'patient');
    };

    const handleOpenAssessment = (patient) => {
        setSelectedPatient(patient);
        if (patient.assessment) {
            setAssessmentData(patient.assessment);
        } else {
            setAssessmentData({
                bodyComp: { weight: '', height: '', bmi: '', bodyFat: '', muscleMass: '', visceralFat: '', waist: '' },
                weightHistory: { currentWeight: '', highestWeight: '', previousLoss: '', regain: '' },
                medicalHistory: { conditions: '', surgeries: '', medications: '', allergies: '' },
                lifestyle: { meals: '', snacks: '', water: '', activity: '', sleep: '', habits: '' },
                prevTreatment: { diets: '', meds: '', response: '', sideEffects: '' },
                labs: { hba1c: '', glucose: '', lipids: '', tsh: '', organFunc: '', other: '' },
                doctorAssessment: { mainConcern: '', patientGoal: '', clinicalAssessment: '' },
                managementPlan: { nutritionPlan: false, lifestyleMod: false, pharmacotherapy: false, nutritionPharm: false, investigations: false, followUp: false, treatmentPlan: '', followUpDays: '' }
            });
        }
        setShowAssessmentModal(true);
    };

    const handleSaveAssessment = async (e) => {
        e.preventDefault();
        if (!selectedPatient) return;
        await db.collection("patients").doc(selectedPatient.id).update({
            assessment: assessmentData
        });
        setSelectedPatient({ ...selectedPatient, assessment: assessmentData });
        setShowAssessmentModal(false);
        logActivity(`Saved initial assessment for ${selectedPatient.name}`, 'patient');
        alert(lang === 'ar' ? 'تم حفظ التقييم الأولي بنجاح!' : 'Initial assessment saved successfully!');
    };

    const handleSaveAndPrintAssessment = async () => {
        if (!selectedPatient) return;
        try {
            await db.collection("patients").doc(selectedPatient.id).update({ assessment: assessmentData });
            setSelectedPatient({ ...selectedPatient, assessment: assessmentData });
            logActivity(`Saved initial assessment for ${selectedPatient.name}`, 'patient');
        } catch (err) {
            alert(lang === 'ar' ? 'تعذّر حفظ التقييم، سيتم الطباعة فقط.' : 'Could not save the assessment - printing only.');
        }
        handlePrintAssessment();
    };

    const handlePrintAssessment = () => {
        if (!selectedPatient) return;
        const d = assessmentData;
        const esc = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));
        const val = (v) => (v && String(v).trim()) ? esc(v) : '<span class="empty">&mdash;</span>';
        const field = (label, v) => `<div class="f"><span class="l">${esc(label)}</span><span class="v" dir="auto">${val(v)}</span></div>`;
        const block = (label, v) => `<div class="b"><div class="l">${esc(label)}</div><div class="v" dir="auto">${val(v)}</div></div>`;
        const section = (title, items, cols) => `<section><h3>${esc(title)}</h3><div class="g g${cols || 1}">${items.join('')}</div></section>`;
        const plan = d.managementPlan || {};
        const check = (on, label) => `<div class="c"><span class="box">${on ? '&#9745;' : '&#9744;'}</span> ${esc(label)}</div>`;
        const today = new Date().toISOString().split('T')[0];
        let logoSrc = clinicLogo;
        try { logoSrc = new URL(clinicLogo, window.location.href).href; } catch (e) {}

        const html = `<!DOCTYPE html>
<html lang="en" dir="ltr"><head><meta charset="utf-8"><title>${esc(strings.patientAssessment)} - ${esc(selectedPatient.name)}</title>
<style>
@page { size: A4; margin: 12mm; }
* { box-sizing: border-box; }
body { margin: 0; font-family: 'Segoe UI', Tahoma, Arial, sans-serif; color: #1f3a4d; font-size: 11px; line-height: 1.45; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
.head { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #1f3a4d; padding-bottom: 8px; margin-bottom: 10px; }
.brand { display: flex; align-items: center; gap: 10px; }
.brand img { width: 46px; height: 46px; object-fit: contain; border: 1px solid #ddd; border-radius: 10px; }
.brand h1 { margin: 0; font-size: 17px; }
.brand p { margin: 0; font-size: 10px; color: #5b6f7e; font-weight: 600; }
.meta { text-align: right; font-size: 10px; font-weight: 600; }
.title { text-align: center; font-size: 14px; font-weight: 800; letter-spacing: .04em; text-transform: uppercase; margin: 4px 0 10px; }
.patient { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 16px; background: #f4f1ea; border: 1px solid #ddd5c6; border-radius: 8px; padding: 8px 12px; margin-bottom: 10px; }
.patient .l { color: #5b6f7e; text-transform: uppercase; font-size: 9.5px; font-weight: 700; margin-right: 4px; }
.patient .v { font-weight: 700; }
.cols { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
section { border: 1px solid #ddd5c6; border-radius: 8px; padding: 7px 10px 8px; break-inside: avoid; margin-bottom: 8px; }
section h3 { margin: 0 0 5px; padding-bottom: 3px; border-bottom: 1px solid #ddd5c6; font-size: 10px; letter-spacing: .06em; text-transform: uppercase; }
.g { display: grid; gap: 3px 12px; }
.g1 { grid-template-columns: 1fr; }
.g2 { grid-template-columns: 1fr 1fr; }
.f { display: flex; justify-content: space-between; gap: 8px; border-bottom: 1px dotted #ddd5c6; padding: 1px 0; }
.f .l { color: #5b6f7e; font-weight: 600; }
.f .v { font-weight: 700; text-align: right; }
.b { margin-bottom: 5px; }
.b .l { color: #5b6f7e; font-weight: 700; font-size: 10px; margin-bottom: 1px; }
.b .v { white-space: pre-wrap; min-height: 16px; border-bottom: 1px dotted #ddd5c6; }
.empty { color: #a9b4bc; }
.checks { display: grid; grid-template-columns: 1fr 1fr; gap: 3px 10px; margin-bottom: 6px; }
.c { font-weight: 600; }
.box { font-size: 14px; vertical-align: -1px; }
.wide { margin-top: 2px; }
.foot { margin-top: 18px; padding-top: 10px; border-top: 1px solid #ddd5c6; display: flex; justify-content: space-between; align-items: flex-end; break-inside: avoid; }
.foot .note { font-size: 9.5px; color: #5b6f7e; }
.sig { text-align: center; }
.sig .name { height: 34px; font-family: Georgia, serif; font-style: italic; font-weight: 700; font-size: 15px; display: flex; align-items: center; justify-content: center; }
.sig .line { width: 190px; border-top: 1px solid #1f3a4d; padding-top: 3px; font-weight: 700; font-size: 10px; }
</style></head><body>
<div class="head">
  <div class="brand"><img src="${esc(logoSrc)}" alt=""><div><h1>${esc(strings.appName)}</h1><p>${esc(currentUser.name)}${currentUser.specialty ? ' &bull; ' + esc(currentUser.specialty) : ''}</p></div></div>
  <div class="meta"><div>${esc(strings.date)}: ${esc(today)}</div></div>
</div>
<div class="title">${esc(strings.patientAssessment)}</div>
<div class="patient">
  <div><span class="l">${esc(strings.patientName)}:</span><span class="v" dir="auto">${esc(selectedPatient.name)}</span></div>
  <div><span class="l">${esc(strings.ageGender)}:</span><span class="v">${esc(selectedPatient.age)} yrs / ${esc(selectedPatient.gender)}</span></div>
  <div><span class="l">${esc(strings.phone)}:</span><span class="v">${esc(selectedPatient.phone)}</span></div>
  <div><span class="l">${esc(strings.diagnosis)}:</span><span class="v" dir="auto">${esc(selectedPatient.diagnosis)}</span></div>
</div>
<div class="cols">
  <div>
    ${section('01 | Body Composition', [field('Weight', d.bodyComp.weight), field('Height', d.bodyComp.height), field('BMI', d.bodyComp.bmi), field('Body Fat', d.bodyComp.bodyFat), field('Muscle Mass', d.bodyComp.muscleMass), field('Visceral Fat', d.bodyComp.visceralFat), field('Waist', d.bodyComp.waist)])}
    ${section('03 | Medical History', [field('Medical Conditions', d.medicalHistory.conditions), field('Surgeries', d.medicalHistory.surgeries), field('Current Medications', d.medicalHistory.medications), field('Allergies', d.medicalHistory.allergies)])}
    ${section('05 | Previous Treatment', [field('Previous Diets', d.prevTreatment.diets), field('Weight-loss Medications', d.prevTreatment.meds), field('Response', d.prevTreatment.response), field('Side Effects', d.prevTreatment.sideEffects)])}
  </div>
  <div>
    ${section('02 | Weight History', [field('Current Weight', d.weightHistory.currentWeight), field('Highest Weight', d.weightHistory.highestWeight), field('Previous Weight Loss', d.weightHistory.previousLoss), field('Weight Regain', d.weightHistory.regain)])}
    ${section('04 | Lifestyle & Nutrition', [field('Meals', d.lifestyle.meals), field('Snacks', d.lifestyle.snacks), field('Water Intake', d.lifestyle.water), field('Physical Activity', d.lifestyle.activity), field('Sleep', d.lifestyle.sleep), field('Eating Habits', d.lifestyle.habits)])}
    ${section('06 | Labs & Risk Factors', [field('HbA1c', d.labs.hba1c), field('Glucose', d.labs.glucose), field('Lipids', d.labs.lipids), field('TSH', d.labs.tsh), field('Liver/Kidney Function', d.labs.organFunc), field('Other', d.labs.other)])}
  </div>
</div>
<div class="cols">
  <section><h3>Doctor's Assessment</h3>
    ${block('Main Concern', d.doctorAssessment.mainConcern)}
    ${block('Patient Goal', d.doctorAssessment.patientGoal)}
    ${block('Clinical Assessment', d.doctorAssessment.clinicalAssessment)}
  </section>
  <section><h3>Management Plan</h3>
    <div class="checks">
      ${check(plan.nutritionPlan, 'Nutrition Plan')}${check(plan.lifestyleMod, 'Lifestyle Modification')}${check(plan.pharmacotherapy, 'Pharmacotherapy')}${check(plan.nutritionPharm, 'Nutrition + Pharm')}${check(plan.investigations, 'Further Investigations')}${check(plan.followUp, 'Follow-up')}
    </div>
    ${block('Treatment Plan', plan.treatmentPlan)}
    ${block('Follow-up Period / Date', plan.followUpDays)}
  </section>
</div>
<div class="foot">
  <div class="note"><div>Hepta Hub Clinic Management Suite</div><div>Cairo, Egypt &bull; Contact: support@heptahub.com</div></div>
  <div class="sig"><div class="name">${esc(currentUser.name)}</div><div class="line">Physician Signature &amp; Stamp</div></div>
</div>
</body></html>`;

        const frame = document.createElement('iframe');
        frame.setAttribute('aria-hidden', 'true');
        frame.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;';
        document.body.appendChild(frame);
        const fdoc = frame.contentWindow.document;
        fdoc.open();
        fdoc.write(html);
        fdoc.close();
        setTimeout(() => {
            try { frame.contentWindow.focus(); frame.contentWindow.print(); } catch (e) { window.print(); }
            setTimeout(() => { try { frame.remove(); } catch (e) {} }, 60000);
        }, 600);
    };

    const handleAddPatientSubmit = async (e) => {
        e.preventDefault();
        const patientId = `pat-${Date.now()}`;
        const patientObj = {
            id: patientId,
            ...newPatient,
            doctorId: currentUser.isAdmin ? doctors[1]?.id || 'doc-2' : currentUser.id,
            lastVisit: new Date().toISOString().split('T')[0],
            history: [{ id: `hist-${Date.now()}`, date: new Date().toISOString().split('T')[0], doctor: currentUser.name, notes: 'Registered patient profile.', diagnosis: newPatient.diagnosis }],
            prescriptions: [],
            assessment: null
        };
        await db.collection("patients").doc(patientId).set(patientObj);
        logActivity(`${currentUser.name} admitted new patient: ${newPatient.name}`, 'patient');
        setNewPatient({ name: '', age: '', phone: '', gender: 'Male', diagnosis: '', triage: 'Routine', notes: '' });
        setShowAddPatient(false);
    };

    const handleEditPatientSubmit = async (e) => {
        e.preventDefault();
        if (!editingPatient) return;
        await db.collection("patients").doc(editingPatient.id).update({
            name: editingPatient.name,
            age: Number(editingPatient.age),
            phone: editingPatient.phone,
            gender: editingPatient.gender,
            diagnosis: editingPatient.diagnosis,
            triage: editingPatient.triage || 'Routine',
            notes: editingPatient.notes
        });
        setShowEditPatient(false);
        setEditingPatient(null);
        logActivity(`${currentUser.name} updated patient record: ${editingPatient.name}`, 'patient');
    };

    const handleAddInventorySubmit = async (e) => {
        e.preventDefault();
        const invId = `inv-${Date.now()}`;
        let targetDoctorId = newInventory.doctorId === 'personal' ? currentUser.id : 'all';

        const invObj = {
            id: invId,
            name: newInventory.name,
            category: newInventory.category,
            batch: newInventory.batch,
            stock: Number(newInventory.stock),
            minStock: Number(newInventory.minStock),
            expiryDate: newInventory.expiryDate,
            doctorId: targetDoctorId
        };

        await db.collection("inventory").doc(invId).set(invObj);
        logActivity(`${currentUser.name} added stock item: ${newInventory.name} (+${newInventory.stock} units)`, 'inventory');
        setNewInventory({ name: '', category: 'Antibiotics', stock: '', minStock: '', expiryDate: '', doctorId: 'personal', batch: '' });
        setShowAddInventory(false);
    };

    const handleEditInventorySubmit = async (e) => {
        e.preventDefault();
        if (!editingInventory) return;
        await db.collection("inventory").doc(editingInventory.id).update({
            name: editingInventory.name,
            category: editingInventory.category,
            batch: editingInventory.batch,
            stock: Number(editingInventory.stock),
            minStock: Number(editingInventory.minStock),
            expiryDate: editingInventory.expiryDate,
            doctorId: editingInventory.doctorId
        });
        setShowEditInventory(false);
        setEditingInventory(null);
        logActivity(`${currentUser.name} updated inventory item: ${editingInventory.name}`, 'inventory');
    };

    const handleAddDoctorSubmit = async (e) => {
        e.preventDefault();
        if (!currentUser?.isAdmin || originalAdminUser) return;
        const uname = newDoctor.username.trim().toLowerCase();
        const mail = newDoctor.email.trim().toLowerCase();
        if (staff.some(x => x.username.trim().toLowerCase() === uname || x.email.trim().toLowerCase() === mail)) {
            setStaffError(lang === 'ar' ? 'اسم المستخدم أو البريد مستخدم بالفعل.' : 'That username or email is already in use.');
            return;
        }
        const role = newDoctor.role === 'assistant' ? 'assistant' : 'doctor';
        let branchId, branchIds;
        if (role === 'assistant') {
            // exactly one branch
            branchId = ALL_BRANCH_IDS.includes(newDoctor.branchId) ? newDoctor.branchId : ALL_BRANCH_IDS[0];
            branchIds = [branchId];
        } else {
            // one or more branches
            branchIds = (newDoctor.branchIds || []).filter(id => ALL_BRANCH_IDS.includes(id));
            if (branchIds.length === 0) {
                setStaffError(lang === 'ar' ? 'اختر فرعاً واحداً على الأقل للطبيب.' : 'Select at least one branch for the doctor.');
                return;
            }
            branchId = branchIds.length === ALL_BRANCH_IDS.length ? 'all' : branchIds[0];
        }
        const docId = `${role === 'assistant' ? 'asst' : 'doc'}-${Date.now()}`;
        const docObj = {
            ...newDoctor,
            id: docId,
            role,
            branchId,
            branchIds,
            username: newDoctor.username.trim(),
            email: newDoctor.email.trim(),
            specialty: newDoctor.specialty.trim() || (role === 'assistant' ? 'Assistant' : 'Doctor'),
            isAdmin: false,
            status: 'Active'
        };
        await db.collection("doctors").doc(docId).set(docObj);
        logActivity(`${currentUser.name} created ${role} account: ${newDoctor.name}`, 'system');
        setNewDoctor({ role: 'doctor', branchId: ALL_BRANCH_IDS[0], branchIds: [ALL_BRANCH_IDS[0]], name: '', specialty: '', email: '', username: '', password: '', avatar: newDoctor.avatar });
        setStaffError('');
        setShowAddDoctor(false);
    };

    const handleToggleDoctorBranch = async (d, branchId) => {
        if (!currentUser?.isAdmin || originalAdminUser || d.role !== 'doctor') return;
        const has = d.branchIds.includes(branchId);
        const next = has ? d.branchIds.filter(x => x !== branchId) : [...d.branchIds, branchId];
        if (next.length === 0) return; // a doctor must keep at least one branch
        await db.collection("doctors").doc(d.id).update({ branchIds: next, branchId: next.length === ALL_BRANCH_IDS.length ? 'all' : next[0] });
        logActivity(`${currentUser.name} changed branches of ${d.name}`, 'system');
    };

    const handleChangeBranch = async (id, branchId) => {
        if (!currentUser?.isAdmin || originalAdminUser) return;
        const target = staff.find(x => x.id === id);
        if (!target || target.role !== 'assistant') return; // single-branch change is for assistants only
        await db.collection("doctors").doc(id).update({ branchId, branchIds: [branchId] });
        logActivity(`${currentUser.name} changed branch of an account`, 'system');
    };

    const handleToggleStatus = async (d) => {
        if (!currentUser?.isAdmin || originalAdminUser || d.isAdmin) return;
        await db.collection("doctors").doc(d.id).update({ status: d.status === 'Active' ? 'Disabled' : 'Active' });
    };

    // ===== UPDATED WITH OPTIMISTIC UI FILTERING TO PREVENT RE-APPEARANCE GLITCH =====
  const handleDeleteItem = async (collectionName, id) => {
    if (confirm(lang === 'ar' ? 'هل أنت متأكد من الحذف؟' : 'Are you sure you want to delete this item?')) {
try {
    console.log("Attempting to delete ID:", id, "from collection:", collectionName);
    
    // 1. Delete from Firestore first
    await db.collection(collectionName).doc(id).delete();
    // Firestore reports success even if the doc id doesn't exist, so double-check on the server
    const stillThere = await db.collection(collectionName).doc(id).get({ source: 'server' });
    if (stillThere.exists) throw new Error("Document " + id + " still exists after delete (check Firestore rules / are they published?)");
    
    // 2. Update local state immediately upon success
    if (collectionName === 'patients') {
        setPatients(prev => prev.filter(p => p.id !== id));
        setShowPatientDetailModal(false);
        setShowEditPatient(false);
    } else if (collectionName === 'inventory') {
        setInventory(prev => prev.filter(i => i.id !== id));
        setShowEditInventory(false);
    } else if (collectionName === 'doctors') {
        setDoctors(prev => prev.filter(d => d.id !== id));
    } else if (collectionName === 'appointments') {
        setAppointments(prev => prev.filter(a => a.id !== id));
    }

    logActivity(`${currentUser.name} deleted an item from ${collectionName}`, 'system');
} catch (error) {
    console.error("Detailed Firebase delete error: ", error);
    alert("Firebase Error: " + error.message);
}
    }
};

    const handleAddPrescriptionSubmit = async (e) => {
        e.preventDefault();
        if (!selectedPatient) return;

        const medicationName = rxForm.selectedItem === 'others' ? rxForm.customMedication : rxForm.selectedItem;
        if (!medicationName) return;

        const newRx = {
            id: `rx-${Date.now()}`,
            date: new Date().toISOString().split('T')[0],
            medication: medicationName,
            dosage: rxForm.dosage,
            instructions: rxForm.instructions,
            doctor: currentUser.name
        };

        const matchedInvItem = inventory.find(i => i.name === rxForm.selectedItem);
        if (matchedInvItem) {
            const newStockLevel = Math.max(0, Number(matchedInvItem.stock) - 1);
            await db.collection("inventory").doc(matchedInvItem.id).update({ stock: newStockLevel });
        }

        const updatedPrescriptions = [newRx, ...(selectedPatient.prescriptions || [])];
        const updatedHistory = [{ id: `hist-${Date.now()}`, date: new Date().toISOString().split('T')[0], doctor: currentUser.name, notes: `Prescribed: ${medicationName}`, diagnosis: selectedPatient.diagnosis }, ...(selectedPatient.history || [])];

        await db.collection("patients").doc(selectedPatient.id).update({
            prescriptions: updatedPrescriptions,
            history: updatedHistory
        });

        setSelectedPatient({ ...selectedPatient, prescriptions: updatedPrescriptions, history: updatedHistory });
        setRxForm({ selectedItem: '', customMedication: '', dosage: '', instructions: '' });
        setShowPrescriptionModal(false);
        logActivity(`${currentUser.name} issued prescription for ${selectedPatient.name}`, 'rx');
    };

    const handleEditRxSubmit = async (e) => {
        e.preventDefault();
        if (!selectedPatient || !editingRx) return;
        const updatedPrescriptions = (selectedPatient.prescriptions || []).map(rx => rx.id === editingRx.id ? { ...editingRx } : rx);
        await db.collection("patients").doc(selectedPatient.id).update({ prescriptions: updatedPrescriptions });
        setSelectedPatient({ ...selectedPatient, prescriptions: updatedPrescriptions });
        setShowEditRxModal(false);
        setEditingRx(null);
    };

    const handleDeleteRx = async (rxId) => {
        if (!selectedPatient) return;
        if (confirm(lang === 'ar' ? 'حذف هذه الروشتة؟' : 'Delete prescription?')) {
            try {
                const ref = db.collection("patients").doc(selectedPatient.id);
                const snap = await ref.get({ source: 'server' });
                if (!snap.exists) throw new Error("Patient record not found in database");
                const updatedPrescriptions = (snap.data().prescriptions || []).filter(rx => rx.id !== rxId);
                await ref.update({ prescriptions: updatedPrescriptions });
                setSelectedPatient(prev => ({ ...prev, prescriptions: updatedPrescriptions }));
                setPatients(prev => prev.map(p => p.id === selectedPatient.id ? { ...p, prescriptions: updatedPrescriptions } : p));
            } catch (error) {
                console.error("Delete prescription error:", error);
                alert("Firebase Error: " + error.message);
            }
        }
    };

    const handleEditVisitSubmit = async (e) => {
        e.preventDefault();
        if (!selectedPatient || !editingVisit) return;
        const updatedHistory = (selectedPatient.history || []).map(h => h.id === editingVisit.id ? { ...editingVisit } : h);
        await db.collection("patients").doc(selectedPatient.id).update({ history: updatedHistory });
        setSelectedPatient({ ...selectedPatient, history: updatedHistory });
        setShowEditVisitModal(false);
        setEditingVisit(null);
    };

    const handleDeleteVisit = async (visitId) => {
        if (!selectedPatient) return;
        if (confirm(lang === 'ar' ? 'حذف سجل الزيارة؟' : 'Delete visit item?')) {
            try {
                const ref = db.collection("patients").doc(selectedPatient.id);
                const snap = await ref.get({ source: 'server' });
                if (!snap.exists) throw new Error("Patient record not found in database");
                const updatedHistory = (snap.data().history || []).filter(h => h.id !== visitId);
                await ref.update({ history: updatedHistory });
                setSelectedPatient(prev => ({ ...prev, history: updatedHistory }));
                setPatients(prev => prev.map(p => p.id === selectedPatient.id ? { ...p, history: updatedHistory } : p));
            } catch (error) {
                console.error("Delete visit error:", error);
                alert("Firebase Error: " + error.message);
            }
        }
    };

    const getExpiryStatus = (expiryDateStr) => {
        const today = new Date('2026-10-28');
        const expDate = new Date(expiryDateStr);
        const diffTime = expDate - today;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        if (diffDays < 0) return { label: lang === 'ar' ? 'منتهي الصلاحية' : 'Expired', color: 'bg-rose-100 text-rose-800 border-rose-300' };
        if (diffDays <= 70) return { label: lang === 'ar' ? `ينتهي خلال (${diffDays} يوم)` : `Expiring (${diffDays}d)`, color: 'bg-amber-100 text-amber-800 border-amber-300' };
        return { label: lang === 'ar' ? 'سليم' : 'Healthy', color: 'bg-emerald-100 text-emerald-800 border-emerald-300' };
    };

    const filteredPatients = useMemo(() => {
        let list = currentUser?.isAdmin && !originalAdminUser ? patients : patients.filter(p => p.doctorId === currentUser?.id);
        if (!patientSearch.trim()) return list;
        const q = patientSearch.toLowerCase();
        return list.filter(p => p.name.toLowerCase().includes(q) || p.phone.includes(q) || p.diagnosis.toLowerCase().includes(q));
    }, [patients, currentUser, originalAdminUser, patientSearch]);

    const filteredInventory = useMemo(() => {
        let list = [];
        if (currentUser?.isAdmin && !originalAdminUser) {
            list = inventory;
        } else {
            list = inventory.filter(i => i.doctorId === 'all' || i.doctorId === currentUser?.id);
        }

        if (!inventorySearch.trim()) return list;
        const q = inventorySearch.toLowerCase();
        return list.filter(i => i.name.toLowerCase().includes(q) || i.category.toLowerCase().includes(q) || i.batch.toLowerCase().includes(q));
    }, [inventory, currentUser, originalAdminUser, inventorySearch]);

    const allCategories = useMemo(() => {
        const seen = new Set();
        const out = [];
        [...DEFAULT_CATEGORIES, ...customCategories, ...inventory.map(i => i.category)].forEach(c => {
            const name = (c || '').trim();
            if (name && !seen.has(name.toLowerCase())) { seen.add(name.toLowerCase()); out.push(name); }
        });
        return out;
    }, [customCategories, inventory]);

    const handleAddCategory = async (applyTo) => {
        const name = newCategoryName.trim();
        if (!name) return;
        const existing = allCategories.find(c => c.toLowerCase() === name.toLowerCase());
        const finalName = existing || name;
        applyTo(finalName);
        setNewCategoryName('');
        setAddingCategory(false);
        if (!existing) {
            const updated = [...customCategories, finalName];
            setCustomCategories(updated);
            try { localStorage.setItem('heptaCategories', JSON.stringify(updated)); } catch (e) {}
            try { await db.collection("settings").doc("inventoryCategories").set({ list: updated }); } catch (err) {}
            logActivity(`${currentUser.name} added inventory category: ${finalName}`, 'inventory');
        }
    };

    const renderCategoryField = (value, onChange) => {
        const options = (!value || allCategories.includes(value)) ? allCategories : [value, ...allCategories];
        const fieldCls = "w-full px-4 py-3 rounded-2xl bg-brand-linen/50 border border-brand-dune text-brand-harbor text-sm font-medium focus:outline-none focus:ring-2 focus:ring-brand-sky focus:bg-white";
        return (
            <div>
                <label className="block text-xs font-bold uppercase text-brand-steel mb-1.5">{strings.category}</label>
                {addingCategory ? (
                    <div className="flex items-center gap-2">
                        <input
                            autoFocus
                            type="text"
                            value={newCategoryName}
                            onChange={e => setNewCategoryName(e.target.value)}
                            onKeyDown={e => {
                                if (e.key === 'Enter') { e.preventDefault(); handleAddCategory(onChange); }
                                if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setAddingCategory(false); setNewCategoryName(''); }
                            }}
                            placeholder={lang === 'ar' ? 'اسم الفئة الجديدة' : 'New category name'}
                            className={fieldCls + " min-w-0 flex-1"}
                        />
                        <button type="button" onClick={() => handleAddCategory(onChange)} className="h-11 px-4 shrink-0 rounded-2xl bg-brand-harbor hover:bg-brand-sky text-white text-xs font-bold">{lang === 'ar' ? 'إضافة' : 'Add'}</button>
                        <button type="button" onClick={() => { setAddingCategory(false); setNewCategoryName(''); }} aria-label={strings.cancel} className="h-11 w-11 shrink-0 rounded-2xl bg-brand-linen hover:bg-brand-dune/40 text-brand-steel">✕</button>
                    </div>
                ) : (
                    <div className="flex items-center gap-2">
                        <select value={value} onChange={e => onChange(e.target.value)} className={fieldCls + " min-w-0 flex-1"}>
                            {options.map(c => <option key={c} value={c}>{c}</option>)}
                        </select>
                        <button type="button" title={lang === 'ar' ? 'إضافة فئة جديدة' : 'Add new category'} aria-label={lang === 'ar' ? 'إضافة فئة جديدة' : 'Add new category'} onClick={() => setAddingCategory(true)} className="h-11 w-11 shrink-0 rounded-2xl bg-brand-linen border border-brand-dune text-brand-harbor text-lg font-extrabold hover:bg-brand-dune/40">+</button>
                    </div>
                )}
            </div>
        );
    };

    const filteredDoctors = useMemo(() => {
        let list = staffBranchFilter === 'all' ? staff : staff.filter(d => d.branchIds.includes(staffBranchFilter));
        if (!doctorSearch.trim()) return list;
        const q = doctorSearch.toLowerCase();
        return list.filter(d => d.name.toLowerCase().includes(q) || d.specialty.toLowerCase().includes(q) || d.email.toLowerCase().includes(q));
    }, [staff, doctorSearch, staffBranchFilter]);

    const branchName = (id) => id === 'all' ? (lang === 'ar' ? 'كل الفروع' : 'All branches') : ((BRANCHES.find(b => b.id === id) || {}).name || id || '-');
    const roleLabel = (r) => (ROLE_LABELS[r] || ROLE_LABELS.doctor)[lang];
    const aptBranchId = (a) => {
        if (a.branchId) return a.branchId;
        const d = staff.find(x => x.id === a.doctorId);
        return d && d.branchIds && d.branchIds.length === 1 ? d.branchIds[0] : null;
    };
    const branchLabel = (u) => !u ? '-' : (u.branchIds && u.branchIds.length === BRANCHES.length ? branchName('all') : (u.branchIds || [u.branchId]).map(branchName).join(', '));
    const timeToMinutes = (tm) => {
        const m = /^(\d{1,2}):(\d{2})\s*(AM|PM)?$/i.exec((tm || '').trim());
        if (!m) return 0;
        let h = parseInt(m[1], 10) % 12;
        if (m[3] && m[3].toUpperCase() === 'PM') h += 12;
        return h * 60 + parseInt(m[2], 10);
    };
    const isAssistantUser = currentUser?.role === 'assistant';
    const branchDoctors = useMemo(() => isAssistantUser
        ? doctors.filter(d => d.branchIds.includes(currentUser.branchId) && d.status === 'Active')
        : doctors, [doctors, currentUser, isAssistantUser]);
    const branchAppointments = useMemo(() => (isAssistantUser
        ? appointments.filter(a => aptBranchId(a) === currentUser.branchId)
        : appointments
    ).slice().sort((a, b) => (a.date || '').localeCompare(b.date || '') || timeToMinutes(a.time) - timeToMinutes(b.time)),
        [appointments, staff, currentUser, isAssistantUser]);
    const bookingDoctorId = branchDoctors.some(d => d.id === assistantBooking.doctorId) ? assistantBooking.doctorId : (branchDoctors[0]?.id || '');

    const filteredAppointments = useMemo(() => {
        let list = currentUser?.isAdmin && !originalAdminUser ? appointments : appointments.filter(a => a.doctorId === currentUser?.id);
        if (!appointmentSearch.trim()) return list;
        const q = appointmentSearch.toLowerCase();
        return list.filter(a => a.patientName.toLowerCase().includes(q));
    }, [appointments, currentUser, originalAdminUser, appointmentSearch]);

    // ===== Browser / phone Back button: step back through the app instead of leaving it =====
    const navRef = React.useRef({});
    navRef.current.cu = currentUser;
    navRef.current.ou = originalAdminUser;
    navRef.current.staff = staff;
    const anyModalOpen = !!(showAddPatient || showAddInventory || showAddDoctor || showPatientDetailModal || showPrescriptionModal || showProfileModal || showAssistantPicker || showEditPatient || showEditInventory || showEditRxModal || showEditVisitModal || showAssessmentModal || showPrintRxModal);

    useEffect(() => {
        const h = navRef.current;
        let base, nav;
        if (currentUser) {
            base = `${currentUser.id}|${originalAdminUser ? originalAdminUser.id : ''}|${activeTab}`;
            nav = { u: currentUser.id, o: originalAdminUser ? originalAdminUser.id : null, tab: activeTab, m: anyModalOpen };
        } else {
            base = 'out|' + (assistantLoginMode ? 'a' : 's');
            nav = { out: true, lm: assistantLoginMode };
        }
        const key = base + '|' + (anyModalOpen ? 1 : 0);
        if (h.key === key) return;
        const prevBase = h.base, prevKey = h.key;
        h.key = key; h.base = base;
        try {
            if (h.skipPush) { h.skipPush = false; h.modalPushed = false; window.history.replaceState({ nav }, ''); return; }
            if (prevKey === undefined) { window.history.replaceState({ nav }, ''); return; }
            const wasOut = prevBase.startsWith('out|'), isOut = base.startsWith('out|');
            if (wasOut !== isOut) { h.modalPushed = false; window.history.replaceState({ nav }, ''); return; } // login / logout never adds a Back step
            if (prevBase === base) {                       // only a popup opened or closed
                if (anyModalOpen) { window.history.pushState({ nav }, ''); h.modalPushed = true; }
                else if (h.modalPushed) { h.modalPushed = false; window.history.back(); }
                return;
            }
            h.modalPushed = false;
            window.history.pushState({ nav }, '');         // new tab / new portal = new Back step
        } catch (err) { /* history API unavailable: ignore */ }
    }, [currentUser, originalAdminUser, activeTab, assistantLoginMode, showAddPatient, showAddInventory, showAddDoctor, showPatientDetailModal, showPrescriptionModal, showProfileModal, showAssistantPicker, showEditPatient, showEditInventory, showEditRxModal, showEditVisitModal, showAssessmentModal, showPrintRxModal]);

    useEffect(() => {
        const onPop = (e) => {
            const h = navRef.current;
            const nav = e.state && e.state.nav;
            if (!nav) return;
            const cu = h.cu, ou = h.ou;
            if (!cu) {                                      // logged out: only step between the two login screens
                if (nav.out) setAssistantLoginMode(!!nav.lm);
                return;                                     // never log anyone back in through Back
            }
            if (nav.out) return;
            const list = h.staff || [];
            const target = list.find(x => x.id === nav.u);
            const orig = nav.o ? list.find(x => x.id === nav.o) : null;
            if (!target || (nav.o && !orig)) return;
            if (target.status && target.status !== 'Active') return;
            if ((ou || cu).id !== (orig || target).id) return;   // never jump into another person's session
            const restoredKey = `${target.id}|${orig ? orig.id : ''}|${nav.tab}|0`;
            if (h.key !== restoredKey) h.skipPush = true;
            h.modalPushed = false;
            setShowAddPatient(false); setShowAddInventory(false); setShowAddDoctor(false); setShowPatientDetailModal(false); setShowPrescriptionModal(false); setShowProfileModal(false); setShowAssistantPicker(false); setShowEditPatient(false); setShowEditInventory(false); setShowEditRxModal(false); setShowEditVisitModal(false); setShowAssessmentModal(false); setShowPrintRxModal(false);
            if (target.id !== cu.id) { setCurrentUser(target); setProfileAvatarUrl(target.avatar); }
            setOriginalAdminUser(orig);
            setActiveTab(nav.tab);
        };
        window.addEventListener('popstate', onPop);
        return () => window.removeEventListener('popstate', onPop);
    }, []);

    const assistantChoices = useMemo(() => {
        if (!currentUser || currentUser.role === 'assistant') return [];
        const viewerIsAdmin = !!((originalAdminUser || currentUser).isAdmin);
        return staff.filter(a => a.role === 'assistant' && a.status === 'Active' && (viewerIsAdmin || (currentUser.branchIds || []).includes(a.branchId)));
    }, [staff, currentUser, originalAdminUser]);

    if (currentUser && currentUser.role === 'assistant') {
        return (
            <AssistantPortal
                appointments={appointments}
                assistantBooking={assistantBooking}
                avatarNotice={avatarNotice}
                bookingDoctorId={bookingDoctorId}
                bookingNotice={bookingNotice}
                branchAppointments={branchAppointments}
                branchDoctors={branchDoctors}
                branchName={branchName}
                clinicLogo={clinicLogo}
                currentUser={currentUser}
                handleAssistantAvatarUpload={handleAssistantAvatarUpload}
                handleAssistantBookSubmit={handleAssistantBookSubmit}
                handleLogout={handleLogout}
                handleReturnToAdmin={handleReturnToAdmin}
                handleUpdateAppointmentStatus={handleUpdateAppointmentStatus}
                lang={lang}
                originalAdminUser={originalAdminUser}
                setAssistantBooking={setAssistantBooking}
                setLang={setLang}
                strings={strings}
            />
        );
    }

    if (!currentUser) {
        return (
            <LoginScreen
                assistantLoginMode={assistantLoginMode}
                clinicLogo={clinicLogo}
                doctorsLoaded={doctorsLoaded}
                handleLogin={handleLogin}
                inventory={inventory}
                lang={lang}
                loginError={loginError}
                loginPassword={loginPassword}
                loginUsername={loginUsername}
                setAssistantLoginMode={setAssistantLoginMode}
                setLang={setLang}
                setLoginError={setLoginError}
                setLoginPassword={setLoginPassword}
                setLoginUsername={setLoginUsername}
                strings={strings}
            />
        );
    }

    return (
        <div className="min-h-screen bg-brand-linen text-brand-harbor flex flex-col" dir={lang === 'ar' ? 'rtl' : 'ltr'}>
            {originalAdminUser && (
                <div className="bg-amber-400 text-brand-harbor px-4 sm:px-6 py-2.5 text-xs font-extrabold flex flex-wrap justify-between items-center gap-2 shadow-md z-50">
                    <span>{strings.impersonatingBanner} <strong>{currentUser.name}</strong></span>
                    <button onClick={handleReturnToAdmin} className="bg-brand-harbor text-white px-4 py-1.5 rounded-xl shadow hover:bg-brand-sky transition-colors">
                        {strings.returnToHesham}
                    </button>
                </div>
            )}

            <header className="bg-brand-harbor text-white sticky top-0 z-40 !shadow-[0_10px_30px_-14px_rgba(20,32,48,.7)]">
                <div className="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 h-16 sm:h-20 gap-2 flex items-center justify-between">
                    <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 sm:w-12 sm:h-12 rounded-xl sm:rounded-2xl overflow-hidden shadow-md ring-2 ring-white/30 shrink-0">
                            <img src={clinicLogo} alt="Hepta Hub Logo" className="w-full h-full object-contain bg-white" />
                        </div>
                        <div className="hidden min-[460px]:block min-w-0">
                            <h1 className="text-lg sm:text-xl font-extrabold tracking-tight text-white truncate">{strings.appName}</h1>
                            <p className="hidden md:block text-xs text-white/80 font-bold truncate">{strings.appSubtitle}</p>
                        </div>
                    </div>

                    <div className="flex items-center gap-2 sm:gap-3 shrink-0">
                        <button 
                            onClick={() => setShowAssistantPicker(true)}
                            title={strings.assistantPortal} aria-label={strings.assistantPortal}
                            className="px-3 sm:px-3.5 py-2 bg-white/10 hover:bg-white/20 text-white rounded-xl text-xs font-bold transition-colors border border-white/15 flex items-center justify-center gap-1.5"
                        >
                            <i data-lucide="user-check" className="w-3.5 h-3.5 text-white/80"></i>
                            <span className="hidden md:inline">{strings.assistantPortal}</span>
                        </button>

                        <button 
                            onClick={() => setLang(lang === 'en' ? 'ar' : 'en')}
                            className="px-3 sm:px-3.5 py-2 bg-white/10 hover:bg-white/20 text-white rounded-xl text-xs font-bold transition-colors border border-white/15"
                        >
                            {strings.language}
                        </button>

                        <div 
                            onClick={() => { setProfileAvatarUrl(currentUser.avatar); setShowProfileModal(true); }}
                            className="flex items-center gap-3 bg-white/10 p-1 sm:px-4 sm:py-2 rounded-xl sm:rounded-2xl border border-white/15 cursor-pointer hover:bg-white/20 transition-all shadow-sm"
                        >
                            <img src={currentUser.avatar} alt={currentUser.name} className="w-9 h-9 sm:w-10 sm:h-10 rounded-lg sm:rounded-xl object-cover border-2 border-brand-sky shadow-sm" />
                            <div className="hidden sm:block text-left rtl:text-right">
                                <p className="text-sm font-bold text-white">{currentUser.name}</p>
                                <p className="text-[11px] text-white/80 font-semibold">{currentUser.specialty}{currentUser.role !== 'admin' ? ` • ${branchLabel(currentUser)}` : ''}</p>
                            </div>
                        </div>

                        <button 
                            onClick={handleLogout}
                            title={strings.logout} aria-label={strings.logout}
                            className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2.5 bg-white/10 hover:bg-rose-500 text-white border border-white/15 rounded-xl text-sm font-bold transition-colors"
                        >
                            <i data-lucide="log-out" className="w-4 h-4"></i>
                            <span className="hidden md:inline">{strings.logout}</span>
                        </button>
                    </div>
                </div>

            </header>
                <div className="app-nav bg-black/15 border-t border-white/10">
                    <div className="app-nav-inner max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex space-x-2 rtl:space-x-reverse overflow-x-auto">
                        <button 
                            onClick={() => setActiveTab('dashboard')}
                            className={`flex items-center space-x-2 rtl:space-x-reverse px-5 py-3.5 text-sm font-bold border-b-2 transition-all whitespace-nowrap ${activeTab === 'dashboard' ? 'border-brand-sky text-white bg-white/10' : 'border-transparent text-white/80 hover:text-white hover:bg-white/5'}`}
                        >
                            <i data-lucide="layout-dashboard" className="w-4 h-4"></i>
                            <span><span className="lg:hidden">{lang === 'ar' ? 'الرئيسية' : 'Home'}</span><span className="hidden lg:inline">{strings.dashboard}</span></span>
                        </button>
                        <button 
                            onClick={() => setActiveTab('inventory')}
                            className={`flex items-center space-x-2 rtl:space-x-reverse px-5 py-3.5 text-sm font-bold border-b-2 transition-all whitespace-nowrap ${activeTab === 'inventory' ? 'border-brand-sky text-white bg-white/10' : 'border-transparent text-white/80 hover:text-white hover:bg-white/5'}`}
                        >
                            <i data-lucide="package" className="w-4 h-4"></i>
                            <span><span className="lg:hidden">{lang === 'ar' ? 'المخزون' : 'Stock'}</span><span className="hidden lg:inline">{strings.inventory}</span></span>
                        </button>
                        <button 
                            onClick={() => setActiveTab('patients')}
                            className={`flex items-center space-x-2 rtl:space-x-reverse px-5 py-3.5 text-sm font-bold border-b-2 transition-all whitespace-nowrap ${activeTab === 'patients' ? 'border-brand-sky text-white bg-white/10' : 'border-transparent text-white/80 hover:text-white hover:bg-white/5'}`}
                        >
                            <i data-lucide="users" className="w-4 h-4"></i>
                            <span><span className="lg:hidden">{lang === 'ar' ? 'المرضى' : 'Patients'}</span><span className="hidden lg:inline">{strings.patients}</span></span>
                        </button>
                        <button 
                            onClick={() => setActiveTab('appointments')}
                            className={`flex items-center space-x-2 rtl:space-x-reverse px-5 py-3.5 text-sm font-bold border-b-2 transition-all whitespace-nowrap ${activeTab === 'appointments' ? 'border-brand-sky text-white bg-white/10' : 'border-transparent text-white/80 hover:text-white hover:bg-white/5'}`}
                        >
                            <i data-lucide="calendar" className="w-4 h-4"></i>
                            <span><span className="lg:hidden">{lang === 'ar' ? 'المواعيد' : 'Visits'}</span><span className="hidden lg:inline">{strings.appointments}</span></span>
                        </button>
                        {currentUser.isAdmin && !originalAdminUser && (
                            <button 
                                onClick={() => setActiveTab('doctors')}
                                className={`flex items-center space-x-2 rtl:space-x-reverse px-5 py-3.5 text-sm font-bold border-b-2 transition-all whitespace-nowrap ${activeTab === 'doctors' ? 'border-brand-sky text-white bg-white/10' : 'border-transparent text-white/80 hover:text-white hover:bg-white/5'}`}
                            >
                                <i data-lucide="stethoscope" className="w-4 h-4"></i>
                                <span><span className="lg:hidden">{lang === 'ar' ? 'الأطباء' : 'Doctors'}</span><span className="hidden lg:inline">{strings.doctors}</span></span>
                            </button>
                        )}
                    </div>
                </div>

            <main className="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
                
                {activeTab === 'dashboard' && (
                    <DashboardTab
                        activityLogs={activityLogs}
                        currentUser={currentUser}
                        filteredInventory={filteredInventory}
                        filteredPatients={filteredPatients}
                        getExpiryStatus={getExpiryStatus}
                        inventory={inventory}
                        lang={lang}
                        setShowAddInventory={setShowAddInventory}
                        setShowAddPatient={setShowAddPatient}
                        strings={strings}
                    />
                )}

                {activeTab === 'inventory' && (
                    <InventoryTab
                        doctors={doctors}
                        filteredInventory={filteredInventory}
                        handleDeleteItem={handleDeleteItem}
                        inventory={inventory}
                        inventorySearch={inventorySearch}
                        lang={lang}
                        setEditingInventory={setEditingInventory}
                        setInventorySearch={setInventorySearch}
                        setShowAddInventory={setShowAddInventory}
                        setShowEditInventory={setShowEditInventory}
                        strings={strings}
                    />
                )}

                {activeTab === 'patients' && (
                    <PatientsTab
                        filteredPatients={filteredPatients}
                        handleDeleteItem={handleDeleteItem}
                        handleOpenAssessment={handleOpenAssessment}
                        lang={lang}
                        patientSearch={patientSearch}
                        patients={patients}
                        setEditingPatient={setEditingPatient}
                        setPatientSearch={setPatientSearch}
                        setSelectedPatient={setSelectedPatient}
                        setShowAddPatient={setShowAddPatient}
                        setShowEditPatient={setShowEditPatient}
                        setShowPatientDetailModal={setShowPatientDetailModal}
                        strings={strings}
                    />
                )}

                {activeTab === 'appointments' && (
                    <AppointmentsTab
                        appointmentSearch={appointmentSearch}
                        appointments={appointments}
                        filteredAppointments={filteredAppointments}
                        handleDeleteItem={handleDeleteItem}
                        handleUpdateAppointmentStatus={handleUpdateAppointmentStatus}
                        lang={lang}
                        setAppointmentSearch={setAppointmentSearch}
                        strings={strings}
                    />
                )}

                {activeTab === 'doctors' && currentUser.isAdmin && !originalAdminUser && (
                    <StaffTab
                        branchDraft={branchDraft}
                        branchName={branchName}
                        branchNotice={branchNotice}
                        doctors={doctors}
                        filteredDoctors={filteredDoctors}
                        handleChangeBranch={handleChangeBranch}
                        handleDeleteItem={handleDeleteItem}
                        handleImpersonateDoctor={handleImpersonateDoctor}
                        handleToggleDoctorBranch={handleToggleDoctorBranch}
                        handleToggleStatus={handleToggleStatus}
                        lang={lang}
                        roleLabel={roleLabel}
                        saveBranchNames={saveBranchNames}
                        setBranchDraft={setBranchDraft}
                        setShowAddDoctor={setShowAddDoctor}
                        setStaffBranchFilter={setStaffBranchFilter}
                        staffBranchFilter={staffBranchFilter}
                        strings={strings}
                    />
                )}

            </main>

                                {/* Assistant Portal Picker */}
            {showAssistantPicker && currentUser.role !== 'assistant' && (
                <AssistantPickerModal
                    assistantChoices={assistantChoices}
                    currentUser={currentUser}
                    lang={lang}
                    openAssistantPortal={openAssistantPortal}
                    originalAdminUser={originalAdminUser}
                    setShowAssistantPicker={setShowAssistantPicker}
                    staff={staff}
                />
            )}

            {/* Add Staff Account Modal */}
            {showAddDoctor && currentUser.isAdmin && !originalAdminUser && (
                <AddStaffModal
                    appointments={appointments}
                    handleAddDoctorSubmit={handleAddDoctorSubmit}
                    inventory={inventory}
                    lang={lang}
                    newDoctor={newDoctor}
                    patients={patients}
                    setNewDoctor={setNewDoctor}
                    setShowAddDoctor={setShowAddDoctor}
                    setStaffError={setStaffError}
                    staffError={staffError}
                />
            )}

            {/* Print Prescription Modal */}
            {showPrintRxModal && activePrescriptionToPrint && selectedPatient && (
                <PrintPrescriptionModal
                    activePrescriptionToPrint={activePrescriptionToPrint}
                    clinicLogo={clinicLogo}
                    currentUser={currentUser}
                    lang={lang}
                    selectedPatient={selectedPatient}
                    setShowPrintRxModal={setShowPrintRxModal}
                    strings={strings}
                />
            )}

            {showAssessmentModal && selectedPatient && (
                <AssessmentModal
                    assessmentData={assessmentData}
                    handlePrintAssessment={handlePrintAssessment}
                    handleSaveAndPrintAssessment={handleSaveAndPrintAssessment}
                    handleSaveAssessment={handleSaveAssessment}
                    lang={lang}
                    selectedPatient={selectedPatient}
                    setAssessmentData={setAssessmentData}
                    setShowAssessmentModal={setShowAssessmentModal}
                    strings={strings}
                />
            )}

            {showEditPatient && editingPatient && (
                <EditPatientModal
                    editingPatient={editingPatient}
                    handleEditPatientSubmit={handleEditPatientSubmit}
                    lang={lang}
                    setEditingPatient={setEditingPatient}
                    setShowEditPatient={setShowEditPatient}
                    strings={strings}
                />
            )}

            {showPatientDetailModal && selectedPatient && (
                <PatientDetailModal
                    handleDeleteRx={handleDeleteRx}
                    handleDeleteVisit={handleDeleteVisit}
                    lang={lang}
                    selectedPatient={selectedPatient}
                    setActivePrescriptionToPrint={setActivePrescriptionToPrint}
                    setEditingRx={setEditingRx}
                    setEditingVisit={setEditingVisit}
                    setShowEditRxModal={setShowEditRxModal}
                    setShowEditVisitModal={setShowEditVisitModal}
                    setShowPatientDetailModal={setShowPatientDetailModal}
                    setShowPrescriptionModal={setShowPrescriptionModal}
                    setShowPrintRxModal={setShowPrintRxModal}
                    strings={strings}
                />
            )}

            {showEditRxModal && editingRx && (
                <EditPrescriptionModal
                    editingRx={editingRx}
                    handleEditRxSubmit={handleEditRxSubmit}
                    lang={lang}
                    setEditingRx={setEditingRx}
                    setShowEditRxModal={setShowEditRxModal}
                />
            )}
            {showEditVisitModal && editingVisit && (
                <EditVisitModal
                    editingVisit={editingVisit}
                    handleEditVisitSubmit={handleEditVisitSubmit}
                    lang={lang}
                    setEditingVisit={setEditingVisit}
                    setShowEditVisitModal={setShowEditVisitModal}
                />
            )}

            {showProfileModal && (
                <ProfileModal
                    currentUser={currentUser}
                    handleImageUpload={handleImageUpload}
                    handleUpdateAvatar={handleUpdateAvatar}
                    profileAvatarUrl={profileAvatarUrl}
                    setProfileAvatarUrl={setProfileAvatarUrl}
                    setShowProfileModal={setShowProfileModal}
                    strings={strings}
                />
            )}

            {showAddPatient && (
                <AddPatientModal
                    handleAddPatientSubmit={handleAddPatientSubmit}
                    lang={lang}
                    newPatient={newPatient}
                    setNewPatient={setNewPatient}
                    setShowAddPatient={setShowAddPatient}
                    strings={strings}
                />
            )}

            {showEditInventory && editingInventory && (
                <EditInventoryModal
                    currentUser={currentUser}
                    doctors={doctors}
                    editingInventory={editingInventory}
                    handleEditInventorySubmit={handleEditInventorySubmit}
                    lang={lang}
                    renderCategoryField={renderCategoryField}
                    setEditingInventory={setEditingInventory}
                    setShowEditInventory={setShowEditInventory}
                    strings={strings}
                />
            )}

            {showAddInventory && (
                <AddInventoryModal
                    currentUser={currentUser}
                    handleAddInventorySubmit={handleAddInventorySubmit}
                    lang={lang}
                    newInventory={newInventory}
                    renderCategoryField={renderCategoryField}
                    setNewInventory={setNewInventory}
                    setShowAddInventory={setShowAddInventory}
                    strings={strings}
                />
            )}

            {/* Prescription Writing Modal */}
            {showPrescriptionModal && selectedPatient && (
                <WritePrescriptionModal
                    handleAddPrescriptionSubmit={handleAddPrescriptionSubmit}
                    inventory={inventory}
                    rxForm={rxForm}
                    setRxForm={setRxForm}
                    setShowPrescriptionModal={setShowPrescriptionModal}
                    strings={strings}
                />
            )}

        </div>
    );
}
