const { useState, useEffect, useCallback, useMemo, useRef } = React;

// ============================================================
// SURGTRACK — Surgical Patient Management System
// Module 1: Role-Based Access + Categorized Scheduling
// ============================================================


// ─── Logo ────────────────────────────────────────────────────
const LOGO_SM = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAYlElEQVR42tV5Z3Rd1bXuN9dae5+qo6NebEmW5d5xBWJbxqYYm9AlGwgluQQTEpIXuEkICZGV+3iQQsoLJYQXLiHAxTrU4NCLhW2a425Ltlwky+pdp+621ro/ZAjc8C7cO3g/3hrjjH3GGeOsPb+55przm9/k+JyrToOtAGjLFgAAW7EC1LgChBUgbAHQBI6aOkJjo8b/k6UJqAcALF/zjem54yZvqKiadSfh/4NVV1fH6uvrVV1dg/mXtzdflZ+fe+GMqZXywJ7dmj7b83WsnurVt5+p+Q4L0hWua0gwg1vSB9cTyNjQpJnuGB4dHT6Z2th899Pvo66Oob5efRHG19TU8FgsJhevvnm8z+/dUlU+bnHFhLLyRDyR9dLmFx8Tn7XBRtTregChqPv1+dNyZnb2D8PVPsQtF6OWAKUZMg5DxvHQkx4xOWiVbKqnL9L4BefeMK2oKHzrvBmTzuCcTQbI7OroPNbb07dLfO7dhJHqHhySLd3dMmFzPpwgjKQYEhlCymFqyBLkZ778NOOQMU99UcbPO3fD3BnTyr+1duXpKxIpa1L/wBDAWKqtvX1Au6kPPjcAy9ZMkuAeDCjNuQaBMQEiBgGTK1cCaS2/SM+fVXPrgmhW+LLbb756pWXLiYePHLONkiJfV3dP//ET3S1nL591iH3eTW2X4CoG29WwHA3HA1wP2tKEsBk9YaaNYSuV4RoaAAjQVFdXx1BXxz58jv3+mTeWxWIxuWjV1VP6BgYvfPbhLT8pzI38MDvL3z1z+lTfpIpSd3/T4X7LkzueisXk5z4BRzLYroTlAq7H4EmCqyElN4RWYqs3ki5Vti6zl70uqPEsBZCurx9DU/8J9zZwAECsRgH0H1Muob5eL1391YLBkfiGxx68s6ioKFqdlxdt6O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y7eNNO2xpcWKSkrIsl/OYISjcGGC4qCBFfensJj/vNVdXldPw4VV2x7btTRP3GNXa29n5zhknHh188YtHrUwmXJ3LB3/2/mplbe0czJkzzzY0gP9fMOruj/8PKYx9l2fajg0AAAAASUVORK5CYII=";
// ─── Storage ─────────────────────────────────────────────────
const SK = { USERS: "st:users", PATIENTS: "st:patients", SESSION: "st:session", CONFIG: "st:config" };
async function load(k, fb) { try { const r = await window.storage.get(k); return r ? JSON.parse(r.value) : fb; } catch { return fb; } }
async function save(k, d) { try { await window.storage.set(k, JSON.stringify(d)); } catch (e) { console.error(e); } }

// ── Push Notification Helper ──────────────────────────────
async function notify(title, body, tag = 'surgtrack', url = '/', userIds = []) {
  try {
    await fetch('/api/index.php?route=push&action=send', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title, body, tag, url, userIds }),
    });
  } catch (e) { console.warn('Push notify failed:', e); }
}

// ── Resolve surgeon names from opDetails → user ids ──────
function getSurgeonUserIds(pt, users, config) {
  const od = pt.opDetails || {};
  const surgeons = config.surgeons || [];
  const getName = (val, other) => val === "__other" ? other : val;
  const teamNames = [
    getName(od.operatingSurgeon, od.surgeonOther),
    getName(od.firstAssistant,   od.assistantOther),
    getName(od.secondAssistant,  od.secondAssistantOther),
    getName(od.thirdAssistant,   od.thirdAssistantOther),
    getName(od.fourthAssistant,  od.fourthAssistantOther),
    getName(od.fifthAssistant,   od.fifthAssistantOther),
    od.anaesthetist,
  ].filter(Boolean).map(n => n.trim().toLowerCase());
  const matched = new Set();
  users.forEach(u => {
    if (u.linkStatus !== "approved" || !u.linkedSurgeon) return;
    const surg = surgeons.find(s => s.id === u.linkedSurgeon);
    if (surg && teamNames.includes(surg.name.trim().toLowerCase())) matched.add(u.id);
  });
  users.forEach(u => { if (teamNames.includes(u.name.trim().toLowerCase())) matched.add(u.id); });
  if (pt.createdBy) matched.add(pt.createdBy);
  if (od.operatedById) matched.add(od.operatedById);
  return [...matched];
}

// ── Notification Toggle Component ────────────────────────
function NotificationToggle({ show }) {
  const [status, setStatus] = useState(typeof Notification !== 'undefined' ? Notification.permission : 'unsupported');
  const [loading, setLoading] = useState(false);
  const urlB64 = (b) => { const p = '='.repeat((4 - b.length % 4) % 4); const d = atob((b + p).replace(/-/g, '+').replace(/_/g, '/')); return Uint8Array.from([...d].map(c => c.charCodeAt(0))); };
  const enable = async () => {
    if (!('PushManager' in window)) { show('Push not supported on this browser.', 'error'); return; }
    setLoading(true);
    try {
      const permission = await Notification.requestPermission();
      setStatus(permission);
      if (permission !== 'granted') { show('Permission denied. Enable from device settings.', 'error'); setLoading(false); return; }
      const reg = await navigator.serviceWorker.ready;
      const key = window._vapidPublicKey || '';
      if (!key) { show('VAPID key missing in index.html', 'error'); setLoading(false); return; }
      let sub = await reg.pushManager.getSubscription();
      if (!sub) sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlB64(key) });
      let userId = 'anonymous';
      try { const s = sessionStorage.getItem('st:session'); if (s) { const u = JSON.parse(s); userId = u.id || 'anonymous'; } } catch(e) {}
      const res = await fetch('/api/index.php?route=push&action=subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...sub.toJSON(), userId }) });
      const data = await res.json();
      if (data.ok) { show('🔔 Notifications enabled!'); setStatus('granted'); }
      else show('Failed: ' + JSON.stringify(data), 'error');
    } catch(e) { show('Error: ' + e.message, 'error'); }
    setLoading(false);
  };
  const disable = async () => {
    setLoading(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.getSubscription();
      if (sub) { await fetch('/api/index.php?route=push&action=unsubscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ endpoint: sub.endpoint }) }); await sub.unsubscribe(); }
      setStatus('default'); show('Notifications disabled on this device.');
    } catch(e) { show('Error: ' + e.message, 'error'); }
    setLoading(false);
  };
  if (status === 'unsupported') return <div style={{ fontSize: "0.75rem", color: "#92400e" }}>⚠️ Not supported. On iPhone, open SurgTrack from the Home Screen icon (installed PWA), not Safari directly.</div>;
  if (status === 'denied') return <div style={{ fontSize: "0.75rem", color: "#c62828" }}>🚫 Blocked — go to iPhone Settings → Safari → Notifications → surgtrack.in → Allow, then tap Enable again.</div>;
  if (status === 'granted') return <div style={{ display: "flex", alignItems: "center", gap: 10 }}><span style={{ fontSize: "0.8rem", color: "#2e7d32", fontWeight: 600 }}>✅ Enabled on this device</span><button onClick={disable} disabled={loading} style={{ padding: "6px 12px", borderRadius: 7, border: "1px solid #fca5a5", background: "#fef2f2", color: "#c62828", fontSize: "0.74rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{loading ? '...' : 'Disable'}</button></div>;
  return <button onClick={enable} disabled={loading} style={{ padding: "9px 18px", borderRadius: 8, border: "none", background: "#f59e0b", color: "#fff", fontWeight: 700, fontSize: "0.8rem", cursor: "pointer", fontFamily: "'Outfit',sans-serif", opacity: loading ? 0.6 : 1 }}>{loading ? '⏳ Enabling...' : '🔔 Enable Notifications on This Device'}</button>;
}

// ─── Default Config ──────────────────────────────────────────
const DEFAULT_PRIORITY_SLOTS = {
  "1": { label: "Urgent", color: "#c62828", slots: { gallbladder: 15, hernia: 7, obesity: 3, others: 20 } },
  "2": { label: "High", color: "#e65100", slots: { gallbladder: 10, hernia: 5, obesity: 2, others: 15 } },
  "3": { label: "Normal", color: "#2e7d32", slots: { gallbladder: 6, hernia: 3, obesity: 1, others: 10 } },
  "4": { label: "Routine", color: "#1565c0", slots: { gallbladder: 3, hernia: 2, obesity: 1, others: 8 } },
};
const DEFAULT_CONFIG = {
  admissionDay: 1,
  slots: { gallbladder: 6, hernia: 3, obesity: 1, others: 10 },
  theaters: ["GOT1", "GOT2"],
  prioritySlots: DEFAULT_PRIORITY_SLOTS,
  surgeons: [
    { id: "s1", name: "Prof. (Dr.) Iqbal Saleem Mir", designation: "Professor & HOD", canOperate: true },
    { id: "s2", name: "Dr. Abdul Hamid Samoon", designation: "Associate Professor", canOperate: true },
    { id: "s3", name: "Dr. Arshad Rashid", designation: "Assistant Professor", canOperate: true },
    { id: "s4", name: "Dr. Refut Arah", designation: "Lecturer", canOperate: true },
    { id: "s5", name: "Dr. Khurshid Ahmad Ganaie", designation: "Senior Resident", canOperate: true },
    { id: "s6", name: "Dr. Irshad Ahmad Kumar", designation: "Senior Resident", canOperate: false },
    { id: "s7", name: "Dr. Ashutosh Bawa", designation: "Senior Resident", canOperate: false },
    { id: "s8", name: "Dr. Awhad Mueed Yousuf", designation: "PG Resident", canOperate: false },
    { id: "s9", name: "Dr. Hashmat Rather", designation: "PG Resident", canOperate: false },
  ],
  notifPrefs: { operated: [], discharged: [], emergency: [] },
};
const DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

const DEFAULT_USERS = [
  { id: "u0", name: "Administrator", username: "admin", pin: "0000", role: "admin" },
  { id: "u1", name: "Dr. Resident 1", username: "resident1", pin: "1111", role: "resident" },
  { id: "u2", name: "Prof. Faculty 1", username: "faculty1", pin: "2222", role: "faculty" },
  { id: "u3", name: "Guest", username: "guest", pin: "3333", role: "guest" },
];

const PERMS = {
  admin:    { schedule: true, admit: true, edit: true, editAfterAdmit: true, operate: true, deletePatient: true, addFollowUp: true, addHpe: true, view: true, manageUsers: true, addEmergency: true },
  resident: { schedule: false, admit: false, edit: false, editAfterAdmit: true, operate: true, deletePatient: false, addFollowUp: true, addHpe: true, view: true, manageUsers: false, addEmergency: true },
  faculty:  { schedule: false, admit: false, edit: false, editAfterAdmit: false, operate: false, deletePatient: false, addFollowUp: true, addHpe: true, view: true, manageUsers: false, addEmergency: false },
  guest:    { schedule: false, admit: false, edit: false, editAfterAdmit: false, operate: false, deletePatient: false, addFollowUp: false, addHpe: false, view: true, manageUsers: false, addEmergency: false },
};
const ROLE_LABELS = { admin: "Admin", resident: "Resident", faculty: "Faculty", guest: "Guest" };
const ROLE_COLORS = { admin: { bg: "#fce4ec", color: "#c62828", b: "#ef9a9a" }, resident: { bg: "#e3f2fd", color: "#1565c0", b: "#90caf9" }, faculty: { bg: "#f3e5f5", color: "#7b1fa2", b: "#ce93d8" }, guest: { bg: "#f5f5f5", color: "#616161", b: "#bdbdbd" } };

// ═════════════════════════════════════════════════════════════
// CLINICAL DATA
// ═════════════════════════════════════════════════════════════

const BENIGN_CATEGORIES = {
  gallbladder: {
    label: "Gall Bladder", icon: "🟢", color: "#2e7d32",
    diagnoses: {
      "Cholelithiasis": ["Cholecystectomy"],
      "Acute Calculous Cholecystitis": ["Emergency Cholecystectomy", "Cholecystectomy", "Percutaneous Cholecystostomy"],
      "Chronic Calculous Cholecystitis": ["Cholecystectomy"],
      "Acalculous Cholecystitis": ["Cholecystectomy", "Percutaneous Cholecystostomy"],
      "Gall Bladder Polyp (<10mm)": ["Cholecystectomy"],
      "Gall Bladder Polyp (≥10mm)": ["Cholecystectomy (with Frozen Section)", "Cholecystectomy"],
      "Empyema Gall Bladder": ["Emergency Cholecystectomy", "Cholecystectomy", "Percutaneous Cholecystostomy"],
      "Mucocele Gall Bladder": ["Cholecystectomy"],
      "Porcelain Gall Bladder": ["Cholecystectomy"],
      "Biliary Dyskinesia": ["Cholecystectomy"],
      "Mirizzi Syndrome (Type I)": ["Cholecystectomy (Subtotal if needed)"],
      "Mirizzi Syndrome (Type II-IV)": ["Cholecystectomy + CBD Repair", "Cholecystectomy + Hepaticojejunostomy", "Cholecystectomy + T-Tube"],
    },
  },
  hernia: {
    label: "Hernia", icon: "🔵", color: "#1565c0",
    diagnoses: {
      "Inguinal Hernia": ["Lichtenstein Mesh Repair", "TEP Repair", "TAPP Repair", "Shouldice Repair", "Bilateral TEP Repair", "Bilateral TAPP Repair"],
      "Recurrent Inguinal Hernia": ["TEP/TAPP (if previous open)", "Mesh Repair (if previous lap)"],
      "Femoral Hernia": ["McEvedy's Approach", "TAPP Repair", "Lockwood's Low Approach"],
      "Umbilical Hernia": ["Mesh Repair (Mayo's)", "Mesh Repair"],
      "Paraumbilical Hernia": ["Mesh Repair"],
      "Epigastric Hernia": ["Mesh Repair", "Repair"],
      "Incisional Hernia": ["Sublay Mesh Repair", "Onlay Mesh Repair", "IPOM Repair", "eTEP Repair", "Anterior Component Separation", "Posterior Component Separation (TAR)"],
      "Spigelian Hernia": ["Mesh Repair", "Repair"],
      "Lumbar Hernia": ["Mesh Repair", "Repair"],
      "Obturator Hernia": ["Preperitoneal Repair", "Repair"],
      "Parastomal Hernia": ["Local Mesh Repair", "Stoma Resiting + Repair", "Sugarbaker Repair (Lap)"],
      "Richter's Hernia": ["Emergency Hernia Repair ± Bowel Resection"],
      "Strangulated Hernia": ["Emergency Hernioplasty ± Bowel Resection"],
      "Obstructed Hernia": ["Emergency Hernioplasty ± Bowel Resection"],
    },
  },
  obesity: {
    label: "Obesity", icon: "🟠", color: "#e65100",
    diagnoses: {
      "Morbid Obesity (BMI 35-40 with comorbidities)": ["Sleeve Gastrectomy", "Roux-en-Y Gastric Bypass", "One Anastomosis Gastric Bypass (OAGB)"],
      "Morbid Obesity (BMI 40-50)": ["Sleeve Gastrectomy", "Roux-en-Y Gastric Bypass", "OAGB"],
      "Super Obesity (BMI >50)": ["Sleeve Gastrectomy (Stage 1)", "SADI-S", "Roux-en-Y Gastric Bypass"],
      "Obesity with Type 2 DM (Metabolic Surgery)": ["Sleeve Gastrectomy", "Roux-en-Y Gastric Bypass", "OAGB"],
      "Failed Bariatric Surgery — Revision": ["Revision Sleeve to Bypass", "Band Removal + Sleeve/Bypass", "Sleeve to SADI-S"],
      "Obesity with GERD": ["Roux-en-Y Gastric Bypass", "OAGB"],
    },
  },
  others: {
    label: "Others", icon: "🟣", color: "#6a1b9a",
    diagnoses: {
      // ─── BILE DUCT / BILIARY ───
      "Cholelithiasis with Choledocholithiasis": ["Cholecystectomy + CBD Exploration", "ERCP followed by Cholecystectomy", "Cholecystectomy + CBD Exploration + T-Tube", "Cholecystectomy + Choledochoduodenostomy"],
      "Choledocholithiasis (CBD Stones)": ["ERCP + Sphincterotomy + Stone Extraction", "CBD Exploration + T-Tube", "CBD Exploration + Choledochoduodenostomy", "Laparoscopic CBD Exploration", "ERCP + Mechanical Lithotripsy"],
      "Recurrent CBD Stone (Post Cholecystectomy)": ["CBD Exploration", "ERCP + Sphincterotomy", "Choledochoduodenostomy", "Hepaticojejunostomy"],
      "Gallstone Ileus": ["Enterolithotomy", "Enterolithotomy + Cholecystectomy + Fistula Repair"],
      "Bouveret's Syndrome": ["Duodenotomy + Stone Extraction", "Endoscopic Extraction"],
      "Choledochal Cyst (Type I)": ["Cyst Excision + Roux-en-Y Hepaticojejunostomy"],
      "Choledochal Cyst (Type II)": ["Diverticulectomy + CBD Repair"],
      "Choledochal Cyst (Type III — Choledochocele)": ["Endoscopic Sphincterotomy", "Transduodenal Excision"],
      "Choledochal Cyst (Type IV-A)": ["Cyst Excision + Roux-en-Y HJ", "Hepatectomy + HJ (if intrahepatic)"],
      "Choledochal Cyst (Type V — Caroli's)": ["Hepatic Resection", "Liver Transplant"],
      "CBD Stricture (Benign — Post Cholecystectomy)": ["Roux-en-Y Hepaticojejunostomy", "Endoscopic Stenting + Dilatation", "Repair over T-Tube"],
      "CBD Stricture (Benign — Post Inflammatory)": ["Hepaticojejunostomy", "Endoscopic Dilatation + Stenting"],
      "Bile Duct Injury (Iatrogenic — Strasberg A)": ["ERCP + Stenting", "Conservative"],
      "Bile Duct Injury (Iatrogenic — Strasberg B-E)": ["Roux-en-Y Hepaticojejunostomy", "End-to-End Repair over T-Tube", "Biliary Stenting"],
      "Biliary-Enteric Anastomotic Stricture": ["Revision Hepaticojejunostomy", "Endoscopic Dilatation"],
      "Biliary Peritonitis": ["Exploratory Laparotomy + Repair", "ERCP + Stenting + Drainage"],
      "Bile Leak (Post Cholecystectomy)": ["ERCP + Stenting", "Percutaneous Drainage", "Surgical Repair"],
      "CBD Cyst (Adult)": ["Cyst Excision + HJ"],
      "Oriental Cholangiohepatitis (OCH) / Recurrent Pyogenic Cholangitis": ["Hepaticojejunostomy + Stone Clearance", "CBD Exploration + T-Tube", "Hepatic Resection (localized)", "ERCP + Sphincterotomy + Stone Extraction", "Choledochoduodenostomy", "Access Loop HJ"],
      "Intrahepatic Stones (Hepatolithiasis)": ["Hepatic Resection", "Hepaticojejunostomy + Stone Clearance", "Percutaneous Cholangioscopy + Lithotripsy"],
      "Sphincter of Oddi Dysfunction": ["Endoscopic Sphincterotomy", "Biliary Manometry + Sphincterotomy"],
      // ─── LIVER ───
      "Hydatid Cyst": ["Cystectomy + Capitonnage", "Pericystectomy", "Hepatic Resection", "PAIR (Percutaneous Aspiration)", "Hydatid Cystectomy"],
      "Liver Abscess (Amoebic)": ["Percutaneous Drainage", "Open Drainage"],
      "Liver Abscess (Pyogenic)": ["Percutaneous Drainage", "Open Drainage", "Laparoscopic Drainage"],
      "Simple Liver Cyst": ["Deroofing", "Fenestration", "Laparoscopic Fenestration"],
      "Polycystic Liver Disease": ["Fenestration", "Hepatic Resection", "Liver Transplant"],
      "Hepatic Hemangioma": ["Enucleation", "Hepatic Resection", "Observation"],
      "Hepatic Adenoma": ["Hepatic Resection", "Observation"],
      "Focal Nodular Hyperplasia": ["Observation", "Hepatic Resection (if symptomatic)"],
      "Liver Cyst (Cystadenoma)": ["Hepatic Resection", "Complete Excision"],
      // ─── SPLEEN ───
      "Splenic Abscess": ["Splenectomy", "Percutaneous Drainage"],
      "Wandering Spleen": ["Splenopexy", "Splenectomy"],
      "Splenic Artery Aneurysm": ["Splenectomy", "Endovascular Coiling"],
      "ITP (for Splenectomy)": ["Splenectomy", "Laparoscopic Splenectomy"],
      "Hereditary Spherocytosis": ["Splenectomy", "Laparoscopic Splenectomy"],
      "Splenic Cyst (Benign)": ["Splenectomy", "Cyst Deroofing", "Partial Splenectomy"],
      "Hypersplenism (Secondary)": ["Splenectomy"],
      // ─── PANCREAS ───
      "Acute Pancreatitis (Necrotizing — Surgical)": ["Necrosectomy", "VARD", "Transgastric Necrosectomy", "Percutaneous Drainage"],
      "Walled-Off Necrosis (WON)": ["Endoscopic Necrosectomy", "VARD", "Laparoscopic Cystogastrostomy + Necrosectomy"],
      "Pancreatic Pseudocyst": ["Cystogastrostomy", "Cystojejunostomy", "Endoscopic Drainage"],
      "Chronic Pancreatitis": ["Freys Procedure", "Partington Rochelle (LPJ)", "Distal Pancreatectomy", "Total Pancreatectomy + Auto-Islet Transplant"],
      "Chronic Pancreatitis with Pseudocyst": ["Freys + Cystojejunostomy", "LPJ + Cystogastrostomy"],
      "Pancreatic Duct Stricture": ["Endoscopic Stenting", "LPJ (Partington Rochelle)"],
      "Pancreatic Duct Calculi": ["ESWL + ERCP", "Freys Procedure", "LPJ"],
      "Pancreatic Fistula (External)": ["Conservative + ERCP Stenting", "Distal Pancreatectomy", "Fistulojejunostomy"],
      "Disconnected Pancreatic Duct": ["Distal Pancreatectomy", "Roux-en-Y Pancreatojejunostomy"],
      "Pancreatic Abscess": ["Percutaneous Drainage", "Surgical Drainage"],
      "Solid Pseudopapillary Neoplasm (SPN)": ["Distal Pancreatectomy", "Pancreaticoduodenectomy", "Enucleation"],
      "Pancreatic Neuroendocrine Tumor (Benign/Low-grade)": ["Enucleation", "Distal Pancreatectomy", "Whipple's Procedure"],
      "Insulinoma": ["Enucleation", "Distal Pancreatectomy"],
      "Gastrinoma (Zollinger-Ellison)": ["Excision", "Distal Pancreatectomy", "Whipple's Procedure"],
      "Serous Cystadenoma (Pancreas)": ["Observation", "Distal Pancreatectomy (if symptomatic)"],
      "Mucinous Cystadenoma (Pancreas)": ["Distal Pancreatectomy", "Whipple's Procedure"],
      "IPMN (Branch Duct — Low Risk)": ["Surveillance", "Distal Pancreatectomy"],
      "IPMN (Main Duct / High Risk)": ["Whipple's Procedure", "Total Pancreatectomy", "Distal Pancreatectomy"],
      // ─── UPPER GI ───
      "Hiatal Hernia": ["Nissen Fundoplication", "Toupet Fundoplication", "Repair + Fundoplication", "Laparoscopic Hiatal Hernia Repair"],
      "Diaphragmatic Hernia (Traumatic)": ["Laparoscopic Repair", "Open Repair", "Mesh Repair"],
      "Diaphragmatic Hernia (Congenital — Adult)": ["Laparoscopic Repair", "Open Repair"],
      "Achalasia Cardia": ["Heller's Myotomy + Dor Fundoplication", "POEM (Peroral Endoscopic Myotomy)"],
      "Zenker's Diverticulum": ["Diverticulectomy", "Endoscopic Stapling", "Cricopharyngeal Myotomy"],
      "Epiphrenic Diverticulum": ["Diverticulectomy + Myotomy", "Thoracoscopic Excision"],
      "GERD (Refractory)": ["Nissen Fundoplication", "Toupet Fundoplication", "LINX Device"],
      "Barrett's Esophagus (with HGD)": ["Endoscopic Mucosal Resection", "RFA", "Esophagectomy"],
      "Esophageal Stricture (Benign — Peptic)": ["Endoscopic Dilatation", "Esophageal Stenting"],
      "Esophageal Stricture (Corrosive)": ["Endoscopic Dilatation", "Esophageal Bypass (Colonic/Gastric)", "Esophagectomy + Reconstruction"],
      "Esophageal Perforation (Boerhaave)": ["Primary Repair + Drainage", "Esophageal Stenting", "Esophageal Diversion"],
      "Peptic Ulcer Disease (Surgical)": ["Truncal Vagotomy + Pyloroplasty", "Gastrojejunostomy"],
      "Peptic Ulcer — Perforation (Emergency)": ["Omental Patch (Graham Repair)", "Omental Patch + Definitive Surgery"],
      "Gastric Outlet Obstruction (Benign)": ["Gastrojejunostomy", "Pyloroplasty", "Endoscopic Balloon Dilatation"],
      "Gastric Volvulus": ["Gastropexy", "Fundoplication"],
      "Gastric Diverticulum": ["Diverticulectomy", "Observation"],
      "Gastric Polyp (Benign)": ["Endoscopic Polypectomy", "Wedge Resection"],
      "Gastrointestinal Stromal Tumor — Benign/Low Risk": ["Wedge Resection", "Segmental Resection", "Enucleation"],
      "Duodenal Diverticulum": ["Diverticulectomy", "Observation"],
      "Duodenal Stricture (Benign)": ["Gastrojejunostomy", "Stricturoplasty", "Endoscopic Dilatation"],
      "Superior Mesenteric Artery Syndrome": ["Duodenojejunostomy", "Strong's Procedure"],
      "Dieulafoy Lesion (Surgical)": ["Wedge Resection", "Oversewing"],
      // ─── SMALL & LARGE BOWEL ───
      "Meckel's Diverticulum": ["Resection + Ileal Anastomosis", "Diverticulectomy"],
      "Small Bowel Diverticulum": ["Diverticulectomy", "Segmental Resection"],
      "Tubercular Intestinal Stricture": ["Stricturoplasty", "Resection Anastomosis"],
      "Ileal Stricture (Tubercular — Healed)": ["Stricturoplasty", "Resection Anastomosis"],
      "Crohn's Disease (Surgical)": ["Stricturoplasty", "Segmental Resection", "Ileocecal Resection"],
      "Ulcerative Colitis (Surgical)": ["Total Proctocolectomy + IPAA (J-Pouch)", "Total Colectomy + Ileorectal Anastomosis", "Subtotal Colectomy + Ileostomy"],
      "Sigmoid Volvulus (Recurrent)": ["Elective Sigmoid Colectomy"],
      "Cecal Volvulus": ["Right Hemicolectomy", "Cecopexy"],
      "Colonic Diverticulitis (Complicated)": ["Sigmoid Colectomy", "Hartmann's Procedure"],
      "Intussusception (Adult)": ["Resection", "Reduction + Fixation"],
      "Colonic Polyp (Large — Endoscopically Unresectable)": ["Segmental Colectomy", "Transanal Excision"],
      "Familial Adenomatous Polyposis (FAP)": ["Total Proctocolectomy + IPAA", "Total Colectomy + IRA"],
      "Recurrent Appendicitis": ["Appendectomy"],
      "Appendicular Lump": ["Interval Appendectomy (6 weeks)", "Ochsner-Sherren Regimen"],
      "Acute Appendicitis": ["Appendectomy"],
      "Appendicular Perforation + Abscess": ["Emergency Appendectomy", "Appendectomy + Drainage"],
      "Adhesive Intestinal Obstruction (Recurrent)": ["Adhesiolysis"],
      "Mesenteric Ischemia (Chronic)": ["Mesenteric Bypass", "Endovascular Intervention"],
      "Short Bowel Syndrome": ["Bowel Lengthening (STEP/Bianchi)", "Intestinal Transplant"],
      "Enterocutaneous Fistula": ["Definitive Resection + Anastomosis"],
      "Entero-Enteric Fistula": ["Resection + Anastomosis"],
      "Colovesical Fistula": ["Colonic Resection + Bladder Repair"],
      "Intestinal Obstruction (Acute)": ["Exploratory Laparotomy", "Adhesiolysis"],
      "Perforation Peritonitis": ["Exploratory Laparotomy + Primary Repair", "Exploratory Laparotomy + Resection"],
      "Blunt Trauma Abdomen (for Surgery)": ["Exploratory Laparotomy"],
      "Penetrating Abdominal Injury": ["Exploratory Laparotomy"],
      // ─── STOMA REVERSAL ───
      "Ileostomy (Planned Reversal)": ["Ileostomy Reversal (Closure)"],
      "Colostomy (Planned Reversal)": ["Colostomy Reversal (Closure)", "Colostomy Reversal + Anastomosis"],
      "Hartmann's Reversal": ["Reversal of Hartmann's + Colorectal Anastomosis"],
      "Loop Ileostomy (Defunctioning — for Closure)": ["Loop Ileostomy Closure"],
      "Loop Colostomy (Defunctioning — for Closure)": ["Loop Colostomy Closure"],
      "Mucous Fistula Closure": ["Stoma Closure + Anastomosis"],
      // ─── ANORECTAL ───
      "Hemorrhoids (Grade I-II)": ["Rubber Band Ligation", "Sclerotherapy"],
      "Hemorrhoids (Grade III)": ["Hemorrhoidectomy (Milligan-Morgan)", "Closed Hemorrhoidectomy (Ferguson)", "Stapled Hemorrhoidopexy (PPH)", "Laser Hemorrhoidoplasty", "HAL-RAR"],
      "Hemorrhoids (Grade IV)": ["Hemorrhoidectomy (Milligan-Morgan)", "Stapled Hemorrhoidopexy", "Closed Hemorrhoidectomy"],
      "Thrombosed External Hemorrhoid": ["Thrombectomy / Excision"],
      "Fissure-in-Ano (Chronic)": ["Lateral Internal Sphincterotomy", "Fissurectomy + Sphincterotomy", "Advancement Flap"],
      "Fistula-in-Ano (Low/Intersphincteric)": ["Fistulotomy", "Fistulectomy"],
      "Fistula-in-Ano (High/Transsphincteric)": ["Seton Placement", "LIFT Procedure", "Endorectal Advancement Flap", "VAAFT", "FiLaC (Laser)"],
      "Fistula-in-Ano (Horseshoe)": ["Staged Seton + Fistulotomy", "Modified Hanley's Procedure"],
      "Fistula-in-Ano (Recurrent)": ["Re-do Fistulotomy", "LIFT Procedure", "Advancement Flap"],
      "Perianal Abscess": ["Incision & Drainage"],
      "Ischiorectal Abscess": ["Incision & Drainage"],
      "Pilonidal Sinus": ["Wide Excision + Primary Closure", "Wide Excision + Secondary Healing", "Karydakis Flap", "Limberg Flap", "Bascom's Cleft Lift"],
      "Pilonidal Abscess": ["Incision & Drainage"],
      "Rectal Prolapse (Complete)": ["Ventral Mesh Rectopexy", "Delorme's Procedure", "Altemeier's Procedure", "Suture Rectopexy"],
      "Rectal Prolapse (Mucosal)": ["Delorme's Procedure", "Rubber Band Ligation"],
      "Solitary Rectal Ulcer Syndrome": ["Rectopexy", "Conservative + Biofeedback"],
      "Anal Stenosis": ["Anoplasty / Advancement Flap", "Dilatation"],
      "Anal Warts / Condylomata": ["Excision / Fulguration", "Laser Ablation"],
      "Rectal Polyp (Benign)": ["Transanal Excision", "TEM / TAMIS"],
      "Anal Incontinence (Surgical)": ["Sphincteroplasty", "Graciloplasty", "Sacral Nerve Stimulation"],
      "Rectovaginal Fistula": ["Advancement Flap", "Gracilis Interposition", "Transanal Repair"],
      "Pelvic Floor Dysfunction / Obstructed Defecation": ["STARR Procedure", "Ventral Rectopexy"],
      // ─── VARICOSE VEINS ───
      "Varicose Veins (GSV)": ["Stripping + Ligation", "EVLA", "RFA", "Foam Sclerotherapy", "Glue Ablation (VenaSeal)"],
      "Varicose Veins (SSV)": ["SSV Stripping + Ligation", "EVLA", "RFA"],
      "Varicose Veins with Venous Ulcer": ["EVLA/RFA + Ulcer Care", "Stripping + Split Skin Graft"],
      "Perforator Incompetence": ["SEPS", "Foam Sclerotherapy"],
      // ─── THYROID / PARATHYROID / ENDOCRINE ───
      "Multinodular Goitre": ["Total Thyroidectomy", "Subtotal Thyroidectomy"],
      "Solitary Thyroid Nodule (Bethesda II)": ["Hemithyroidectomy", "Total Thyroidectomy"],
      "Solitary Thyroid Nodule (Bethesda III/IV)": ["Hemithyroidectomy (diagnostic)", "Total Thyroidectomy"],
      "Toxic Multinodular Goitre": ["Total Thyroidectomy"],
      "Graves' Disease (Surgical)": ["Total Thyroidectomy"],
      "Thyroglossal Cyst": ["Sistrunk's Operation"],
      "Retrosternal Goitre": ["Total Thyroidectomy (cervical ± sternotomy)"],
      "Primary Hyperparathyroidism": ["Focused Parathyroidectomy", "Bilateral Neck Exploration"],
      "Secondary Hyperparathyroidism (Renal)": ["Subtotal Parathyroidectomy", "Total Parathyroidectomy + Auto-Transplant"],
      "Parathyroid Adenoma": ["Focused Parathyroidectomy"],
      "Adrenal Adenoma (Functioning)": ["Adrenalectomy", "Laparoscopic Adrenalectomy"],
      "Pheochromocytoma (Benign)": ["Adrenalectomy", "Laparoscopic Adrenalectomy"],
      "Conn's Syndrome": ["Adrenalectomy", "Laparoscopic Adrenalectomy"],
      "Cushing's Syndrome (Adrenal)": ["Adrenalectomy"],
      "Adrenal Incidentaloma (≥4cm)": ["Adrenalectomy"],
      // ─── BREAST (BENIGN) ───
      "Fibroadenoma": ["Excision Biopsy", "Vacuum Assisted Excision"],
      "Giant Fibroadenoma": ["Excision Biopsy"],
      "Phyllodes Tumor — Benign": ["Wide Local Excision", "Simple Mastectomy"],
      "Breast Abscess": ["Incision & Drainage", "USG Guided Aspiration"],
      "Galactocele": ["Aspiration", "Excision"],
      "Gynecomastia": ["Subcutaneous Mastectomy", "Liposuction + Gland Excision"],
      "Duct Ectasia": ["Microdochectomy", "Hadfield's Operation"],
      "Breast Duct Papilloma": ["Microdochectomy"],
      // ─── HERNIA EMERGENCIES (cross-ref) ───
      "Parastomal Hernia": ["Local Mesh Repair", "Stoma Resiting + Repair", "Sugarbaker Repair (Lap)"],
      // ─── HEAD / NECK / SALIVARY ───
      "Submandibular Gland Calculus": ["Excision of Submandibular Gland"],
      "Chronic Submandibular Sialadenitis": ["Excision of Submandibular Gland"],
      "Parotid Pleomorphic Adenoma": ["Superficial Parotidectomy"],
      "Parotid Warthin's Tumor": ["Superficial Parotidectomy"],
      "Ranula": ["Excision / Marsupialization"],
      "Branchial Cyst": ["Excision"],
      "Branchial Fistula": ["Excision (Stepladder)"],
      "Carotid Body Tumor": ["Excision"],
      "Cervical Rib (Symptomatic)": ["Excision"],
      "Thoracic Outlet Syndrome": ["First Rib Resection", "Scalenectomy"],
      "Cervical Lymphadenopathy (Biopsy)": ["Excision Biopsy"],
      "Axillary Lymphadenopathy (Biopsy)": ["Excision Biopsy"],
      "Inguinal Lymphadenopathy (Biopsy)": ["Excision Biopsy"],
      // ─── THORACIC ───
      "Empyema Thoracis": ["Decortication", "Intercostal Drainage", "VATS Decortication"],
      "Pneumothorax (Recurrent)": ["VATS Pleurodesis", "Bullectomy + Pleurodesis"],
      "Bronchiectasis (Surgical)": ["Lobectomy", "Segmentectomy"],
      "Lung Abscess (Chronic)": ["Lobectomy", "Percutaneous Drainage"],
      "Mediastinal Cyst / Mass (Benign)": ["VATS Excision", "Thoracotomy + Excision"],
      // ─── RETROPERITONEAL / MESENTERIC ───
      "Psoas Abscess": ["Percutaneous Drainage", "Open Drainage"],
      "Subphrenic Abscess": ["Percutaneous Drainage", "Open Drainage"],
      "Pelvic Abscess": ["Transrectal Drainage", "Percutaneous Drainage"],
      "Retroperitoneal Fibrosis": ["Ureterolysis", "Biopsy"],
      "Retroperitoneal Cyst": ["Excision"],
      "Mesenteric Cyst": ["Excision"],
      "Omental Cyst": ["Excision"],
      "Mesenteric Lymphadenitis (Surgical)": ["Diagnostic Laparoscopy", "Excision Biopsy"],
      "Retroperitoneal Lymphangioma": ["Excision"],
      // ─── SOFT TISSUE / SKIN ───
      "Sebaceous Cyst": ["Excision"],
      "Lipoma": ["Excision"],
      "Lipoma (Large/Deep)": ["Excision under GA"],
      "Dermoid Cyst": ["Excision"],
      "Ganglion": ["Excision"],
      "Neurofibroma": ["Excision"],
      "Soft Tissue Abscess": ["Incision & Drainage"],
      "Keratoacanthoma": ["Excision Biopsy"],
      "Infected Sebaceous Cyst": ["I&D → Delayed Excision"],
      "Granuloma": ["Excision Biopsy"],
      "Foreign Body (Subcutaneous)": ["Removal"],
      "Lymphangioma": ["Excision"],
      "Lymphocele": ["Drainage", "Excision"],
      "Cystic Hygroma": ["Excision", "Sclerotherapy"],
      "Sacrococcygeal Teratoma": ["Excision"],
      "Sinus Tract / Chronic Discharging Sinus": ["Excision", "Curettage"],
      "Cavernous Hemangioma": ["Excision", "Sclerotherapy"],
      "Abdominal Wall Desmoid Tumor": ["Wide Excision"],
      // ─── UROLOGY ───
      "Hydrocele (Primary)": ["Jaboulay's Eversion", "Lord's Plication"],
      "Epididymal Cyst": ["Excision"],
      "Spermatocele": ["Excision"],
      "Varicocele": ["Varicocelectomy", "Microsurgical Varicocelectomy", "Palomo's"],
      "Undescended Testis": ["Orchidopexy"],
      "Testicular Torsion (Surgical)": ["Orchidopexy (bilateral)", "Orchidectomy (if non-viable)"],
      "Fournier's Gangrene": ["Emergency Debridement", "Staged Reconstruction"],
      "Phimosis": ["Circumcision"],
      "Paraphimosis": ["Dorsal Slit", "Circumcision"],
      "Urethral Stricture": ["Urethroplasty", "Endoscopic Internal Urethrotomy (OIU)"],
      "Renal Calculus (Staghorn / Complex)": ["PCNL", "Pyelolithotomy", "Nephrectomy (non-functioning kidney)"],
      "Ureteric Calculus (Impacted)": ["Ureterolithotomy", "Ureteroscopy + Lithotripsy"],
      "Bladder Stone": ["Cystolithotomy", "Endoscopic Cystolitholapaxy"],
      "BPH (Benign Prostatic Hyperplasia)": ["TURP", "Open Prostatectomy (Freyer's/Millin's)", "Laser Prostatectomy (HoLEP)"],
      "Urinary Retention (Acute — Surgical)": ["Suprapubic Cystostomy", "TURP"],
      "Hydronephrosis (PUJ Obstruction)": ["Pyeloplasty", "Laparoscopic Pyeloplasty"],
      "Vesicoureteric Reflux (Surgical)": ["Ureteric Reimplantation", "Endoscopic Injection (Deflux)"],
      "Renal Cyst (Symptomatic)": ["Laparoscopic Decortication", "Percutaneous Aspiration + Sclerotherapy"],
      "Nephroptosis (Symptomatic)": ["Nephropexy"],
      "Ureteric Injury (Iatrogenic)": ["End-to-End Anastomosis", "Reimplantation + Psoas Hitch", "Boari Flap"],
      "Posterior Urethral Valve": ["Endoscopic Valve Ablation", "Vesicostomy"],
      "Hypospadias": ["Urethroplasty (Snodgrass / Mathieu)", "Staged Repair"],
      "Epispadias": ["Epispadias Repair"],
      // ─── GYNAECOLOGY (managed by general surgery) ───
      "Ovarian Cyst (Benign / Dermoid)": ["Laparoscopic Cystectomy", "Oophorectomy", "Laparotomy + Cystectomy"],
      "Ovarian Torsion": ["Laparoscopic Detorsion + Cystectomy", "Oophorectomy"],
      "Ectopic Pregnancy": ["Laparoscopic Salpingectomy", "Laparoscopic Salpingostomy", "Open Salpingectomy"],
      "Tubo-Ovarian Abscess": ["Laparoscopic Drainage", "Laparotomy + Drainage + Salpingectomy"],
      "Endometriosis (Surgical)": ["Laparoscopic Excision / Ablation", "Laparoscopic Cystectomy (Endometrioma)"],
      "Fibroid Uterus (Surgical)": ["Myomectomy (Laparoscopic)", "Myomectomy (Open)", "Total Abdominal Hysterectomy", "Total Laparoscopic Hysterectomy"],
      "Uterine Prolapse": ["Vaginal Hysterectomy + Pelvic Floor Repair", "Sacrocolpopexy"],
      "Bartholin's Cyst / Abscess": ["Marsupialization", "Excision"],
      "Cervical Polyp": ["Polypectomy"],
      "Broad Ligament Cyst": ["Laparoscopic Excision", "Open Excision"],
      "Hydatid of Morgagni (Torsion)": ["Laparoscopic Excision"],
      // ─── DIABETIC FOOT / VASCULAR ───
      "Diabetic Foot — Wagner 1-2": ["Debridement + Wound Care", "Ray Amputation"],
      "Diabetic Foot — Wagner 3-4": ["Debridement", "Transmetatarsal Amputation", "Below Knee Amputation"],
      "Diabetic Foot — Wagner 5": ["Below Knee Amputation", "Above Knee Amputation"],
      "Chronic Non-Healing Ulcer": ["Debridement + SSG", "Debridement + VAC"],
      "Gangrene — Toe": ["Toe / Ray Amputation"],
      "Gangrene — Foot (Wet)": ["Guillotine / BKA"],
      "Peripheral Arterial Disease (Critical Limb Ischaemia)": ["Embolectomy", "Bypass Grafting", "Amputation"],
      "Arteriovenous Malformation": ["Excision", "Embolization"],
      // ─── BURNS / PLASTICS ───
      "Post-Burns Contracture": ["Contracture Release + SSG / Flap"],
      "Keloid / Hypertrophic Scar": ["Excision + Adjuvant"],
      // ─── DIAGNOSTIC / STAGING ───
      "Diagnostic Laparoscopy": ["Diagnostic Laparoscopy + Biopsy"],
      "Staging Laparoscopy": ["Staging Laparoscopy + Peritoneal Washings"],
      "EUA (Examination Under Anesthesia)": ["EUA + Biopsy"],
      "Feeding Jejunostomy (Planned)": ["Feeding Jejunostomy"],
    },
  },
};

const MALIGNANCY_SITES = {
  "Breast": { procedures: ["Modified Radical Mastectomy (MRM)", "Breast Conservation Surgery (BCS) + ALND", "BCS + SLNB", "Simple Mastectomy + SLNB", "Toilet Mastectomy", "Breast Reconstruction", "Oncoplastic Surgery", "SLNB alone", "ALND alone", "Skin-Sparing Mastectomy", "Nipple-Sparing Mastectomy"] },
  "Thyroid": { procedures: ["Total Thyroidectomy", "Total Thyroidectomy + Central Neck Dissection", "Total Thyroidectomy + MRND", "Total Thyroidectomy + Bilateral Neck Dissection", "Hemithyroidectomy (low-risk micro)", "Completion Thyroidectomy", "Isthmusectomy"] },
  "Esophagus — Upper Third": { procedures: ["Definitive Chemoradiation", "McKeown Esophagectomy (3-field)", "Pharyngo-Laryngo-Esophagectomy"] },
  "Esophagus — Middle Third": { procedures: ["McKeown Esophagectomy", "Ivor Lewis Esophagectomy", "MIE (Minimally Invasive)", "Transhiatal Esophagectomy"] },
  "Esophagus — Lower / GEJ": { procedures: ["Ivor Lewis Esophagectomy", "Transhiatal Esophagectomy", "MIE", "Sweet's Esophagectomy", "Total Gastrectomy + Distal Esophagectomy"] },
  "Stomach — Proximal": { procedures: ["Total Gastrectomy + D2 Lymphadenectomy", "Proximal Gastrectomy", "Palliative Feeding Jejunostomy"] },
  "Stomach — Distal / Antrum": { procedures: ["Subtotal Gastrectomy + D2", "Total Gastrectomy + D2", "Palliative Gastrojejunostomy", "Palliative Feeding Jejunostomy"] },
  "Stomach — Linitis Plastica": { procedures: ["Total Gastrectomy + D2", "Palliative Chemotherapy", "Palliative Feeding Jejunostomy"] },
  "Stomach — GOO (Malignant)": { procedures: ["Palliative Gastrojejunostomy", "Endoscopic Stenting", "Subtotal Gastrectomy (if resectable)"] },
  "Liver (HCC)": { procedures: ["Anatomical Hepatectomy", "Non-Anatomical Resection", "Liver Resection", "Liver Transplant", "RFA", "TACE"] },
  "Liver — Metastases (Colorectal)": { procedures: ["Hepatic Metastasectomy", "RFA", "TACE", "Staged Hepatectomy / ALPPS"] },
  "Gall Bladder": { procedures: ["Radical Cholecystectomy (Liver Bed + LN)", "Extended Cholecystectomy", "Palliative Biliary Stenting / PTBD", "Hepaticojejunostomy"] },
  "Bile Duct — Hilar (Klatskin)": { procedures: ["Hepatectomy + Caudate Lobe + HJ", "Palliative PTBD / Stenting", "Liver Transplant (selected)"] },
  "Bile Duct — Distal": { procedures: ["Pancreaticoduodenectomy (Whipple's)", "Palliative Biliary Stenting"] },
  "Periampullary Region": { procedures: ["Whipple's Procedure", "PPPD", "Palliative Triple Bypass", "Endoscopic Stenting"] },
  "Pancreas — Head": { procedures: ["Whipple's Procedure", "PPPD", "Palliative Triple Bypass", "Palliative Biliary Stenting"] },
  "Pancreas — Body / Tail": { procedures: ["Distal Pancreatectomy + Splenectomy", "Distal Pancreatectomy", "Palliative Celiac Plexus Block"] },
  "Colon — Cecum / Ascending": { procedures: ["Right Hemicolectomy + D3", "Right Hemicolectomy", "Extended Right Hemicolectomy", "Palliative Ileostomy"] },
  "Colon — Transverse": { procedures: ["Extended Right Hemicolectomy", "Transverse Colectomy"] },
  "Colon — Descending": { procedures: ["Left Hemicolectomy", "Palliative Colostomy"] },
  "Colon — Sigmoid": { procedures: ["Sigmoid Colectomy / High AR", "Sigmoid Colectomy", "Hartmann's Procedure", "Palliative Colostomy"] },
  "Colon — Obstruction / Perforation": { procedures: ["Hartmann's Procedure", "Subtotal Colectomy", "Defunctioning Stoma → Staged Resection"] },
  "Rectum — Upper (12-15cm)": { procedures: ["Anterior Resection + TME", "Anterior Resection", "Palliative Loop Colostomy"] },
  "Rectum — Mid (7-12cm)": { procedures: ["Low Anterior Resection + TME", "Low Anterior Resection", "Intersphincteric Resection", "Palliative Colostomy"] },
  "Rectum — Low (<7cm)": { procedures: ["Ultra Low AR + Coloanal Anastomosis", "APR (Miles' Operation)", "Intersphincteric Resection", "Palliative Colostomy"] },
  "Anal Canal": { procedures: ["Wide Local Excision (early)", "APR", "Definitive Chemoradiation (Nigro)"] },
  "Small Intestine": { procedures: ["Segmental Resection + Anastomosis", "Wide Excision + Lymphadenectomy", "Palliative Bypass"] },
  "Appendix": { procedures: ["Appendectomy (<2cm carcinoid)", "Right Hemicolectomy (>2cm / adenoCA)"] },
  "Retroperitoneum": { procedures: ["Wide / Compartmental Resection", "Multivisceral Resection", "Palliative Debulking"] },
  "Soft Tissue — Extremity": { procedures: ["Wide Local Excision + RT", "Compartmental Resection", "Amputation"] },
  "Soft Tissue — Trunk": { procedures: ["Wide Local Excision", "Excision + Flap Reconstruction"] },
  "Skin (Melanoma)": { procedures: ["Wide Excision (1-2cm margin)", "Wide Excision + SLNB", "Wide Excision + LN Dissection"] },
  "Adrenal": { procedures: ["Adrenalectomy", "Bilateral Adrenalectomy"] },
  "Parotid": { procedures: ["Total Parotidectomy ± Nerve Sacrifice", "Total Parotidectomy + Neck Dissection"] },
  "Kidney": { procedures: ["Radical Nephrectomy", "Partial Nephrectomy"] },
  "Urinary Bladder": { procedures: ["Radical Cystectomy + Ileal Conduit", "Partial Cystectomy", "TURBT"] },
  "Testis": { procedures: ["High Inguinal Orchidectomy", "Retroperitoneal Lymph Node Dissection"] },
  "Unknown Primary (CUP)": { procedures: ["Excision Biopsy", "Core Biopsy + Staging", "Palliative Resection"] },
};

// ─── Clinical Details Constants ─────────────────────────────
const COMORBIDITIES = ["Hypertension", "Diabetes Mellitus", "CKD", "CAD", "Hypothyroid", "COPD"];
const BLOOD_GROUPS = ["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"];
const HISTOLOGY_TYPES = ["Adenocarcinoma", "Squamous Cell Carcinoma", "GIST", "NET / Carcinoid", "Sarcoma", "Lymphoma", "Papillary Carcinoma", "Follicular Carcinoma", "Medullary Carcinoma", "Anaplastic Carcinoma", "Melanoma", "Transitional Cell Carcinoma", "Hepatocellular Carcinoma", "Cholangiocarcinoma", "Mucinous Adenocarcinoma", "Signet Ring Cell", "Undifferentiated", "Others"];
const PALLOR_ICTERUS = ["Absent", "Present"];
const ACCESS_MODES = ["Laparoscopic", "Open", "Lap/Open", "VATS", "Endoscopic", "Robotic", "Others"];
const OP_ACCESS_MODES = ["Laparoscopic", "Laparoscopy Assisted", "Laparoscopy Converted to Open", "Open", "Laparoscopy + Endoscopy", "Laparoscopy + Open", "VATS", "Endoscopic", "Other"];
const ANAESTHESIA = ["GA", "SA", "RA", "LA", "Other"];
const SURGEONS = []; // Legacy - now uses config.surgeons
const ASSISTANTS = []; // Legacy - now uses config.surgeons
const OP_PROCEDURES = [
  // Gallbladder & Biliary
  "Cholecystectomy", "Completion Cholecystectomy", "Subtotal Cholecystectomy", "Extended Cholecystectomy", "Radical Cholecystectomy", "Cholecystectomy With Liver Resection", "Cholecystostomy", "CBD Exploration", "CBD Exploration With T Tube", "Choledocoduodenostomy", "Choledocojejunostomy", "Hepaticojejunostomy", "Roux-en-Y Hepaticojejunostomy", "Primary Closure Of CBD", "Biliary Stenting (Intraoperative)", "Choledochal Cyst Excision", "Cholecystectomy + IOC", "Triple Tube Drainage", "Bilioenteric Bypass", "Hepaticoduodenostomy",
  // Liver
  "Hepatectomy", "Right Hepatectomy", "Left Hepatectomy", "Extended Right Hepatectomy", "Extended Left Hepatectomy", "Segmentectomy", "Non-Anatomical Liver Resection", "Liver Wedge Resection", "Hydatid Liver Cystectomy", "Pericystectomy", "Liver Abscess Drainage", "ALPPS Procedure", "Liver Biopsy", "Caudate Lobectomy", "Mesohepatectomy", "RFA Of Liver Lesion", "TACE (Transarterial Chemoembolization)", "Liver Cyst Deroofing",
  // Pancreas
  "Whipple Procedure", "PPPD", "Distal Pancreatectomy", "Distal Pancreatectomy + Splenectomy", "Freys Procedure", "Partington Rochelle", "Pancreatic Necrosectomy", "Pancreatic Cystogastrostomy", "Enucleation (Pancreatic)", "Central Pancreatectomy", "Total Pancreatectomy", "VARD (Video-Assisted Retroperitoneal Debridement)", "Transgastric Necrosectomy", "Pancreatic Abscess Drainage", "Pancreaticojejunostomy (Puestow)", "Beger's Procedure",
  // Stomach & Duodenum
  "Total Gastrectomy", "Subtotal Gastrectomy", "Partial Gastrectomy", "Proximal Gastrectomy", "Sleeve Gastrectomy", "Gastrojejunostomy", "Palliative Gastrojejunostomy", "Truncal Vagotomy", "Pyloroplasty", "Gastric Perforation Closure (Graham Patch)", "Gastrectomy + D2 Lymphadenectomy", "Excision Of GIST", "Gastrostomy", "Percutaneous Endoscopic Gastrostomy (PEG)", "Ramstedt's Pyloromyotomy", "Billroth I", "Billroth II", "Roux-en-Y Reconstruction", "Duodenal Ulcer Perforation Repair", "Duodenojejunostomy", "Duodenal Diverticulectomy", "Gastric Wedge Resection", "Dieulafoy Lesion Excision",
  // Esophagus
  "Ivor Lewis Esophagectomy", "McKeown Esophagectomy", "Transhiatal Esophagectomy", "MIE (Minimally Invasive Esophagectomy)", "Heller's Myotomy", "Esophageal Stenting", "Esophageal Diverticulectomy", "Zenker's Diverticulectomy", "Esophageal Perforation Repair", "Colon Interposition (Esophageal Replacement)", "Peroral Endoscopic Myotomy (POEM)", "Epiphrenic Diverticulectomy",
  // Bariatric
  "OAGB", "Roux-en-Y Gastric Bypass", "SADI-S", "Revision Bariatric Procedure", "Intragastric Balloon", "Adjustable Gastric Banding", "BPD-DS (Biliopancreatic Diversion With Duodenal Switch)", "Endoscopic Sleeve Gastroplasty",
  // Small Bowel
  "Resection Anastomosis Of Small Bowel", "Stricturoplasty", "Meckel's Diverticulectomy", "Adhesiolysis", "Jejunostomy", "Feeding Jejunostomy", "Ileostomy", "Loop Ileostomy", "End Ileostomy", "Ileostomy Reversal", "Duodenostomy", "Small Bowel Bypass", "Ileal Conduit", "Side-to-Side Anastomosis", "End-to-End Anastomosis", "End-to-Side Anastomosis", "Enterotomy + Foreign Body Removal", "Bypass Of Stricture", "Small Bowel Diverticulectomy", "Mesenteric Vascular Embolectomy",
  // Colon & Rectum
  "Right Hemicolectomy", "Right Extended Hemicolectomy", "Transverse Colectomy", "Left Hemicolectomy", "Extended Left Hemicolectomy", "Sigmoidectomy", "Sigmoid Colectomy", "Subtotal Colectomy", "Total Colectomy", "Total Proctocolectomy", "Hartmann's Procedure", "Hartmann's Reversal", "Anterior Resection", "LAR", "Ultra LAR", "APR (Abdominoperineal Resection)", "Intersphincteric Resection", "TAMIS", "TEM (Transanal Endoscopic Microsurgery)", "Colostomy", "Loop Colostomy", "End Colostomy", "Colostomy Reversal", "Frykman Goldberg's Procedure", "Ventral Mesh Rectopexy", "Delorme's Procedure", "Altemeier's Procedure", "Ileoanal Pouch (J-Pouch)", "Ileorectal Anastomosis", "Cecostomy", "Appendicostomy (Malone)", "Colocolonic Anastomosis", "Sigmoid Volvulus Derotation + Fixation", "Cecal Volvulus Reduction + Cecopexy", "Polypectomy (Colonoscopic)", "EMR (Endoscopic Mucosal Resection)",
  // Proctology
  "MIPH", "Hemorrhoidectomy (Milligan-Morgan)", "Hemorrhoidectomy (Ferguson)", "Stapled Hemorrhoidopexy", "Laser Hemorrhoidoplasty", "HAL-RAR", "Rubber Band Ligation", "Fistulotomy", "Fistulectomy", "Seton Placement", "LIFT Procedure", "VAAFT", "FiLaC (Laser Fistula)", "Advancement Flap (Fistula)", "Lateral Internal Sphincterotomy", "Fissurectomy + Sphincterotomy", "Anoplasty", "Pilonidal Sinus Excision", "Karydakis Flap", "Limberg Flap", "Bascom's Cleft Lift", "Transanal Excision", "Sclerotherapy (Hemorrhoids)", "Infrared Coagulation (Hemorrhoids)", "Perianal Abscess Drainage", "Ischiorectal Abscess Drainage", "Sphincteroplasty", "Gracilis Muscle Transposition", "Rectal Prolapse Mesh Repair", "STARR Procedure", "Thiersch Procedure", "EUA + Biopsy (Rectum)",
  // Hernia
  "Lichtenstein Mesh Repair", "TEP Repair", "TAPP Repair", "Shouldice Repair", "Bilateral TEP Repair", "Bilateral TAPP Repair", "McEvedy's Approach", "Umbilical Hernia Mesh Repair", "Sublay Mesh Repair", "Onlay Mesh Repair", "IPOM Repair", "IPOM Plus", "eTEP Repair", "eTEP-TAR", "rTAPP Repair", "Anterior Component Separation", "Posterior Component Separation (TAR)", "Sugarbaker Repair", "Nissen Fundoplication", "Toupet Fundoplication", "Dor Fundoplication", "Diaphragmatic Hernia Repair", "Bassini Repair", "Desarda Repair", "Darning Repair", "Plug Mesh Repair", "Rives-Stoppa Repair", "Herniorrhaphy (Pediatric)", "Mayo's Repair (Umbilical)", "Keyhole Repair (Parastomal)", "Laparoscopic Hernia Repair (IPOM)", "Robotics-Assisted Hernia Repair", "Emergency Hernioplasty", "Emergency Hernioplasty + Bowel Resection",
  // Thyroid & Parathyroid
  "Total Thyroidectomy", "Hemithyroidectomy", "Subtotal Thyroidectomy", "Completion Thyroidectomy", "Total Thyroidectomy + Central Neck Dissection", "Total Thyroidectomy + MRND", "Total Thyroidectomy + Bilateral Neck Dissection", "Isthmusectomy", "Sistrunk's Operation", "Parathyroidectomy", "Subtotal Parathyroidectomy", "Total Parathyroidectomy + Autotransplant", "Thyroidectomy + Sternotomy (Retrosternal Goitre)", "Minimally Invasive Thyroidectomy",
  // Breast
  "Modified Radical Mastectomy (MRM)", "Simple Mastectomy", "Breast Conservation Surgery (BCS)", "BCS + ALND", "BCS + SLNB", "Simple Mastectomy + SLNB", "SLNB", "ALND", "Subcutaneous Mastectomy", "Skin-Sparing Mastectomy", "Nipple-Sparing Mastectomy", "Microdochectomy", "Hadfield's Operation", "Excision Biopsy (Breast)", "Wide Local Excision (Breast)", "Oncoplastic Surgery", "Breast Reconstruction", "TRAM Flap", "DIEP Flap", "Latissimus Dorsi Flap", "Implant-Based Reconstruction", "Wire-Localized Excision Biopsy", "Vacuum-Assisted Biopsy", "Lumpectomy", "Central Duct Excision", "Breast Abscess Drainage",
  // Spleen
  "Splenectomy", "Partial Splenectomy", "Splenic Salvage / Splenorrhaphy",
  // Adrenal
  "Adrenalectomy", "Bilateral Adrenalectomy", "Retroperitoneoscopic Adrenalectomy",
  // Appendix
  "Appendectomy", "Appendectomy + Drainage", "Interval Appendectomy", "Appendicular Abscess Drainage", "Right Hemicolectomy (Appendicular Malignancy)",
  // Salivary Glands
  "Superficial Parotidectomy", "Total Parotidectomy", "Excision Of Submandibular Gland", "Sublingual Gland Excision", "Sialendoscopy", "Salivary Calculus Removal", "Parotid Abscess Drainage",
  // Vascular
  "Varicose Vein Stripping + Ligation", "EVLA", "RFA (Varicose Veins)", "Foam Sclerotherapy", "VenaSeal Ablation", "SEPS", "Embolectomy", "Thrombectomy", "Femoral-Popliteal Bypass", "Aortobifemoral Bypass", "AV Fistula Creation", "AV Fistula Repair", "Carotid Endarterectomy", "Fasciotomy (Compartment Syndrome)", "Venous Cutdown",
  // Amputations
  "Toe Amputation", "Ray Amputation", "Transmetatarsal Amputation", "Below Knee Amputation", "Above Knee Amputation", "Guillotine Amputation", "Hip Disarticulation", "Knee Disarticulation", "Finger Amputation", "Forearm Amputation", "Forequarter Amputation", "Hindquarter Amputation", "Stump Revision",
  // Wound & Soft Tissue
  "Incision & Drainage", "Debridement", "Debridement + SSG", "Debridement + VAC", "Split Skin Grafting", "Full Thickness Skin Graft", "Excision Biopsy", "Wide Local Excision", "Excision", "Marsupialization", "Contracture Release + SSG / Flap", "Lipoma Excision", "Dermoid Cyst Excision", "Sebaceous Cyst Excision", "Ganglion Excision", "Soft Tissue Sarcoma Excision", "Flap Cover (Local / Pedicled)", "Negative Pressure Wound Therapy (NPWT)", "Secondary Suturing", "Wound Exploration + Repair", "Tissue Expander Insertion", "Scar Revision",
  // Neck
  "Excision Biopsy (Lymph Node)", "MRND (Modified Radical Neck Dissection)", "Radical Neck Dissection", "Selective Neck Dissection", "Branchial Cyst Excision", "Branchial Fistula Excision", "Thyroglossal Cyst Excision", "Cervical Rib Excision", "Cystic Hygroma Excision", "Carotid Body Tumour Excision", "Lymph Node Biopsy", "Scalene Node Biopsy", "Neck Abscess Drainage",
  // Emergency / Trauma
  "Exploratory Laparotomy", "Exploratory Laparotomy + Primary Repair", "Exploratory Laparotomy + Resection", "Damage Control Laparotomy", "Laparotomy + Peritoneal Lavage", "Gastric Perforation Repair", "Duodenal Perforation Repair (Graham Patch)", "Ileal Perforation Repair", "Colonic Perforation Repair", "Repair Of Mesenteric Tear", "Splenorrhaphy / Splenectomy (Trauma)", "Liver Repair (Trauma)", "Pancreatic Injury Repair", "Diaphragmatic Injury Repair", "Bladder Repair (Trauma)", "Retroperitoneal Hematoma Evacuation", "Relook Laparotomy", "Temporary Abdominal Closure (Bogota Bag)", "Abdominal Wall Reconstruction", "DPL (Diagnostic Peritoneal Lavage)",
  // Laparoscopic General
  "Diagnostic Laparoscopy", "Diagnostic Laparoscopy and Proceed", "Laparoscopic Adhesiolysis", "Laparoscopic Peritoneal Lavage", "Laparoscopic CBD Exploration", "Laparoscopic Splenectomy", "Laparoscopic Appendectomy", "Laparoscopic Right Hemicolectomy", "Laparoscopic Left Hemicolectomy", "Laparoscopic Sigmoid Colectomy", "Laparoscopic APR", "Laparoscopic LAR", "Laparoscopic Total Colectomy", "Laparoscopic Rectopexy", "Laparoscopic Liver Resection", "Laparoscopic Adrenalectomy", "Single Incision Laparoscopic Surgery (SILS)", "Laparoscopic Common Bile Duct Exploration", "Laparoscopic Gastrojejunostomy", "Laparoscopic Feeding Jejunostomy",
  // Urology-Related (General Surgery overlap)
  "Orchidopexy", "Jaboulay's Eversion (Hydrocele)", "Lord's Plication (Hydrocele)", "Varicocelectomy", "Microsurgical Varicocelectomy", "Circumcision", "Epididymal Cyst Excision", "Testicular Biopsy", "Vasectomy", "High Inguinal Orchidectomy",
  // Urology Extended
  "PCNL (Percutaneous Nephrolithotomy)", "Pyelolithotomy", "Ureterolithotomy", "Ureteroscopy + Lithotripsy", "Cystolithotomy", "Endoscopic Cystolitholapaxy", "TURP", "Open Prostatectomy", "Laser Prostatectomy (HoLEP)", "Suprapubic Cystostomy", "Pyeloplasty", "Laparoscopic Pyeloplasty", "Ureteric Reimplantation", "Endoscopic Injection (Deflux)", "Laparoscopic Decortication (Renal Cyst)", "Nephropexy", "Urethroplasty", "Endoscopic Internal Urethrotomy (OIU)", "Dorsal Slit", "Ureteric End-to-End Anastomosis", "Psoas Hitch + Reimplantation", "Boari Flap", "Endoscopic Valve Ablation", "Vesicostomy", "Snodgrass Urethroplasty", "Epispadias Repair", "Nephrectomy",
  // Gynaecology (managed by general surgery)
  "Laparoscopic Ovarian Cystectomy", "Oophorectomy", "Laparoscopic Salpingectomy", "Laparoscopic Salpingostomy", "Open Salpingectomy", "Laparoscopic Detorsion + Cystectomy", "Laparoscopic Drainage (Tubo-Ovarian Abscess)", "Laparoscopic Endometriosis Excision", "Myomectomy (Laparoscopic)", "Myomectomy (Open)", "Total Abdominal Hysterectomy (TAH)", "Total Laparoscopic Hysterectomy (TLH)", "Vaginal Hysterectomy + Pelvic Floor Repair", "Sacrocolpopexy", "Marsupialization (Bartholin)", "Bartholin Cyst Excision", "Cervical Polypectomy", "Broad Ligament Cyst Excision",
  // Miscellaneous
  "Mesenteric Cyst Excision", "Omental Cyst Excision", "Retroperitoneal Cyst Excision", "Abdominal Wall Desmoid Excision", "Ranula Excision", "Keloid Excision", "Tracheostomy", "Intercostal Drain Insertion", "Central Line Insertion", "Peritoneal Dialysis Catheter Insertion", "PICC Line Insertion", "Chemoport Insertion", "Peritoneal Biopsy", "Omental Biopsy", "Mesenteric Lymph Node Biopsy", "Trucut Biopsy", "Skin Biopsy", "EUA (Examination Under Anaesthesia)", "Second Look Surgery", "Staging Laparoscopy", "Palliative Bypass Procedure", "Tube Thoracostomy", "Mini Thoracotomy", "VATS Decortication", "VATS Pleurodesis", "Chest Wall Resection", "Mediastenotomy", "Pericardial Window", "Pericardiostomy",
];
const INTRA_COMPLICATIONS = ["None", "Hemorrhage", "Bile Duct Injury", "Bowel Injury", "Injury to Other Organs", "Anesthetic Complication", "Other"];
const SHIFTED_TO = ["ICU", "PACU", "Ward", "Other"];
const PAC_STATUS = ["", "OK", "Review"];

const emptyOpDetails = () => ({
  surgeryDateActual: "", startTime: "", endTime: "",
  anaesthesia: "", anaesthesiaOther: "", anaesthetist: "",
  operatingSurgeon: "", surgeonOther: "",
  firstAssistant: "", assistantOther: "",
  secondAssistant: "", secondAssistantOther: "",
  thirdAssistant: "", thirdAssistantOther: "",
  fourthAssistant: "", fourthAssistantOther: "",
  fifthAssistant: "", fifthAssistantOther: "",
  otherSurgeons: "", theatreAssistant: "",
  patientPosition: "", patientPositionOther: "",
  opAccessMode: "", opAccessOther: "",
  primaryProcedure: "", primaryProcManual: "",
  adjunctProcedure: "", secondaryProcedure: "",
  intraFindings: [""],
  specimenSent: "No", specimenDetails: "",
  operativeNote: "",
  bloodLoss: "", prbcTransfusion: "0", ffpUnits: "0", plateletUnits: "0",
  complication1: "", complication1Other: "",
  complication2: "", complication2Other: "",
  stoma: "", stomaType: "", stomaSite: "",
  drains: "No", drainList: [],  // [{type:"", site:""}]
  rylesTube: "No", foleysCatheter: "No",
  thoracostomy: "None",
  epidural: "No", extubation: "Yes",
  abdominalClosure: "",
  shiftedTo: "", otherInfo: "",
});

const emptyPostOp = () => ({
  complications: [""],
  drainRemoval: [],  // [{drainIdx: 0, pod: "", status: "Removed"}] — built from op drainList
  rylesRemoval: "", // POD or "In Situ"
  catheterRemoval: "", // POD or "In Situ"
  flatusDay: "", bowelsDay: "", oralsDay: "",
  ambulationDay: "", sutureRemovalDay: "",
  woundCondition: "",
  postOpImaging: "", postOpInvestigations: "",
  hpeReport: "", hpeStage: "",
  finalDx: {}, // { type, primaryDx, primaryLaterality, secondaryDx, malSite, histology, histologyOther, pathStage, notes, changed }
  dischargeMedications: "", dietInstructions: "",
  adviceOnDischarge: "", hospitalStayNotes: "",
  followUpDate: "", followUpInstructions: "",
});

const POST_OP_COMPLICATIONS = ["None", "Surgical Site Infection", "Wound Dehiscence", "Anastomotic Leak", "Intra-abdominal Abscess", "Post-op Hemorrhage", "DVT / PE", "Pneumonia", "UTI", "Paralytic Ileus", "Bile Leak", "Pancreatic Fistula", "Enterocutaneous Fistula", "Incisional Hernia", "Other"];
const ASH_GRADES = ["Nyhus I", "Nyhus II", "Nyhus IIIA", "Nyhus IIIB", "Nyhus IIIC (Femoral)", "Nyhus IV (Recurrent)", "EHS L1", "EHS L2", "EHS L3", "EHS M1", "EHS M2", "EHS M3"];

// Diagnoses needing laterality
const LATERALITY_DX = [
  "Inguinal Hernia", "Femoral Hernia", "Recurrent Inguinal Hernia",
  "Fibroadenoma", "Phyllodes Tumor", "Breast Abscess", "Gynecomastia",
  "Varicose Veins", "Undescended Testis", "Hydrocele", "Varicocele",
  "Carcinoma Breast", "Epididymal Cyst", "Spermatocele",
  "Testicular Torsion", "Lumbar Hernia",
  "Ovarian Cyst", "Ovarian Torsion", "Ectopic Pregnancy", "Tubo-Ovarian Abscess",
  "Renal Calculus", "Ureteric Calculus", "Hydronephrosis", "Renal Cyst",
  "Vesicoureteric Reflux", "Bartholin",
];
const needsLaterality = (dx) => LATERALITY_DX.some(l => dx && dx.includes(l));

// Diagnoses needing site specification
const SITE_DX = {
  "Hydatid Cyst": ["Liver", "Lung — Right", "Lung — Left", "Spleen", "Kidney", "Pelvis", "Peritoneum", "Bone", "Brain", "Other"],
  "Abscess": ["Liver", "Splenic", "Psoas", "Intra-abdominal", "Pelvic", "Subphrenic", "Lung", "Other"],
  "GIST": ["Gastric", "Duodenal", "Jejunal", "Ileal", "Colonic", "Rectal", "Esophageal", "Other"],
  "Lymphadenopathy": ["Cervical", "Axillary", "Inguinal", "Mesenteric", "Retroperitoneal", "Supraclavicular", "Other"],
  "Soft Tissue Sarcoma": ["Upper Extremity", "Lower Extremity", "Trunk", "Retroperitoneal", "Head/Neck"],
  "Melanoma": ["Head/Neck", "Trunk", "Upper Extremity", "Lower Extremity", "Subungual"],
  "Intrahepatic Stones": ["Left Lobe", "Right Lobe", "Bilateral"],
  "Polycystic Liver": ["Bilateral", "Left Lobe Predominant", "Right Lobe Predominant"],
};
const getSiteOptions = (dx) => { for (const [k, v] of Object.entries(SITE_DX)) { if (dx && dx.includes(k)) return v; } return null; };

// Expand diagnoses: add laterality/site variants as separate entries
function expandDiagnoses(cats) {
  const expanded = {};
  for (const [catKey, cat] of Object.entries(cats)) {
    expanded[catKey] = { ...cat, diagnoses: {} };
    for (const [dx, procs] of Object.entries(cat.diagnoses)) {
      // Check if this diagnosis needs laterality
      if (LATERALITY_DX.some(l => dx.includes(l))) {
        expanded[catKey].diagnoses[dx + " (Right)"] = [...procs];
        expanded[catKey].diagnoses[dx + " (Left)"] = [...procs];
        expanded[catKey].diagnoses[dx + " (Bilateral)"] = [...procs];
      }
      // Check if this diagnosis needs site
      let hasSite = false;
      for (const [siteDx, sites] of Object.entries(SITE_DX)) {
        if (dx.includes(siteDx)) {
          hasSite = true;
          for (const site of sites) {
            expanded[catKey].diagnoses[dx + " — " + site] = [...procs];
          }
          break;
        }
      }
      // If no laterality or site, keep as-is
      if (!LATERALITY_DX.some(l => dx.includes(l)) && !hasSite) {
        expanded[catKey].diagnoses[dx] = [...procs];
      }
    }
  }
  return expanded;
}
const EXPANDED_BENIGN = expandDiagnoses(BENIGN_CATEGORIES);

// Diagnoses that are hernias (need ASH classification)
const isHernia = (dx) => dx && (dx.toLowerCase().includes("hernia") || dx.toLowerCase().includes("hernioplasty"));

// Subtypes
const SUBTYPE_DX = {
  "Inguinal Hernia": ["Direct", "Indirect", "Pantaloon"],
  "Recurrent Inguinal Hernia": ["Direct", "Indirect"],
  "Hiatal Hernia": ["Sliding (Type I)", "Paraesophageal (Type II)", "Mixed (Type III)", "Giant (Type IV)"],
  "Rectal Prolapse": ["Complete (Full-thickness)", "Mucosal", "Internal (Intussusception)"],
  "Hemorrhoids": ["Grade I", "Grade II", "Grade III", "Grade IV"],
  "Fistula-in-Ano": ["Intersphincteric", "Transsphincteric", "Suprasphincteric", "Extrasphincteric", "Horseshoe"],
  "Thyroid Nodule": ["Bethesda I", "Bethesda II", "Bethesda III", "Bethesda IV", "Bethesda V", "Bethesda VI"],
  "Diabetic Foot": ["Wagner 0", "Wagner 1", "Wagner 2", "Wagner 3", "Wagner 4", "Wagner 5"],
  "Gynecomastia": ["Unilateral", "Bilateral"],
  "Incisional Hernia": ["Midline", "Lateral", "Parastomal"],
  "Mirizzi Syndrome": ["Type I", "Type II", "Type III", "Type IV"],
  "Bile Duct Injury": ["Strasberg A", "Strasberg B", "Strasberg C", "Strasberg D", "Strasberg E1", "Strasberg E2", "Strasberg E3", "Strasberg E4", "Strasberg E5"],
  "CBD Stricture": ["Bismuth I", "Bismuth II", "Bismuth III", "Bismuth IV", "Bismuth V"],
  "IPMN": ["Branch Duct", "Main Duct", "Mixed"],
  "Chronic Pancreatitis": ["Calcific", "Non-calcific", "With Pseudocyst", "With Duct Dilatation"],
  "Esophageal Stricture": ["Upper Third", "Middle Third", "Lower Third"],
  "Achalasia Cardia": ["Type I", "Type II", "Type III (Spastic)"],
  "Pancreatic Fistula": ["Low Output (<200ml/day)", "High Output (>200ml/day)"],
};
const getSubtypes = (dx) => { for (const [k, v] of Object.entries(SUBTYPE_DX)) { if (dx && dx.includes(k)) return v; } return null; };

// Build flat benign dx list for the PreOp section
const ALL_BENIGN_DX = [];
Object.entries(BENIGN_CATEGORIES).forEach(([catKey, cat]) => {
  Object.keys(cat.diagnoses).forEach(dx => {
    ALL_BENIGN_DX.push({ dx, category: catKey, catLabel: cat.label, procedures: cat.diagnoses[dx] });
  });
});

const emptyPreOp = () => ({
  lesionType: "", // "benign" | "malignancy"
  // Benign
  primaryDx: "", primaryLaterality: "", primarySite: "", primarySubtype: "",
  ashClass: "", benignCategory: "",
  secondaryDx: "", secondaryLaterality: "", secondarySite: "",
  procedure: "", accessMode: "", accessOther: "",
  plan: "", // Curative / Palliative for malignancy
  // Malignancy
  malSite: "", preOpHistology: "", histologyOther: "", ihc: "",
  clinicalT: "", clinicalN: "", clinicalM: "",
});

const INDIA_STATES_DISTRICTS = {
  "Jammu and Kashmir": ["Srinagar","Anantnag","Baramulla","Budgam","Bandipora","Ganderbal","Kupwara","Pulwama","Shopian","Kulgam","Jammu","Kathua","Udhampur","Rajouri","Poonch","Doda","Kishtwar","Ramban","Reasi","Samba"],
  "Ladakh": ["Leh","Kargil"],
  "Himachal Pradesh": ["Shimla","Kangra","Mandi","Kullu","Solan","Una","Sirmaur","Bilaspur","Hamirpur","Chamba","Kinnaur","Lahaul and Spiti"],
  "Punjab": ["Ludhiana","Amritsar","Jalandhar","Patiala","Bathinda","Mohali","Pathankot","Hoshiarpur","Gurdaspur","Sangrur","Firozpur","Moga"],
  "Uttarakhand": ["Dehradun","Haridwar","Nainital","Udham Singh Nagar","Almora","Pauri Garhwal","Tehri Garhwal","Chamoli","Pithoragarh","Champawat","Bageshwar","Rudraprayag","Uttarkashi"],
  "Haryana": ["Gurugram","Faridabad","Panipat","Ambala","Karnal","Hisar","Rohtak","Sonipat","Panchkula"],
  "Delhi": ["Central","East","New Delhi","North","North East","North West","South","South East","South West","Shahdara","West"],
  "Rajasthan": ["Jaipur","Jodhpur","Udaipur","Kota","Bikaner","Ajmer","Alwar","Bhilwara","Sikar","Bharatpur"],
  "Uttar Pradesh": ["Lucknow","Kanpur","Agra","Varanasi","Meerut","Allahabad","Ghaziabad","Noida","Bareilly","Aligarh","Gorakhpur","Jhansi"],
  "Bihar": ["Patna","Gaya","Muzaffarpur","Bhagalpur","Darbhanga","Purnia","Begusarai"],
  "Madhya Pradesh": ["Bhopal","Indore","Jabalpur","Gwalior","Ujjain","Sagar","Dewas","Satna","Rewa"],
  "Chhattisgarh": ["Raipur","Bhilai","Bilaspur","Korba","Durg"],
  "Gujarat": ["Ahmedabad","Surat","Vadodara","Rajkot","Bhavnagar","Jamnagar","Gandhinagar"],
  "Maharashtra": ["Mumbai","Pune","Nagpur","Thane","Nashik","Aurangabad","Solapur","Kolhapur"],
  "Jharkhand": ["Ranchi","Jamshedpur","Dhanbad","Bokaro","Deoghar","Hazaribagh"],
  "Odisha": ["Bhubaneswar","Cuttack","Berhampur","Rourkela","Sambalpur","Puri"],
  "West Bengal": ["Kolkata","Howrah","Asansol","Siliguri","Durgapur","Bardhaman"],
  "Sikkim": ["Gangtok","Namchi","Gyalshing","Mangan"],
  "Assam": ["Guwahati","Silchar","Dibrugarh","Jorhat","Nagaon","Tinsukia","Tezpur"],
  "Meghalaya": ["Shillong","Tura","Jowai"],
  "Tripura": ["Agartala","Dharmanagar","Udaipur"],
  "Arunachal Pradesh": ["Itanagar","Naharlagun","Pasighat","Tawang"],
  "Manipur": ["Imphal","Bishnupur","Thoubal","Churachandpur"],
  "Mizoram": ["Aizawl","Lunglei","Champhai"],
  "Nagaland": ["Kohima","Dimapur","Mokokchung"],
  "Goa": ["North Goa","South Goa"],
  "Karnataka": ["Bengaluru","Mysuru","Mangaluru","Hubli-Dharwad","Belagavi"],
  "Kerala": ["Thiruvananthapuram","Kochi","Kozhikode","Thrissur","Kollam"],
  "Tamil Nadu": ["Chennai","Coimbatore","Madurai","Tiruchirappalli","Salem"],
  "Andhra Pradesh": ["Visakhapatnam","Vijayawada","Guntur","Tirupati","Kurnool"],
  "Telangana": ["Hyderabad","Warangal","Nizamabad","Karimnagar","Khammam"],
};
const INDIA_STATES = Object.keys(INDIA_STATES_DISTRICTS).sort();

const OCCUPATIONS = [
  "Government Employee", "Private Employee", "Self Employed / Business",
  "Farmer / Agriculture", "Labourer / Daily Wage", "Housewife / Homemaker",
  "Student", "Teacher / Professor", "Doctor / Healthcare Worker",
  "Engineer / IT Professional", "Lawyer / Legal", "Shopkeeper / Trader",
  "Driver / Transport", "Carpenter / Mason / Construction", "Tailor",
  "Army / Police / Paramilitary", "Retired / Pensioner", "Unemployed", "Other",
];

// Imaging: date + region + findings
const IMAGING_KEYS = ["usg", "ncct", "cect", "mri", "cemri", "mrcp", "ctAngio", "doppler", "petScan", "hidaScan", "bariumStudy", "defecography", "fistuloGram", "contrastStudy"];
const IMAGING_LABELS = { usg: "USG", ncct: "NCCT", cect: "CECT", mri: "MRI", cemri: "CEMRI", mrcp: "MRCP", ctAngio: "CT Angiography", doppler: "Doppler USG", petScan: "PET Scan", hidaScan: "HIDA Scan", bariumStudy: "Barium Study", defecography: "Defecography", fistuloGram: "Fistulogram", contrastStudy: "Contrast Study" };
// Endoscopy: date + findings (no region)
const ENDO_KEYS = ["ercp", "ugiEndoscopy", "colonoscopy", "proctosigmoidoscopy", "cystoscopy", "eus", "capsuleEndoscopy", "anorectalManometry"];
const ENDO_LABELS = { ercp: "ERCP", ugiEndoscopy: "UGI Endoscopy", colonoscopy: "Colonoscopy", proctosigmoidoscopy: "Proctosigmoidoscopy", cystoscopy: "Cystoscopy", eus: "EUS (Endoscopic Ultrasound)", capsuleEndoscopy: "Capsule Endoscopy", anorectalManometry: "Anorectal Manometry" };
// Pathology: date + site + findings
const PATHO_KEYS = ["fnac", "hpe", "trucut"];
const PATHO_LABELS = { fnac: "FNAC", hpe: "HPE", trucut: "Trucut Biopsy" };

const emptyClinical = () => ({
  // Section 1: Particulars
  name: "", age: "", sex: "", phone: "",
  mrd: "", state: "", district: "", occupation: "",
  height: "", weight: "", bloodGroup: "", comorbidities: [], comorbidOther: "",
  // Section 2: History
  chiefComplaints: [""], pastHistory: [""], prevSurgeries: [""], otherDetails: [""],
  // Section 2: Examination
  pulse: "", bp: "", spo2: "", pallor: "Absent", icterus: "Absent",
  chest: "", cvs: "", abdominalFindings: "", dre: "", otherExam: [""],
  // Section 3: Investigations — Haematology
  cbc: { done: false, date: "", hb: "", tlc: "", plt: "", esr: "", dlc: "", pcv: "", mcv: "", mch: "", mchc: "", rdw: "" },
  coagulation: { done: false, date: "", pt: "", inr: "", aptt: "", bt: "", ct: "", fibrinogen: "" },
  peripheralSmear: { done: false, date: "", findings: "" },
  reticulocyte: { done: false, date: "", count: "" },
  dimer: { done: false, date: "", value: "" },
  crossmatch: { done: false, date: "", bloodGroup: "", units: "" },
  // Section 3: Biochemistry
  lft: { done: false, date: "", tbil: "", dbil: "", ast: "", alt: "", alp: "", ggt: "", alb: "", tp: "", ag: "" },
  kft: { done: false, date: "", bun: "", creatinine: "", na: "", k: "", cl: "", ca: "", phosphate: "", uricAcid: "" },
  glucose: { done: false, date: "", fbs: "", ppbs: "", rbs: "", hba1c: "" },
  lipid: { done: false, date: "", tg: "", tchol: "", ldl: "", vldl: "", hdl: "" },
  pancreatic: { done: false, date: "", amylase: "", lipase: "", crp: "" },
  protein: { done: false, date: "", tp: "", alb: "", glob: "", ag: "" },
  // Section 3: Endocrine
  thyroid: { done: false, date: "", t3: "", t4: "", ft3: "", ft4: "", tsh: "" },
  cortisol: { done: false, date: "", morning: "", evening: "", acth: "" },
  parathyroid: { done: false, date: "", pth: "", vitD: "", ionizedCa: "" },
  insulin: { done: false, date: "", fasting: "", cpeptide: "" },
  // Section 3: Tumour Markers
  tumorMarkers: { done: false, date: "", cea: "", ca199: "", ca125: "", afp: "", ca153: "", psa: "", bhcg: "", calcitonin: "", chromograninA: "", ldh: "", s100: "" },
  // Section 3: Iron + Special
  iron: { done: false, date: "", siron: "", ferritin: "", transferrin: "", tibc: "" },
  vitB12Folate: { done: false, date: "", b12: "", folate: "" },
  // Section 3: Urine + Serology + ABG
  urineExam: { done: false, date: "", colour: "", albumin: "", sugar: "", micro: "", culture: "", bence: "" },
  serology: { done: false, date: "", hiv: "", hbsag: "", hcv: "", vdrl: "", widal: "", dengue: "", malarial: "" },
  abg: { done: false, date: "", ph: "", pco2: "", po2: "", hco3: "", lactate: "", be: "" },
  stoolExam: { done: false, date: "", occultBlood: "", microscopy: "", culture: "" },
  ascitic: { done: false, date: "", albumin: "", protein: "", cellCount: "", cytology: "", culture: "", saag: "" },
  pleural: { done: false, date: "", albumin: "", protein: "", ldh: "", cellCount: "", cytology: "", culture: "" },
  // Section 3: Imaging + Endoscopy (expandable cards)
  usg: { done: false, date: "", region: "", findings: "" },
  ncct: { done: false, date: "", region: "", findings: "" },
  cect: { done: false, date: "", region: "", findings: "" },
  mri: { done: false, date: "", region: "", findings: "" },
  cemri: { done: false, date: "", region: "", findings: "" },
  mrcp: { done: false, date: "", region: "", findings: "" },
  ctAngio: { done: false, date: "", region: "", findings: "" },
  doppler: { done: false, date: "", region: "", findings: "" },
  petScan: { done: false, date: "", region: "", findings: "" },
  hidaScan: { done: false, date: "", region: "", findings: "" },
  bariumStudy: { done: false, date: "", region: "", findings: "" },
  defecography: { done: false, date: "", findings: "" },
  fistuloGram: { done: false, date: "", region: "", findings: "" },
  contrastStudy: { done: false, date: "", region: "", findings: "" },
  ercp: { done: false, date: "", findings: "" },
  ugiEndoscopy: { done: false, date: "", findings: "" },
  colonoscopy: { done: false, date: "", findings: "" },
  proctosigmoidoscopy: { done: false, date: "", findings: "" },
  cystoscopy: { done: false, date: "", findings: "" },
  eus: { done: false, date: "", findings: "" },
  capsuleEndoscopy: { done: false, date: "", findings: "" },
  anorectalManometry: { done: false, date: "", findings: "" },
  fnac: { done: false, date: "", site: "", findings: "" },
  hpe: { done: false, date: "", site: "", findings: "" },
  trucut: { done: false, date: "", site: "", findings: "" },
  additionalInvestigations: [],
  // Section 4: PreOp Diagnosis
  preOp: emptyPreOp(),
  // Clinical form completed flag
  clinicalDone: false,
  // Surgery listing
  surgeryListDate: "", theater: "", listStatus: "",
  // Tracking
  clinicalBy: "", clinicalById: "",
});

// ─── Scheduling Helpers ──────────────────────────────────────

function getNextAdmDates(day, n = 12) {
  const dates = []; const d = new Date(); d.setHours(0, 0, 0, 0);
  while (d.getDay() !== day) d.setDate(d.getDate() + 1);
  const today = new Date(); today.setHours(0, 0, 0, 0);
  if (d < today) d.setDate(d.getDate() + 7);
  for (let i = 0; i < n; i++) { dates.push(new Date(d)); d.setDate(d.getDate() + 7); }
  return dates;
}
function fmt(d) { const y = d.getFullYear(), m = String(d.getMonth()+1).padStart(2,"0"), dd = String(d.getDate()).padStart(2,"0"); return `${y}-${m}-${dd}`; }
function fmtD(s) { return new Date(s + "T00:00:00").toLocaleDateString("en-IN", { weekday: "short", day: "numeric", month: "short", year: "numeric" }); }
function fmtDT(iso) { if (!iso) return "—"; const d = new Date(iso); return d.toLocaleDateString("en-IN", { weekday: "short", day: "numeric", month: "short", year: "numeric" }); }
function slotsUsed(pts, ds, cat) { return pts.filter(p => p.surgeryDate === ds && p.benignCategory === cat && p.type === "benign").length; }
function findDate(pts, day, cat, slots) {
  for (const d of getNextAdmDates(day, 24)) { const ds = fmt(d); if (slotsUsed(pts, ds, cat) < slots[cat]) return ds; }
  return fmt(getNextAdmDates(day, 1)[0]);
}

// ─── UI Helpers ──────────────────────────────────────────────

function SearchSelect({ options, value, onChange, placeholder, label, req, clearable }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const ref = useRef(null);
  const [pos, setPos] = useState({ top: 0, left: 0, width: 0, openUp: false });
  const fil = options.filter(o => o.toLowerCase().includes(q.toLowerCase()));
  const isMob = typeof window !== "undefined" && window.innerWidth < 768;
  const doOpen = () => {
    if (ref.current) {
      const r = ref.current.getBoundingClientRect();
      const spaceBelow = window.innerHeight - r.bottom;
      const openUp = spaceBelow < 260 && r.top > 260;
      setPos({ top: openUp ? r.top - 4 : r.bottom + 4, left: r.left, width: r.width, openUp });
    }
    setOpen(!open); setQ("");
  };
  const doSelect = (o) => { onChange(o); setOpen(false); setQ(""); };
  const list = (
    <>
      {fil.map(o => (
        <div key={o} onClick={() => doSelect(o)}
          style={{ padding: isMob ? "12px 16px" : "9px 14px", cursor: "pointer", fontSize: isMob ? "0.92rem" : "0.84rem", fontFamily: "'Outfit',sans-serif", color: o === "Other (Enter Manually)" ? "#1565c0" : "#1e293b", background: o === value ? "#e8f5e9" : "transparent", borderBottom: "1px solid #f1f5f9", fontWeight: o === value ? 600 : (o === "Other (Enter Manually)" ? 600 : 400), fontStyle: o === "Other (Enter Manually)" ? "italic" : "normal" }}>{o}</div>
      ))}
      {fil.length === 0 && <div style={{ padding: "12px", color: "#94a3b8", fontSize: "0.84rem" }}>No matches</div>}
    </>
  );
  return (
    <div style={{ position: "relative" }} ref={ref}>
      {label && <label style={S.label}>{label}{req && <span style={{ color: "#c62828" }}> *</span>}</label>}
      <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
        <div onClick={doOpen} style={{ ...S.input, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "space-between", background: value ? "#fff" : "#f8fafc", flex: 1 }}>
          <span style={{ color: value ? "#1e293b" : "#94a3b8", fontSize: "0.87rem", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}>{value || placeholder}</span>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.5"><polyline points="6 9 12 15 18 9" /></svg>
        </div>
        {clearable && value && <button onClick={() => onChange("")} style={{ border: "1px solid #e2e8f0", borderRadius: 6, background: "#fff", padding: "6px 8px", cursor: "pointer", fontSize: "0.72rem", color: "#c62828", fontFamily: "'Outfit',sans-serif", flexShrink: 0 }} title="Clear">✕</button>}
      </div>
      {open && isMob && (
        <>
          <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", zIndex: 9990 }} onClick={() => { setOpen(false); setQ(""); }} />
          <div style={{ position: "fixed", left: 0, right: 0, bottom: 0, maxHeight: "75vh", background: "#fff", borderRadius: "16px 16px 0 0", boxShadow: "0 -10px 40px rgba(0,0,0,0.2)", zIndex: 9991, display: "flex", flexDirection: "column" }}>
            <div style={{ padding: "12px 16px 8px", borderBottom: "1px solid #e2e8f0" }}>
              <div style={{ width: 36, height: 4, borderRadius: 2, background: "#cbd5e1", margin: "0 auto 10px" }} />
              <input autoFocus placeholder="Type to search..." value={q} onChange={e => setQ(e.target.value)} onClick={e => e.stopPropagation()} style={{ width: "100%", padding: "10px 14px", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.92rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" }} />
            </div>
            <div style={{ flex: 1, overflowY: "auto", WebkitOverflowScrolling: "touch" }}>{list}</div>
          </div>
        </>
      )}
      {open && !isMob && (
        <>
          <div style={{ position: "fixed", inset: 0, zIndex: 9990 }} onClick={() => { setOpen(false); setQ(""); }} />
          <div style={{ position: "fixed", top: pos.openUp ? undefined : pos.top, bottom: pos.openUp ? (window.innerHeight - pos.top) : undefined, left: pos.left, width: pos.width, background: "#fff", border: "1.5px solid #e2e8f0", borderRadius: 10, boxShadow: "0 10px 30px rgba(0,0,0,0.15)", zIndex: 9991 }}>
            <div style={{ padding: "8px 8px 4px" }}>
              <input autoFocus placeholder="Type to search..." value={q} onChange={e => setQ(e.target.value)} onClick={e => e.stopPropagation()} style={{ ...S.input, marginBottom: 0, fontSize: "0.84rem", padding: "8px 12px" }} />
            </div>
            <div style={{ maxHeight: 220, overflowY: "auto" }}>{list}</div>
          </div>
        </>
      )}
    </div>
  );
}

function Bdg({ children, bg, color, border }) { return <span style={{ display: "inline-block", padding: "2px 9px", borderRadius: 20, fontSize: "0.67rem", fontWeight: 700, letterSpacing: "0.04em", backgroundColor: bg, color, border: `1px solid ${border}`, textTransform: "uppercase", fontFamily: "'Outfit',sans-serif" }}>{children}</span>; }

function CollapseSection({ title, icon, open, onToggle, color = "#1565c0", children }) {
  return (
    <div style={{ marginBottom: 12, border: "1px solid #e2e8f0", borderRadius: 10 }}>
      <button onClick={onToggle} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 14px", background: open ? color + "08" : "#f8fafc", border: "none", cursor: "pointer", fontFamily: "'Outfit',sans-serif", borderRadius: open ? "10px 10px 0 0" : 10 }}>
        <span style={{ fontWeight: 700, fontSize: "0.82rem", color }}>{icon} {title}</span>
        <span style={{ fontSize: "0.8rem", color: "#94a3b8", transform: open ? "rotate(180deg)" : "none", transition: "0.2s" }}>▼</span>
      </button>
      {open && <div style={{ padding: "12px 14px", borderTop: "1px solid #e2e8f0" }}>{children}</div>}
    </div>
  );
}

function LabCard({ label, fields, data, onChange, color = "#6a1b9a" }) {
  const d = data || { done: false, date: "" };
  const hasData = d.done || fields.some(f => d[f.key]);
  const toggle = () => onChange({ ...d, done: !d.done });
  const inp = { width: "100%", padding: "5px 7px", border: "1px solid #e2e8f0", borderRadius: 6, fontSize: "0.78rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" };
  return (
    <div style={{ marginBottom: 5, borderRadius: 8, border: `1.5px solid ${hasData || d.done ? color : "#e2e8f0"}`, overflow: "hidden", background: hasData || d.done ? color + "08" : "#fff" }}>
      <button onClick={toggle} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "7px 10px", border: "none", background: "transparent", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontSize: "0.76rem", fontWeight: 600, color: hasData || d.done ? color : "#94a3b8", textAlign: "left" }}>
        <span style={{ width: 18, height: 18, borderRadius: 4, border: `2px solid ${hasData || d.done ? color : "#cbd5e1"}`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "0.65rem", color: "#fff", background: hasData || d.done ? color : "transparent", flexShrink: 0 }}>{hasData || d.done ? "✓" : ""}</span>
        {label}
        {d.date && <span style={{ fontSize: "0.6rem", color: "#94a3b8", fontWeight: 400, marginLeft: "auto" }}>{d.date}</span>}
      </button>
      {(d.done || hasData) && <div style={{ padding: "0 10px 8px" }}>
        <div style={{ marginBottom: 6 }}>
          <label style={{ fontSize: "0.58rem", color: "#94a3b8", fontWeight: 600, textTransform: "uppercase" }}>Date</label>
          <input type="date" value={d.date || ""} onChange={e => onChange({ ...d, date: e.target.value })} style={{ ...inp, maxWidth: 160, fontSize: "0.74rem" }} />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${Math.min(fields.length, 5)}, 1fr)`, gap: 5 }}>
          {fields.map(f => (
            <div key={f.key}>
              <label style={{ fontSize: "0.58rem", color: "#94a3b8", fontWeight: 600, textTransform: "uppercase" }}>{f.label}</label>
              <input value={d[f.key] || ""} onChange={e => onChange({ ...d, [f.key]: e.target.value })} placeholder="—" style={inp} />
            </div>
          ))}
        </div>
      </div>}
    </div>
  );
}

function MultiInput({ label, values, onChange, max = 3 }) {
  const add = () => { if (values.length < max) onChange([...values, ""]); };
  return (
    <div style={{ marginBottom: 10 }}>
      <label style={{ fontSize: "0.72rem", fontWeight: 600, color: "#475569", textTransform: "uppercase", letterSpacing: "0.04em" }}>{label}</label>
      {values.map((v, i) => (
        <div key={i} style={{ display: "flex", gap: 6, marginTop: 4 }}>
          <input value={v} onChange={e => { const n = [...values]; n[i] = e.target.value; onChange(n); }} style={{ flex: 1, padding: "6px 10px", border: "1px solid #e2e8f0", borderRadius: 7, fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif" }} placeholder={`${label} ${i + 1}`} />
          {values.length > 1 && <button onClick={() => onChange(values.filter((_, j) => j !== i))} style={{ border: "none", background: "none", cursor: "pointer", color: "#c62828", fontSize: "0.82rem" }}>✕</button>}
        </div>
      ))}
      {values.length < max && <button onClick={add} style={{ marginTop: 4, border: "none", background: "none", cursor: "pointer", fontSize: "0.72rem", color: "#1565c0", fontFamily: "'Outfit',sans-serif", fontWeight: 600 }}>+ Add another</button>}
    </div>
  );
}

// ─── Photo/File Upload Component ─────────────────────────────
function PhotoUpload({ photos, onChange, label, maxPhotos = 10, accept = "image/jpeg,image/png,image/webp" }) {
  const handleAdd = (e) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;
    const current = photos || [];
    const remaining = maxPhotos - current.length;
    files.slice(0, remaining).forEach(file => {
      if (file.size > 2000000) return; // 2MB max per file
      const reader = new FileReader();
      reader.onload = () => {
        onChange([...current, { data: reader.result, name: file.name, date: new Date().toISOString().slice(0,10), caption: "" }]);
      };
      reader.readAsDataURL(file);
    });
    e.target.value = "";
  };
  const remove = (i) => onChange((photos || []).filter((_, j) => j !== i));
  const updateCaption = (i, cap) => { const n = [...(photos || [])]; n[i] = { ...n[i], caption: cap }; onChange(n); };
  const arr = photos || [];
  return (
    <div style={{ marginTop: 8 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
        <label style={{ fontSize: "0.66rem", fontWeight: 600, color: "#475569", textTransform: "uppercase", letterSpacing: "0.04em" }}>{label || "Photos"} ({arr.length}/{maxPhotos})</label>
        {arr.length < maxPhotos && <label style={{ padding: "3px 10px", borderRadius: 6, border: "1px solid #90caf9", background: "#e3f2fd", fontSize: "0.68rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>
          {"📷"} Add
          <input type="file" accept={accept} multiple onChange={handleAdd} style={{ display: "none" }} />
        </label>}
      </div>
      {arr.length > 0 && <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))", gap: 8 }}>
        {arr.map((p, i) => (
          <div key={i} style={{ position: "relative", borderRadius: 8, border: "1px solid #e2e8f0", overflow: "hidden", background: "#f8fafc" }}>
            {p.data.startsWith("data:image") ? (
              <img src={p.data} alt={p.caption || p.name} style={{ width: "100%", height: 90, objectFit: "cover", display: "block" }} />
            ) : (
              <div style={{ width: "100%", height: 90, display: "flex", alignItems: "center", justifyContent: "center", background: "#fef2f2", fontSize: "0.7rem", color: "#c62828", fontWeight: 600 }}>{"📄"} PDF</div>
            )}
            <input value={p.caption || ""} onChange={e => updateCaption(i, e.target.value)} placeholder="Caption..." style={{ width: "100%", border: "none", borderTop: "1px solid #e2e8f0", padding: "4px 6px", fontSize: "0.64rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box", outline: "none" }} />
            <button onClick={() => remove(i)} style={{ position: "absolute", top: 2, right: 2, width: 18, height: 18, borderRadius: "50%", border: "none", background: "rgba(198,40,40,0.85)", color: "#fff", fontSize: "0.6rem", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>✕</button>
          </div>
        ))}
      </div>}
    </div>
  );
}

function ClinicalForm({ patient, onSave, onCancel, repo }) {
  const cl = patient.clinical || emptyClinical();
  const [c, setC] = useState({ ...emptyClinical(), ...cl, name: cl.name || patient.name, age: cl.age || patient.age, sex: cl.sex || patient.sex, phone: cl.phone || patient.phone, preOp: { ...emptyPreOp(), ...(cl.preOp || {}), lesionType: cl.preOp?.lesionType || patient.type || "", malSite: cl.preOp?.malSite || patient.malignancySite || "", primaryDx: cl.preOp?.primaryDx || patient.diagnosis || "", procedure: cl.preOp?.procedure || patient.plannedProcedure || "", plan: cl.preOp?.plan || patient.malignancyPlan || "", benignCategory: cl.preOp?.benignCategory || patient.benignCategory || "" } });
  const [sec, setSec] = useState({ s1: true, s2: false, s3: false, s4: false });
  const p = c.preOp;
  const setP = (u) => setC({ ...c, preOp: { ...p, ...u } });
  const bmi = c.height && c.weight ? (parseFloat(c.weight) / ((parseFloat(c.height) / 100) ** 2)).toFixed(1) : "";
  const inp = { width: "100%", padding: "7px 10px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" };
  const lbl = { display: "block", fontSize: "0.68rem", fontWeight: 600, color: "#475569", marginBottom: 3, textTransform: "uppercase", letterSpacing: "0.04em" };
  const g2 = { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 10 };
  const g3 = { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 };
  const chip = (sel, clr) => ({ padding: "4px 10px", borderRadius: 16, border: `1.5px solid ${sel ? clr : "#e2e8f0"}`, background: sel ? clr + "12" : "#fff", cursor: "pointer", fontSize: "0.72rem", fontFamily: "'Outfit',sans-serif", fontWeight: sel ? 600 : 400, color: sel ? clr : "#94a3b8" });
  const [formWarnings, setFormWarnings] = useState(null);
  const doSave = () => {
    const emptySections = [];
    const missingFields = [];
    // Key fields — always warn individually
    if (!c.mrd) missingFields.push("MRD Number");
    const primaryDx = p.lesionType === "malignancy" ? p.malSite : p.primaryDx;
    if (!primaryDx) missingFields.push("Primary Diagnosis");
    if (!p.procedure) missingFields.push("Primary Procedure");
    // Section 1: Particulars — check if ANY field filled
    const hasParticulars = c.mrd || c.bloodGroup || c.state || c.district || c.occupation || c.height || c.weight || (c.comorbidities || []).length > 0;
    if (!hasParticulars) emptySections.push("Particulars (MRD, Blood Group, Address, etc.)");
    // Section 2: Clinical Details — check if ANY field filled
    const hasClinical = (c.chiefComplaints || []).filter(Boolean).length > 0 || c.pulse || c.bp || c.spo2 || c.abdominalFindings || c.dre || c.chest || c.cvs || (c.pastHistory || []).filter(Boolean).length > 0 || (c.prevSurgeries || []).filter(Boolean).length > 0;
    if (!hasClinical) emptySections.push("Clinical Details (Complaints, Vitals, Examination)");
    // Section 3: Investigations — check if ANY investigation is done
    const invKeys = ["cbc","coagulation","peripheralSmear","reticulocyte","dimer","crossmatch","lft","kft","glucose","lipid","pancreatic","protein","thyroid","cortisol","parathyroid","insulin","tumorMarkers","iron","vitB12Folate","urineExam","serology","abg","stoolExam","ascitic","pleural","usg","ncct","cect","mri","cemri","mrcp","ctAngio","doppler","petScan","hidaScan","bariumStudy","defecography","fistuloGram","contrastStudy","ercp","ugiEndoscopy","colonoscopy","proctosigmoidoscopy","cystoscopy","eus","capsuleEndoscopy","anorectalManometry","fnac","hpe","trucut"];
    const hasInvestigations = invKeys.some(k => c[k]?.done) || (c.additionalInvestigations || []).length > 0;
    if (!hasInvestigations) emptySections.push("Investigations (Lab work, Imaging, Endoscopy)");
    // Section 4: Pre-Op Diagnosis
    const hasPreOp = p.lesionType || p.primaryDx || p.malSite || p.procedure;
    if (!hasPreOp) emptySections.push("Pre-Operative Diagnosis");
    if (missingFields.length > 0 || emptySections.length > 0) {
      setFormWarnings({ missingFields, emptySections, onProceed: () => { setFormWarnings(null); doSaveConfirmed(); } });
      return;
    }
    doSaveConfirmed();
  };
  const doSaveConfirmed = () => {
    onSave({ ...c, clinicalDone: true }, { name: c.name, age: c.age, sex: c.sex, phone: c.phone, diagnosis: p.lesionType === "malignancy" ? ((p.preOpHistology === "Others" ? p.histologyOther : p.preOpHistology) || "") + " " + (p.malSite || "") : p.primaryDx, plannedProcedure: p.procedure, malignancyPlan: p.plan, type: p.lesionType || patient.type, benignCategory: p.benignCategory || patient.benignCategory });
  };

  // Procedure options for current diagnosis
  const getProcedures = () => {
    let procs = [];
    if (p.lesionType === "benign" && p.primaryDx) {
      const found = repo.allBenignDx.find(d => d.dx === p.primaryDx);
      const cat = found?.category || p.benignCategory || "";
      // Get ALL procedures from the entire category (not just this diagnosis)
      if (cat && repo.benignCats && repo.benignCats[cat]) {
        const allCatProcs = [];
        Object.values(repo.benignCats[cat].diagnoses || {}).forEach(dxProcs => {
          dxProcs.forEach(pr => { if (!allCatProcs.includes(pr)) allCatProcs.push(pr); });
        });
        procs = allCatProcs;
      } else if (found) {
        procs = [...found.procedures];
      }
      // Also add standalone procedures mapped to same category
      if (cat && repo.customRepo) {
        const catProcs = (repo.customRepo.opProcs || []).filter(proc => (repo.customRepo.procCategories || {})[proc] === cat);
        procs = [...new Set([...procs, ...catProcs])];
      }
    }
    if (p.lesionType === "malignancy" && p.malSite && repo.maligSites[p.malSite]) {
      procs = [...repo.maligSites[p.malSite].procedures];
    }
    return procs;
  };

  return (
    <div style={{ maxWidth: 740, margin: "0 auto" }}>

      {/* Section 1: Patient Particulars */}
      <CollapseSection title="Patient Particulars" icon="👤" open={sec.s1} onToggle={() => setSec({ ...sec, s1: !sec.s1 })} color="#2e7d32">
        <div style={g2}>
          <div><label style={lbl}>Name</label><input style={inp} value={c.name} onChange={e => setC({ ...c, name: e.target.value })} /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6 }}>
            <div><label style={lbl}>Age</label><input style={inp} type="number" value={c.age} onChange={e => setC({ ...c, age: e.target.value })} /></div>
            <div><label style={lbl}>Sex</label><select style={inp} value={c.sex} onChange={e => setC({ ...c, sex: e.target.value })}><option value="">-</option><option>Male</option><option>Female</option><option>Other</option></select></div>
            <div><label style={lbl}>Blood Gp</label><select style={inp} value={c.bloodGroup} onChange={e => setC({ ...c, bloodGroup: e.target.value })}><option value="">-</option>{BLOOD_GROUPS.map(b => <option key={b}>{b}</option>)}</select></div>
          </div>
          <div><label style={lbl}>Phone</label><input style={inp} value={c.phone} onChange={e => setC({ ...c, phone: e.target.value })} /></div>
          <div><label style={lbl}>MRD No.</label><input style={inp} value={c.mrd} onChange={e => setC({ ...c, mrd: e.target.value })} /></div>
          <div><label style={lbl}>State</label><select style={inp} value={c.state} onChange={e => setC({ ...c, state: e.target.value, district: "" })}><option value="">Select State...</option>{INDIA_STATES.map(s => <option key={s}>{s}</option>)}</select></div>
          <div><label style={lbl}>District</label><select style={inp} value={c.district} onChange={e => setC({ ...c, district: e.target.value })}><option value="">Select District...</option>{(INDIA_STATES_DISTRICTS[c.state] || []).map(d => <option key={d}>{d}</option>)}</select></div>
        </div>
        <div style={{ ...g2, marginTop: 10 }}>
          <div><label style={lbl}>Occupation</label><select style={inp} value={c.occupation} onChange={e => setC({ ...c, occupation: e.target.value })}><option value="">Select...</option>{OCCUPATIONS.map(o => <option key={o}>{o}</option>)}</select>
            {c.occupation === "Other" && <input style={{ ...inp, marginTop: 4, borderColor: "#2e7d32" }} value={c.occupationOther || ""} onChange={e => setC({ ...c, occupationOther: e.target.value })} placeholder="Specify occupation..." />}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6 }}>
            <div><label style={lbl}>Ht (cm)</label><input style={inp} type="number" value={c.height} onChange={e => setC({ ...c, height: e.target.value })} /></div>
            <div><label style={lbl}>Wt (kg)</label><input style={inp} type="number" value={c.weight} onChange={e => setC({ ...c, weight: e.target.value })} /></div>
            <div><label style={lbl}>BMI</label><div style={{ ...inp, background: "#f0fdf4", color: bmi ? (parseFloat(bmi) >= 30 ? "#c62828" : "#2e7d32") : "#94a3b8", fontWeight: 600 }}>{bmi || "—"}</div></div>
          </div>
        </div>
        <div style={{ marginTop: 10 }}>
          <label style={lbl}>Comorbidities</label>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginBottom: 4 }}>
            {COMORBIDITIES.map(cm => <button key={cm} onClick={() => setC({ ...c, comorbidities: c.comorbidities.includes(cm) ? c.comorbidities.filter(x => x !== cm) : [...c.comorbidities, cm] })}
              style={chip(c.comorbidities.includes(cm), "#2e7d32")}>{cm}</button>)}
          </div>
          <input style={{ ...inp, marginTop: 2 }} placeholder="Other comorbidities..." value={c.comorbidOther} onChange={e => setC({ ...c, comorbidOther: e.target.value })} />
        </div>
        <div style={{ ...g2, marginTop: 10 }}>
          <div><label style={lbl}>PAC Cleared On</label><input type="date" style={inp} value={c.pacClearedDate || ""} onChange={e => setC({ ...c, pacClearedDate: e.target.value })} /></div>
        </div>
      </CollapseSection>

      {/* Section 2: Clinical Details */}
      <CollapseSection title="Clinical Details" icon="📝" open={sec.s2} onToggle={() => setSec({ ...sec, s2: !sec.s2 })} color="#c62828">
        <MultiInput label="Chief Complaints" values={c.chiefComplaints} onChange={v => setC({ ...c, chiefComplaints: v })} />
        <MultiInput label="Past History" values={c.pastHistory} onChange={v => setC({ ...c, pastHistory: v })} />
        <MultiInput label="Previous Surgeries" values={c.prevSurgeries} onChange={v => setC({ ...c, prevSurgeries: v })} />
        <MultiInput label="Other Details" values={c.otherDetails} onChange={v => setC({ ...c, otherDetails: v })} />
        <hr style={{ border: "none", borderTop: "1px solid #e2e8f0", margin: "14px 0" }} />
        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#c62828", marginBottom: 8 }}>Examination</div>
        <div style={g3}>
          <div><label style={lbl}>Pulse</label><input style={inp} value={c.pulse} onChange={e => setC({ ...c, pulse: e.target.value })} placeholder="/min" /></div>
          <div><label style={lbl}>BP</label><input style={inp} value={c.bp} onChange={e => setC({ ...c, bp: e.target.value })} placeholder="mmHg" /></div>
          <div><label style={lbl}>SpO2</label><input style={inp} value={c.spo2} onChange={e => setC({ ...c, spo2: e.target.value })} placeholder="%" /></div>
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Pallor</label><select style={inp} value={c.pallor} onChange={e => setC({ ...c, pallor: e.target.value })}>{PALLOR_ICTERUS.map(v => <option key={v}>{v}</option>)}</select></div>
          <div><label style={lbl}>Icterus</label><select style={inp} value={c.icterus} onChange={e => setC({ ...c, icterus: e.target.value })}>{PALLOR_ICTERUS.map(v => <option key={v}>{v}</option>)}</select></div>
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Chest</label><input style={inp} value={c.chest} onChange={e => setC({ ...c, chest: e.target.value })} /></div>
          <div><label style={lbl}>CVS</label><input style={inp} value={c.cvs} onChange={e => setC({ ...c, cvs: e.target.value })} /></div>
        </div>
        <div style={{ marginTop: 8 }}><label style={lbl}>Abdominal Findings</label><textarea style={{ ...inp, minHeight: 45, resize: "vertical" }} value={c.abdominalFindings} onChange={e => setC({ ...c, abdominalFindings: e.target.value })} /></div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>DRE</label><input style={inp} value={c.dre} onChange={e => setC({ ...c, dre: e.target.value })} /></div>
        </div>
        <div style={{ marginTop: 8 }}>
          <MultiInput label="Other Examinations" values={Array.isArray(c.otherExam) ? c.otherExam : (c.otherExam ? [c.otherExam] : [""])} onChange={v => setC({ ...c, otherExam: v })} max={6} />
        </div>
      </CollapseSection>

      {/* Section 3: Investigations */}
      <CollapseSection title="Investigations" icon="🔬" open={sec.s3} onToggle={() => setSec({ ...sec, s3: !sec.s3 })} color="#6a1b9a">
        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#c62828", marginBottom: 8 }}>Haematology</div>
        <LabCard label="CBC" color="#c62828" data={c.cbc} onChange={v => setC({ ...c, cbc: { ...v, done: true } })} fields={[{ key: "hb", label: "Hb" }, { key: "tlc", label: "TLC" }, { key: "plt", label: "PLT" }, { key: "esr", label: "ESR" }, { key: "dlc", label: "DLC" }, { key: "pcv", label: "PCV" }, { key: "mcv", label: "MCV" }, { key: "mch", label: "MCH" }, { key: "mchc", label: "MCHC" }, { key: "rdw", label: "RDW" }]} />
        <LabCard label="Coagulation" color="#c62828" data={c.coagulation} onChange={v => setC({ ...c, coagulation: { ...v, done: true } })} fields={[{ key: "pt", label: "PT" }, { key: "inr", label: "INR" }, { key: "aptt", label: "aPTT" }, { key: "bt", label: "BT" }, { key: "ct", label: "CT" }, { key: "fibrinogen", label: "Fibrinogen" }]} />
        <LabCard label="Peripheral Smear" color="#c62828" data={c.peripheralSmear} onChange={v => setC({ ...c, peripheralSmear: { ...v, done: true } })} fields={[{ key: "findings", label: "Findings" }]} />
        <LabCard label="Reticulocyte Count" color="#c62828" data={c.reticulocyte} onChange={v => setC({ ...c, reticulocyte: { ...v, done: true } })} fields={[{ key: "count", label: "Count (%)" }]} />
        <LabCard label="D-Dimer" color="#c62828" data={c.dimer} onChange={v => setC({ ...c, dimer: { ...v, done: true } })} fields={[{ key: "value", label: "Value" }]} />
        <LabCard label="Cross Match / Blood Reserve" color="#c62828" data={c.crossmatch} onChange={v => setC({ ...c, crossmatch: { ...v, done: true } })} fields={[{ key: "bloodGroup", label: "Group" }, { key: "units", label: "Units" }]} />

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#1565c0", marginBottom: 8, marginTop: 12 }}>Biochemistry</div>
        <LabCard label="LFT" color="#1565c0" data={c.lft} onChange={v => setC({ ...c, lft: { ...v, done: true } })} fields={[{ key: "tbil", label: "T.Bil" }, { key: "dbil", label: "D.Bil" }, { key: "ast", label: "AST" }, { key: "alt", label: "ALT" }, { key: "alp", label: "ALP" }, { key: "ggt", label: "GGT" }, { key: "alb", label: "Alb" }, { key: "tp", label: "T.Prot" }, { key: "ag", label: "A/G" }]} />
        <LabCard label="KFT / Electrolytes" color="#1565c0" data={c.kft} onChange={v => setC({ ...c, kft: { ...v, done: true } })} fields={[{ key: "bun", label: "BUN" }, { key: "creatinine", label: "Creat" }, { key: "na", label: "Na+" }, { key: "k", label: "K+" }, { key: "cl", label: "Cl-" }, { key: "ca", label: "Ca" }, { key: "phosphate", label: "PO4" }, { key: "uricAcid", label: "Uric Acid" }]} />
        <LabCard label="Blood Sugar" color="#1565c0" data={c.glucose} onChange={v => setC({ ...c, glucose: { ...v, done: true } })} fields={[{ key: "fbs", label: "FBS" }, { key: "ppbs", label: "PPBS" }, { key: "rbs", label: "RBS" }, { key: "hba1c", label: "HbA1c" }]} />
        <LabCard label="Lipid Profile" color="#1565c0" data={c.lipid} onChange={v => setC({ ...c, lipid: { ...v, done: true } })} fields={[{ key: "tg", label: "TG" }, { key: "tchol", label: "T.Chol" }, { key: "ldl", label: "LDL" }, { key: "vldl", label: "VLDL" }, { key: "hdl", label: "HDL" }]} />
        <LabCard label="Pancreatic Enzymes" color="#1565c0" data={c.pancreatic} onChange={v => setC({ ...c, pancreatic: { ...v, done: true } })} fields={[{ key: "amylase", label: "Amylase" }, { key: "lipase", label: "Lipase" }, { key: "crp", label: "CRP" }]} />
        <LabCard label="ABG" color="#1565c0" data={c.abg} onChange={v => setC({ ...c, abg: { ...v, done: true } })} fields={[{ key: "ph", label: "pH" }, { key: "pco2", label: "pCO2" }, { key: "po2", label: "pO2" }, { key: "hco3", label: "HCO3" }, { key: "lactate", label: "Lactate" }, { key: "be", label: "BE" }]} />

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#2e7d32", marginBottom: 8, marginTop: 12 }}>Endocrine</div>
        <LabCard label="Thyroid Function" color="#2e7d32" data={c.thyroid} onChange={v => setC({ ...c, thyroid: { ...v, done: true } })} fields={[{ key: "t3", label: "T3" }, { key: "t4", label: "T4" }, { key: "ft3", label: "fT3" }, { key: "ft4", label: "fT4" }, { key: "tsh", label: "TSH" }]} />
        <LabCard label="Cortisol / Adrenal" color="#2e7d32" data={c.cortisol} onChange={v => setC({ ...c, cortisol: { ...v, done: true } })} fields={[{ key: "morning", label: "AM Cortisol" }, { key: "evening", label: "PM Cortisol" }, { key: "acth", label: "ACTH" }]} />
        <LabCard label="Parathyroid / Calcium" color="#2e7d32" data={c.parathyroid} onChange={v => setC({ ...c, parathyroid: { ...v, done: true } })} fields={[{ key: "pth", label: "PTH" }, { key: "vitD", label: "Vit D" }, { key: "ionizedCa", label: "Ionized Ca" }]} />
        <LabCard label="Insulin / C-Peptide" color="#2e7d32" data={c.insulin} onChange={v => setC({ ...c, insulin: { ...v, done: true } })} fields={[{ key: "fasting", label: "Fasting Insulin" }, { key: "cpeptide", label: "C-Peptide" }]} />

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#e65100", marginBottom: 8, marginTop: 12 }}>Tumour Markers</div>
        <LabCard label="Tumour Markers" color="#e65100" data={c.tumorMarkers} onChange={v => setC({ ...c, tumorMarkers: { ...v, done: true } })} fields={[{ key: "cea", label: "CEA" }, { key: "ca199", label: "CA19-9" }, { key: "ca125", label: "CA-125" }, { key: "ca153", label: "CA15-3" }, { key: "afp", label: "AFP" }, { key: "psa", label: "PSA" }, { key: "bhcg", label: "β-hCG" }, { key: "calcitonin", label: "Calcitonin" }, { key: "chromograninA", label: "CgA" }, { key: "ldh", label: "LDH" }, { key: "s100", label: "S-100" }]} />

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#6a1b9a", marginBottom: 8, marginTop: 12 }}>Iron / Vitamins</div>
        <LabCard label="Iron Profile" color="#6a1b9a" data={c.iron} onChange={v => setC({ ...c, iron: { ...v, done: true } })} fields={[{ key: "siron", label: "S.Iron" }, { key: "ferritin", label: "Ferritin" }, { key: "transferrin", label: "Transferrin" }, { key: "tibc", label: "TIBC" }]} />
        <LabCard label="Vit B12 / Folate" color="#6a1b9a" data={c.vitB12Folate} onChange={v => setC({ ...c, vitB12Folate: { ...v, done: true } })} fields={[{ key: "b12", label: "Vit B12" }, { key: "folate", label: "Folate" }]} />

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#00695c", marginBottom: 8, marginTop: 12 }}>Urine / Stool / Serology</div>
        <LabCard label="Urine Examination" color="#00695c" data={c.urineExam} onChange={v => setC({ ...c, urineExam: { ...v, done: true } })} fields={[{ key: "colour", label: "Colour" }, { key: "albumin", label: "Albumin" }, { key: "sugar", label: "Sugar" }, { key: "micro", label: "Microscopy" }, { key: "culture", label: "Culture" }, { key: "bence", label: "Bence Jones" }]} />
        <LabCard label="Stool Examination" color="#00695c" data={c.stoolExam} onChange={v => setC({ ...c, stoolExam: { ...v, done: true } })} fields={[{ key: "occultBlood", label: "Occult Blood" }, { key: "microscopy", label: "Microscopy" }, { key: "culture", label: "Culture" }]} />
        <LabCard label="Serology" color="#00695c" data={c.serology} onChange={v => setC({ ...c, serology: { ...v, done: true } })} fields={[{ key: "hiv", label: "HIV" }, { key: "hbsag", label: "HBsAg" }, { key: "hcv", label: "HCV" }, { key: "vdrl", label: "VDRL" }, { key: "widal", label: "Widal" }, { key: "dengue", label: "Dengue" }, { key: "malarial", label: "MP" }]} />

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#4527a0", marginBottom: 8, marginTop: 12 }}>Fluid Analysis</div>
        <LabCard label="Ascitic Fluid" color="#4527a0" data={c.ascitic} onChange={v => setC({ ...c, ascitic: { ...v, done: true } })} fields={[{ key: "albumin", label: "Albumin" }, { key: "protein", label: "Protein" }, { key: "cellCount", label: "Cell Count" }, { key: "cytology", label: "Cytology" }, { key: "culture", label: "Culture" }, { key: "saag", label: "SAAG" }]} />
        <LabCard label="Pleural Fluid" color="#4527a0" data={c.pleural} onChange={v => setC({ ...c, pleural: { ...v, done: true } })} fields={[{ key: "albumin", label: "Albumin" }, { key: "protein", label: "Protein" }, { key: "ldh", label: "LDH" }, { key: "cellCount", label: "Cell Count" }, { key: "cytology", label: "Cytology" }, { key: "culture", label: "Culture" }]} />

        <hr style={{ border: "none", borderTop: "1px solid #e2e8f0", margin: "12px 0" }} />
        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#6a1b9a", marginBottom: 8 }}>Imaging</div>
        {IMAGING_KEYS.map(k => {
          const img = (typeof c[k] === "object" && c[k] !== null) ? c[k] : { done: !!c[k], date: "", region: "", findings: typeof c[k] === "string" ? c[k] : "" };
          const setImg = (u) => setC({ ...c, [k]: { ...img, ...u } });
          return <div key={k} style={{ marginBottom: 5, borderRadius: 8, border: img.done ? "1.5px solid #ce93d8" : "1.5px solid #e2e8f0", overflow: "hidden", background: img.done ? "#faf5ff" : "#fff" }}>
            <button onClick={() => setImg({ done: !img.done })} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "7px 10px", border: "none", background: "transparent", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontSize: "0.76rem", fontWeight: 600, color: img.done ? "#6a1b9a" : "#94a3b8", textAlign: "left" }}>
              <span style={{ width: 18, height: 18, borderRadius: 4, border: img.done ? "2px solid #6a1b9a" : "2px solid #cbd5e1", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "0.65rem", color: "#fff", background: img.done ? "#6a1b9a" : "transparent", flexShrink: 0 }}>{img.done ? "✓" : ""}</span>
              {IMAGING_LABELS[k]}
              {img.done && img.region && <span style={{ fontSize: "0.62rem", color: "#94a3b8", fontWeight: 400, marginLeft: "auto" }}>{img.region}</span>}
            </button>
            {img.done && <div style={{ padding: "0 10px 8px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
              <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Date</label><input style={{ ...inp, fontSize: "0.78rem" }} type="date" value={img.date || ""} onChange={e => setImg({ date: e.target.value })} /></div>
              <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Region Scanned</label><input style={inp} value={img.region || ""} onChange={e => setImg({ region: e.target.value })} placeholder="e.g. Abdomen, Pelvis..." /></div>
              <div style={{ gridColumn: "1 / -1" }}><label style={{ ...lbl, fontSize: "0.6rem" }}>Findings</label><textarea style={{ ...inp, minHeight: 36, resize: "vertical" }} value={img.findings || ""} onChange={e => setImg({ findings: e.target.value })} placeholder="Findings..." /></div>
            </div>}
          </div>;
        })}

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#6a1b9a", marginBottom: 8, marginTop: 12 }}>Endoscopy</div>
        {ENDO_KEYS.map(k => {
          const img = (typeof c[k] === "object" && c[k] !== null) ? c[k] : { done: !!c[k], date: "", findings: typeof c[k] === "string" ? c[k] : "" };
          const setImg = (u) => setC({ ...c, [k]: { ...img, ...u } });
          return <div key={k} style={{ marginBottom: 5, borderRadius: 8, border: img.done ? "1.5px solid #00897b" : "1.5px solid #e2e8f0", overflow: "hidden", background: img.done ? "#e0f2f1" : "#fff" }}>
            <button onClick={() => setImg({ done: !img.done })} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "7px 10px", border: "none", background: "transparent", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontSize: "0.76rem", fontWeight: 600, color: img.done ? "#00695c" : "#94a3b8", textAlign: "left" }}>
              <span style={{ width: 18, height: 18, borderRadius: 4, border: img.done ? "2px solid #00695c" : "2px solid #cbd5e1", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "0.65rem", color: "#fff", background: img.done ? "#00695c" : "transparent", flexShrink: 0 }}>{img.done ? "✓" : ""}</span>
              {ENDO_LABELS[k]}
            </button>
            {img.done && <div style={{ padding: "0 10px 8px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
              <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Date</label><input style={{ ...inp, fontSize: "0.78rem" }} type="date" value={img.date || ""} onChange={e => setImg({ date: e.target.value })} /></div>
              <div style={{ gridColumn: "1 / -1" }}><label style={{ ...lbl, fontSize: "0.6rem" }}>Findings</label><textarea style={{ ...inp, minHeight: 36, resize: "vertical" }} value={img.findings || ""} onChange={e => setImg({ findings: e.target.value })} placeholder="Findings..." /></div>
            </div>}
          </div>;
        })}

        <div style={{ fontWeight: 700, fontSize: "0.78rem", color: "#6a1b9a", marginBottom: 8, marginTop: 12 }}>Pathology</div>
        {PATHO_KEYS.map(k => {
          const img = (typeof c[k] === "object" && c[k] !== null) ? c[k] : { done: !!c[k], date: "", site: "", findings: typeof c[k] === "string" ? c[k] : "" };
          const setImg = (u) => setC({ ...c, [k]: { ...img, ...u } });
          return <div key={k} style={{ marginBottom: 5, borderRadius: 8, border: img.done ? "1.5px solid #e65100" : "1.5px solid #e2e8f0", overflow: "hidden", background: img.done ? "#fff3e0" : "#fff" }}>
            <button onClick={() => setImg({ done: !img.done })} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "7px 10px", border: "none", background: "transparent", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontSize: "0.76rem", fontWeight: 600, color: img.done ? "#e65100" : "#94a3b8", textAlign: "left" }}>
              <span style={{ width: 18, height: 18, borderRadius: 4, border: img.done ? "2px solid #e65100" : "2px solid #cbd5e1", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "0.65rem", color: "#fff", background: img.done ? "#e65100" : "transparent", flexShrink: 0 }}>{img.done ? "✓" : ""}</span>
              {PATHO_LABELS[k]}
              {img.done && img.site && <span style={{ fontSize: "0.62rem", color: "#94a3b8", fontWeight: 400, marginLeft: "auto" }}>{img.site}</span>}
            </button>
            {img.done && <div style={{ padding: "0 10px 8px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
              <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Date</label><input style={{ ...inp, fontSize: "0.78rem" }} type="date" value={img.date || ""} onChange={e => setImg({ date: e.target.value })} /></div>
              <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Site</label><input style={inp} value={img.site || ""} onChange={e => setImg({ site: e.target.value })} placeholder="e.g. Breast, Lymph node..." /></div>
              <div style={{ gridColumn: "1 / -1" }}><label style={{ ...lbl, fontSize: "0.6rem" }}>Findings / Report</label><textarea style={{ ...inp, minHeight: 36, resize: "vertical" }} value={img.findings || ""} onChange={e => setImg({ findings: e.target.value })} placeholder="Report..." /></div>
            </div>}
          </div>;
        })}

        {/* Additional Investigations — Dynamic Add */}
        <hr style={{ border: "none", borderTop: "1px solid #e2e8f0", margin: "10px 0" }} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
          <span style={{ fontWeight: 700, fontSize: "0.78rem", color: "#6a1b9a" }}>Additional Investigations</span>
          <button onClick={() => setC({ ...c, additionalInvestigations: [...(c.additionalInvestigations || []), { name: "", value: "", date: "" }] })} style={{ padding: "3px 10px", borderRadius: 6, border: "1px solid #ce93d8", background: "#f3e5f5", fontSize: "0.68rem", fontWeight: 600, color: "#6a1b9a", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>+ Add Investigation</button>
        </div>
        {(c.additionalInvestigations || []).map((inv, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(120px, 1fr))", gap: 6, marginBottom: 4, alignItems: "end" }}>
            <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Investigation</label><input style={inp} value={inv.name} onChange={e => { const n = [...c.additionalInvestigations]; n[i] = { ...n[i], name: e.target.value }; setC({ ...c, additionalInvestigations: n }); }} placeholder="e.g. PT/INR, HbA1c..." /></div>
            <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Findings / Value</label><input style={inp} value={inv.value} onChange={e => { const n = [...c.additionalInvestigations]; n[i] = { ...n[i], value: e.target.value }; setC({ ...c, additionalInvestigations: n }); }} placeholder="Result..." /></div>
            <div style={{ display: "flex", gap: 4, alignItems: "end" }}>
              <div style={{ flex: 1 }}><label style={{ ...lbl, fontSize: "0.6rem" }}>Date</label><input style={{ ...inp, fontSize: "0.78rem" }} type="date" value={inv.date || ""} onChange={e => { const n = [...c.additionalInvestigations]; n[i] = { ...n[i], date: e.target.value }; setC({ ...c, additionalInvestigations: n }); }} /></div>
              <button onClick={() => { const n = c.additionalInvestigations.filter((_, j) => j !== i); setC({ ...c, additionalInvestigations: n }); }} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.78rem", fontWeight: 700, paddingBottom: 6 }}>✕</button>
            </div>
          </div>
        ))}
        <PhotoUpload label="Investigation Images (reports, scans)" photos={c.investigationPhotos || []} onChange={v => setC({ ...c, investigationPhotos: v })} maxPhotos={10} accept="image/jpeg,image/png,image/webp,application/pdf" />
      </CollapseSection>

      {/* Section 4: Pre-Operative Diagnosis */}
      <CollapseSection title="Pre-Operative Diagnosis" icon="🩺" open={sec.s4} onToggle={() => setSec({ ...sec, s4: !sec.s4 })} color="#0d47a1">
        {/* Lesion Type Toggle */}
        <div style={{ marginBottom: 14 }}>
          <label style={lbl}>Type of Lesion</label>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setP({ ...emptyPreOp(), lesionType: "benign" })} style={{ flex: 1, padding: "10px 14px", borderRadius: 10, border: p.lesionType === "benign" ? "2px solid #2e7d32" : "1.5px solid #e2e8f0", background: p.lesionType === "benign" ? "#e8f5e9" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 700, fontSize: "0.88rem", color: p.lesionType === "benign" ? "#2e7d32" : "#94a3b8" }}>🟢 Benign</button>
            <button onClick={() => setP({ ...emptyPreOp(), lesionType: "malignancy" })} style={{ flex: 1, padding: "10px 14px", borderRadius: 10, border: p.lesionType === "malignancy" ? "2px solid #c62828" : "1.5px solid #e2e8f0", background: p.lesionType === "malignancy" ? "#fce4ec" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 700, fontSize: "0.88rem", color: p.lesionType === "malignancy" ? "#c62828" : "#94a3b8" }}>🔴 Malignant</button>
          </div>
        </div>

        {/* ─── BENIGN ─── */}
        {p.lesionType === "benign" && <>
          {/* Primary Diagnosis — laterality & site now built into diagnosis name */}
          <div>
            <label style={lbl}>Primary Diagnosis</label>
            <SearchSelect clearable options={[...repo.allBenignDx.map(d => d.dx), "Other (Enter Manually)"]} value={p.primaryDx} onChange={v => {
              if (v === "Other (Enter Manually)") { setP({ primaryDx: "", primaryDxManual: true, benignCategory: "", primarySubtype: "", procedure: "", lesionType: "benign" }); return; }
              const found = repo.allBenignDx.find(d => d.dx === v);
              setP({ primaryDx: v, primaryDxManual: false, benignCategory: found?.category || "", primarySubtype: "", procedure: "", lesionType: "benign" });
            }} placeholder="Search diagnosis..." />
            {p.primaryDxManual && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={p.primaryDx} onChange={e => setP({ primaryDx: e.target.value })} placeholder="Enter diagnosis manually..." />}
          </div>
          {/* Subtype */}
          {getSubtypes(p.primaryDx) && <div style={{ marginTop: 8 }}>
            <label style={lbl}>Subtype / Grade</label>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
              {getSubtypes(p.primaryDx).map(s => <button key={s} onClick={() => setP({ primarySubtype: s })} style={chip(p.primarySubtype === s, "#e65100")}>{s}</button>)}
            </div>
          </div>}
          {/* ASH Classification for hernias */}
          {isHernia(p.primaryDx) && <div style={{ marginTop: 8 }}>
            <label style={lbl}>Classification (Nyhus / EHS)</label>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
              {ASH_GRADES.map(g => <button key={g} onClick={() => setP({ ashClass: g })} style={chip(p.ashClass === g, "#1565c0")}>{g}</button>)}
            </div>
          </div>}

          {/* Secondary Diagnosis */}
          <div style={{ marginTop: 14, padding: "10px 12px", background: "#f8fafc", borderRadius: 8, border: "1px dashed #e2e8f0" }}>
            <label style={{ ...lbl, color: "#64748b" }}>Secondary Diagnosis (Optional)</label>
            <SearchSelect clearable options={[...repo.allBenignDx.map(d => d.dx), "Other (Enter Manually)"]} value={p.secondaryDx} onChange={v => {
              if (v === "Other (Enter Manually)") { setP({ secondaryDx: "", secondaryDxManual: true }); return; }
              setP({ secondaryDx: v, secondaryDxManual: false });
            }} placeholder="Search..." />
            {p.secondaryDxManual && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={p.secondaryDx} onChange={e => setP({ secondaryDx: e.target.value })} placeholder="Enter secondary diagnosis manually..." />}
          </div>

          {/* Procedure */}
          <div style={{ marginTop: 10 }}>
            <label style={lbl}>Planned Procedure</label>
            <SearchSelect clearable options={[...getProcedures(), "Diagnostic Laparoscopy and Proceed", "Other (Enter Manually)"]} value={p.procedure} onChange={v => {
              if (v === "Other (Enter Manually)") { setP({ procedure: "", procedureManual: true }); return; }
              setP({ procedure: v, procedureManual: false });
            }} placeholder="Select procedure..." />
            {p.procedureManual && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={p.procedure} onChange={e => setP({ procedure: e.target.value })} placeholder="Enter procedure manually..." />}
          </div>
          {/* Access Mode */}
          {p.procedure && <div style={{ marginTop: 8 }}>
            <label style={lbl}>Mode of Access</label>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
              {ACCESS_MODES.map(m => <button key={m} onClick={() => setP({ accessMode: m, accessOther: m === "Others" ? p.accessOther : "" })} style={chip(p.accessMode === m, "#0d47a1")}>{m}</button>)}
            </div>
            {p.accessMode === "Others" && <input style={{ ...inp, marginTop: 4 }} placeholder="Specify access..." value={p.accessOther} onChange={e => setP({ accessOther: e.target.value })} />}
          </div>}
        </>}

        {/* ─── MALIGNANCY ─── */}
        {p.lesionType === "malignancy" && <>
          {/* Histological Type — FIRST */}
          <div>
            <label style={lbl}>Histological Type</label>
            <select style={inp} value={p.preOpHistology} onChange={e => setP({ preOpHistology: e.target.value })}>
              <option value="">Select histology...</option>{HISTOLOGY_TYPES.map(h => <option key={h}>{h}</option>)}
            </select>
            {p.preOpHistology === "Others" && <input style={{ ...inp, marginTop: 4, borderColor: "#c62828" }} value={p.histologyOther || ""} onChange={e => setP({ histologyOther: e.target.value })} placeholder="Specify histological type..." />}
          </div>
          {/* Site of Malignancy */}
          <div style={{ marginTop: 10 }}>
            <label style={lbl}>Site</label>
            <SearchSelect clearable options={[...Object.keys(repo.maligSites), "Other (Enter Manually)"]} value={p.malSite} onChange={v => {
              if (v === "Other (Enter Manually)") { setP({ malSite: "", malSiteManual: true, procedure: "" }); return; }
              setP({ malSite: v, malSiteManual: false, procedure: "" });
            }} placeholder="Search site..." />
            {p.malSiteManual && <input style={{ ...inp, marginTop: 4, borderColor: "#c62828" }} autoFocus value={p.malSite} onChange={e => setP({ malSite: e.target.value })} placeholder="Enter site manually..." />}
          </div>
          {/* Diagnosis preview */}
          {(p.preOpHistology || p.malSite) && <div style={{ marginTop: 8, padding: "6px 10px", background: "#fce4ec", borderRadius: 6, fontSize: "0.78rem", color: "#c62828", fontWeight: 600 }}>
            Dx: {(p.preOpHistology === "Others" ? p.histologyOther : p.preOpHistology) || "?"} {p.malSite || "?"}
          </div>}
          {p.malSite && <>
            <div style={{ ...g2, marginTop: 10 }}>
              <div><label style={lbl}>IHC</label><input style={inp} value={p.ihc} onChange={e => setP({ ihc: e.target.value })} /></div>
            </div>
            <div style={{ marginTop: 10 }}>
              <label style={lbl}>Clinical Staging (TNM)</label>
              <div style={g3}>
                <div><label style={{ ...lbl, fontSize: "0.62rem" }}>T</label><input style={inp} value={p.clinicalT} onChange={e => setP({ clinicalT: e.target.value })} placeholder="T1/T2/T3/T4" /></div>
                <div><label style={{ ...lbl, fontSize: "0.62rem" }}>N</label><input style={inp} value={p.clinicalN} onChange={e => setP({ clinicalN: e.target.value })} placeholder="N0/N1/N2" /></div>
                <div><label style={{ ...lbl, fontSize: "0.62rem" }}>M</label><input style={inp} value={p.clinicalM} onChange={e => setP({ clinicalM: e.target.value })} placeholder="M0/M1" /></div>
              </div>
            </div>
            {/* Secondary Diagnosis for malignancy */}
            <div style={{ marginTop: 10, padding: "10px 12px", background: "#f8fafc", borderRadius: 8, border: "1px dashed #e2e8f0" }}>
              <label style={{ ...lbl, color: "#64748b" }}>Secondary Diagnosis (Optional)</label>
              <input style={inp} value={p.secondaryDx} onChange={e => setP({ secondaryDx: e.target.value })} placeholder="Type secondary diagnosis..." />
            </div>
            {/* Plan */}
            <div style={{ marginTop: 10 }}>
              <label style={lbl}>Plan</label>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {["Curative", "Palliative", "Neoadjuvant → Surgery", "Adjuvant", "Diagnostic"].map(pl => <button key={pl} onClick={() => setP({ plan: pl })} style={chip(p.plan === pl, pl === "Palliative" ? "#e65100" : "#2e7d32")}>{pl}</button>)}
              </div>
            </div>
            {/* Procedure */}
            <div style={{ marginTop: 10 }}>
              <label style={lbl}>Planned Procedure</label>
              <SearchSelect clearable options={[...(repo.maligSites[p.malSite]?.procedures || []), "Diagnostic Laparoscopy and Proceed", "Other (Enter Manually)"]} value={p.procedure} onChange={v => {
                if (v === "Other (Enter Manually)") { setP({ procedure: "", procedureManual: true }); return; }
                setP({ procedure: v, procedureManual: false });
              }} placeholder="Select procedure..." />
              {p.procedureManual && <input style={{ ...inp, marginTop: 4, borderColor: "#c62828" }} autoFocus value={p.procedure} onChange={e => setP({ procedure: e.target.value })} placeholder="Enter procedure manually..." />}
            </div>
            {/* Access Mode */}
            {p.procedure && <div style={{ marginTop: 8 }}>
              <label style={lbl}>Mode of Access</label>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
                {ACCESS_MODES.map(m => <button key={m} onClick={() => setP({ accessMode: m, accessOther: m === "Others" ? p.accessOther : "" })} style={chip(p.accessMode === m, "#0d47a1")}>{m}</button>)}
              </div>
              {p.accessMode === "Others" && <input style={{ ...inp, marginTop: 4 }} placeholder="Specify access..." value={p.accessOther} onChange={e => setP({ accessOther: e.target.value })} />}
            </div>}
          </>}
        </>}
      </CollapseSection>

      {/* Validation Warning Modal */}
      {formWarnings && <div style={{ position: "fixed", inset: 0, background: "rgba(11,20,32,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 9999, padding: 20 }}>
        <div style={{ background: "#fff", borderRadius: 16, padding: "24px 22px", maxWidth: 400, width: "100%", boxShadow: "0 20px 60px rgba(0,0,0,0.25)", fontFamily: "'Outfit',sans-serif", maxHeight: "85vh", overflowY: "auto" }}>
          <div style={{ fontSize: "1.1rem", fontWeight: 700, color: "#e65100", marginBottom: 14 }}>{"⚠️"} Missing Information</div>
          {formWarnings.missingFields && formWarnings.missingFields.length > 0 && <>
            <div style={{ fontSize: "0.78rem", fontWeight: 700, color: "#c62828", marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.04em" }}>Key Fields Missing</div>
            <div style={{ marginBottom: 14 }}>
              {formWarnings.missingFields.map((w, i) => (
                <div key={i} style={{ padding: "7px 12px", marginBottom: 3, background: "#fef2f2", borderRadius: 8, fontSize: "0.84rem", color: "#c62828", fontWeight: 600, borderLeft: "3px solid #c62828" }}>{"⚠️"} {w}</div>
              ))}
            </div>
          </>}
          {formWarnings.emptySections && formWarnings.emptySections.length > 0 && <>
            <div style={{ fontSize: "0.78rem", fontWeight: 700, color: "#e65100", marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.04em" }}>Empty Sections</div>
            <div style={{ marginBottom: 14 }}>
              {formWarnings.emptySections.map((w, i) => (
                <div key={i} style={{ padding: "7px 12px", marginBottom: 3, background: "#fff3e0", borderRadius: 8, fontSize: "0.84rem", color: "#e65100", fontWeight: 600, borderLeft: "3px solid #e65100" }}>{"📋"} {w}</div>
              ))}
            </div>
          </>}
          <div style={{ fontSize: "0.8rem", color: "#64748b", marginBottom: 16 }}>You can save now and complete these later.</div>
          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
            <button onClick={() => setFormWarnings(null)} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Go Back</button>
            <button onClick={formWarnings.onProceed} style={{ padding: "10px 20px", background: "linear-gradient(135deg,#e65100,#ff8f00)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.84rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Save Anyway</button>
          </div>
        </div>
      </div>}

      <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
        <button onClick={onCancel} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontWeight: 500, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Cancel</button>
        <button onClick={doSave} style={{ padding: "10px 24px", background: "linear-gradient(135deg,#2e7d32,#388e3c)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.88rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Save Clinical Details</button>
      </div>
    </div>
  );
}

function OperativeForm({ patient, config: cfg, onSave, onCancel, repo }) {
  const od = patient.opDetails || emptyOpDetails();
  const [o, setO] = useState({ ...emptyOpDetails(), ...od, surgeryDateActual: od.surgeryDateActual || patient.clinical?.surgeryListDate || "" });
  const [sec, setSec] = useState({ s1: true, s2: false, s3: false });
  const [opFormWarnings, setOpFormWarnings] = useState(null); // { warnings, onProceed }
  const surgeonList = (cfg?.surgeons || DEFAULT_CONFIG.surgeons || []);
  const surgeonNames = surgeonList.map(s => s.name);
  const inp = { width: "100%", padding: "7px 10px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" };
  const lbl = { display: "block", fontSize: "0.68rem", fontWeight: 600, color: "#475569", marginBottom: 3, textTransform: "uppercase", letterSpacing: "0.04em" };
  const g2 = { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 10 };
  const g3 = { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10 };
  const chip = (sel, clr) => ({ padding: "4px 10px", borderRadius: 16, border: `1.5px solid ${sel ? clr : "#e2e8f0"}`, background: sel ? clr + "12" : "#fff", cursor: "pointer", fontSize: "0.72rem", fontFamily: "'Outfit',sans-serif", fontWeight: sel ? 600 : 400, color: sel ? clr : "#94a3b8" });
  const dur = () => { if (!o.startTime || !o.endTime) return "—"; const [sh, sm] = o.startTime.split(":").map(Number); const [eh, em] = o.endTime.split(":").map(Number); let m = (eh * 60 + em) - (sh * 60 + sm); if (m < 0) m += 1440; const h = Math.floor(m / 60); return h > 0 ? `${h}h ${m % 60}m` : `${m}m`; };

  return (
    <div style={{ maxWidth: 740, margin: "0 auto" }}>
      {/* Patient summary */}
      <div style={{ background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 10, padding: "10px 14px", marginBottom: 14, fontSize: "0.82rem", color: "#475569", lineHeight: 1.7 }}>
        <b>{patient.name}</b> · {patient.age}y/{patient.sex?.[0]} · MRD: {patient.clinical?.mrd || "—"} · {patient.clinical?.theater || "—"}<br/>
        <b>Dx:</b> {patient.type === "malignancy" ? (patient.malignancySite || "Malignancy") : (patient.diagnosis || "—")} → <b>Planned:</b> {patient.plannedProcedure || "—"}
      </div>

      <CollapseSection title="Surgery & Team" icon="🔪" open={sec.s1} onToggle={() => setSec({ ...sec, s1: !sec.s1 })} color="#0d47a1">
        <div style={g3}>
          <div><label style={lbl}>Surgery Date</label><input style={inp} type="date" value={o.surgeryDateActual} onChange={e => setO({ ...o, surgeryDateActual: e.target.value })} /></div>
          <div><label style={lbl}>Start Time</label><input style={inp} type="time" value={o.startTime} onChange={e => setO({ ...o, startTime: e.target.value })} /></div>
          <div><label style={lbl}>End Time</label><input style={inp} type="time" value={o.endTime} onChange={e => setO({ ...o, endTime: e.target.value })} /></div>
        </div>
        {o.startTime && o.endTime && <div style={{ marginTop: 4, fontSize: "0.76rem", color: "#2e7d32", fontWeight: 600 }}>Duration: {dur()}</div>}
        <div style={{ marginTop: 10 }}>
          <label style={lbl}>Anaesthesia</label>
          <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
            {ANAESTHESIA.map(a => <button key={a} onClick={() => setO({ ...o, anaesthesia: a })} style={chip(o.anaesthesia === a, "#0d47a1")}>{a}</button>)}
          </div>
          {o.anaesthesia === "Other" && <input style={{ ...inp, marginTop: 4 }} value={o.anaesthesiaOther} onChange={e => setO({ ...o, anaesthesiaOther: e.target.value })} placeholder="Specify..." />}
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Anaesthetist</label><input style={inp} value={o.anaesthetist} onChange={e => setO({ ...o, anaesthetist: e.target.value })} placeholder="Name..." /></div>
          <div><label style={lbl}>Patient Position</label>
            <div style={{ display: "flex", gap: 3, flexWrap: "wrap" }}>
              {["Supine", "Lithotomy", "Lateral", "Prone", "Trendelenburg", "Reverse Trendelenburg", "Lloyd Davies", "Other"].map(p => <button key={p} onClick={() => setO({ ...o, patientPosition: p })} style={chip(o.patientPosition === p, "#0d47a1")}>{p}</button>)}
            </div>
            {o.patientPosition === "Other" && <input style={{ ...inp, marginTop: 4 }} value={o.patientPositionOther} onChange={e => setO({ ...o, patientPositionOther: e.target.value })} placeholder="Specify position..." />}
          </div>
        </div>
        <div style={{ ...g2, marginTop: 10 }}>
          <div><label style={lbl}>Operating Surgeon</label>
            <select style={inp} value={o.operatingSurgeon} onChange={e => setO({ ...o, operatingSurgeon: e.target.value, surgeonOther: e.target.value === "__other" ? o.surgeonOther : "" })}>
              <option value="">Select...</option>
              {surgeonNames.map(s => <option key={s} value={s}>{s}</option>)}
              <option value="__other">Other (type name)</option>
            </select>
            {o.operatingSurgeon === "__other" && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={o.surgeonOther} onChange={e => setO({ ...o, surgeonOther: e.target.value })} placeholder="Enter surgeon name..." />}
          </div>
          <div><label style={lbl}>1st Assistant</label>
            <select style={inp} value={o.firstAssistant} onChange={e => setO({ ...o, firstAssistant: e.target.value, assistantOther: e.target.value === "__other" ? o.assistantOther : "" })}>
              <option value="">Select...</option>
              {surgeonNames.map(s => <option key={s} value={s}>{s}</option>)}
              <option value="__other">Other (type name)</option>
            </select>
            {o.firstAssistant === "__other" && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={o.assistantOther} onChange={e => setO({ ...o, assistantOther: e.target.value })} placeholder="Enter assistant name..." />}
          </div>
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>2nd Assistant</label>
            <select style={inp} value={o.secondAssistant} onChange={e => setO({ ...o, secondAssistant: e.target.value, secondAssistantOther: e.target.value === "__other" ? o.secondAssistantOther : "" })}>
              <option value="">Select...</option>
              {surgeonNames.map(s => <option key={s} value={s}>{s}</option>)}
              <option value="__other">Other (type name)</option>
            </select>
            {o.secondAssistant === "__other" && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={o.secondAssistantOther} onChange={e => setO({ ...o, secondAssistantOther: e.target.value })} placeholder="Enter 2nd assistant name..." />}
          </div>
          <div><label style={lbl}>3rd Assistant</label>
            <select style={inp} value={o.thirdAssistant || ""} onChange={e => setO({ ...o, thirdAssistant: e.target.value, thirdAssistantOther: e.target.value === "__other" ? o.thirdAssistantOther : "" })}>
              <option value="">Select...</option>
              {surgeonNames.map(s => <option key={s} value={s}>{s}</option>)}
              <option value="__other">Other (type name)</option>
            </select>
            {o.thirdAssistant === "__other" && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={o.thirdAssistantOther || ""} onChange={e => setO({ ...o, thirdAssistantOther: e.target.value })} placeholder="Enter 3rd assistant name..." />}
          </div>
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>4th Assistant</label>
            <select style={inp} value={o.fourthAssistant || ""} onChange={e => setO({ ...o, fourthAssistant: e.target.value, fourthAssistantOther: e.target.value === "__other" ? o.fourthAssistantOther : "" })}>
              <option value="">Select...</option>
              {surgeonNames.map(s => <option key={s} value={s}>{s}</option>)}
              <option value="__other">Other (type name)</option>
            </select>
            {o.fourthAssistant === "__other" && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={o.fourthAssistantOther || ""} onChange={e => setO({ ...o, fourthAssistantOther: e.target.value })} placeholder="Enter 4th assistant name..." />}
          </div>
          <div><label style={lbl}>5th Assistant</label>
            <select style={inp} value={o.fifthAssistant || ""} onChange={e => setO({ ...o, fifthAssistant: e.target.value, fifthAssistantOther: e.target.value === "__other" ? o.fifthAssistantOther : "" })}>
              <option value="">Select...</option>
              {surgeonNames.map(s => <option key={s} value={s}>{s}</option>)}
              <option value="__other">Other (type name)</option>
            </select>
            {o.fifthAssistant === "__other" && <input style={{ ...inp, marginTop: 4, borderColor: "#1565c0" }} autoFocus value={o.fifthAssistantOther || ""} onChange={e => setO({ ...o, fifthAssistantOther: e.target.value })} placeholder="Enter 5th assistant name..." />}
          </div>
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Theatre Assistant / Scrub Nurse</label><input style={inp} value={o.theatreAssistant} onChange={e => setO({ ...o, theatreAssistant: e.target.value })} /></div>
        </div>
      </CollapseSection>

      <CollapseSection title="Procedure Details" icon="📋" open={sec.s2} onToggle={() => setSec({ ...sec, s2: !sec.s2 })} color="#6a1b9a">
        <div><label style={lbl}>Mode of Access</label>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
            {OP_ACCESS_MODES.map(m => <button key={m} onClick={() => setO({ ...o, opAccessMode: m })} style={chip(o.opAccessMode === m, "#6a1b9a")}>{m}</button>)}
          </div>
          {o.opAccessMode === "Other" && <input style={{ ...inp, marginTop: 4 }} value={o.opAccessOther} onChange={e => setO({ ...o, opAccessOther: e.target.value })} placeholder="Specify..." />}
        </div>
        <div style={{ marginTop: 10 }}>
          <label style={lbl}>Primary Procedure</label>
          <SearchSelect clearable options={[...repo.opProcs, "Other (Enter Manually)"]} value={o.primaryProcedure} onChange={v => {
            if (v === "Other (Enter Manually)") { setO({ ...o, primaryProcedure: "", primaryProcManual: true }); return; }
            setO({ ...o, primaryProcedure: v, primaryProcManual: false });
          }} placeholder="Select procedure..." />
          {o.primaryProcManual && <input style={{ ...inp, marginTop: 4, borderColor: "#6a1b9a" }} autoFocus value={o.primaryProcedure} onChange={e => setO({ ...o, primaryProcedure: e.target.value })} placeholder="Enter manually..." />}
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Adjunct Procedure</label><input style={inp} value={o.adjunctProcedure} onChange={e => setO({ ...o, adjunctProcedure: e.target.value })} /></div>
          <div><label style={lbl}>Secondary Procedure</label><input style={inp} value={o.secondaryProcedure} onChange={e => setO({ ...o, secondaryProcedure: e.target.value })} /></div>
        </div>
        <div style={{ marginTop: 10 }}><MultiInput label="Intra-Operative Findings" values={o.intraFindings} onChange={v => setO({ ...o, intraFindings: v })} max={5} /></div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Specimen Sent</label>
            <div style={{ display: "flex", gap: 4 }}>{["No", "Yes — HPE", "Yes — Frozen Section", "Yes — Culture", "Yes — Other"].map(v => <button key={v} onClick={() => setO({ ...o, specimenSent: v })} style={chip(o.specimenSent === v, "#6a1b9a")}>{v}</button>)}</div>
            {o.specimenSent && o.specimenSent !== "No" && <input style={{ ...inp, marginTop: 4 }} value={o.specimenDetails} onChange={e => setO({ ...o, specimenDetails: e.target.value })} placeholder="Specimen details (type, label)..." />}
          </div>
        </div>
        <div style={{ marginTop: 8 }}><label style={lbl}>Brief Operative Note</label><textarea style={{ ...inp, minHeight: 60, resize: "vertical" }} value={o.operativeNote} onChange={e => setO({ ...o, operativeNote: e.target.value })} placeholder="Narrative operative note — steps of procedure, key findings, closure details..." /></div>
        <PhotoUpload label="Operative Photos" photos={o.opPhotos || []} onChange={v => setO({ ...o, opPhotos: v })} maxPhotos={10} />
      </CollapseSection>

      <CollapseSection title="Intra-Op Details" icon="🏥" open={sec.s3} onToggle={() => setSec({ ...sec, s3: !sec.s3 })} color="#c62828">
        <div style={g3}>
          <div><label style={lbl}>Blood Loss (ml)</label><input style={inp} type="number" value={o.bloodLoss} onChange={e => setO({ ...o, bloodLoss: e.target.value })} /></div>
          <div><label style={lbl}>PRBC Units</label><select style={inp} value={o.prbcTransfusion} onChange={e => setO({ ...o, prbcTransfusion: e.target.value })}>{["0","1","2","3","4","5",">5"].map(v => <option key={v}>{v}</option>)}</select></div>
          <div><label style={lbl}>FFP Units</label><select style={inp} value={o.ffpUnits} onChange={e => setO({ ...o, ffpUnits: e.target.value })}>{["0","1","2","3","4",">4"].map(v => <option key={v}>{v}</option>)}</select></div>
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Complication 1</label><select style={inp} value={o.complication1} onChange={e => setO({ ...o, complication1: e.target.value })}><option value="">None</option>{INTRA_COMPLICATIONS.filter(c=>c!=="None").map(c => <option key={c}>{c}</option>)}</select>
            {o.complication1 === "Other" && <input style={{ ...inp, marginTop: 4 }} value={o.complication1Other} onChange={e => setO({ ...o, complication1Other: e.target.value })} placeholder="Specify..." />}</div>
          <div><label style={lbl}>Complication 2</label><select style={inp} value={o.complication2} onChange={e => setO({ ...o, complication2: e.target.value })}><option value="">None</option>{INTRA_COMPLICATIONS.filter(c=>c!=="None").map(c => <option key={c}>{c}</option>)}</select>
            {o.complication2 === "Other" && <input style={{ ...inp, marginTop: 4 }} value={o.complication2Other} onChange={e => setO({ ...o, complication2Other: e.target.value })} placeholder="Specify..." />}</div>
        </div>
        <div style={{ ...g3, marginTop: 8 }}>
          <div><label style={lbl}>Drains</label>
            <div style={{ display: "flex", gap: 4 }}>{["No","Yes"].map(v => <button key={v} onClick={() => { if (v === "Yes" && (!o.drainList || o.drainList.length === 0)) setO({ ...o, drains: v, drainList: [{ type: "", site: "" }] }); else setO({ ...o, drains: v, drainList: v === "No" ? [] : o.drainList }); }} style={chip(o.drains === v, v === "Yes" ? "#c62828" : "#94a3b8")}>{v}</button>)}</div>
          </div>
        </div>
        {o.drains === "Yes" && (o.drainList || []).map((dr, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr auto", gap: 6, marginTop: 6, padding: "6px 8px", background: "#fef2f2", borderRadius: 6, border: "1px solid #fecaca", alignItems: "end" }}>
            <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Drain {i+1} — Type</label><input style={inp} value={dr.type} onChange={e => { const n = [...o.drainList]; n[i] = { ...n[i], type: e.target.value }; setO({ ...o, drainList: n }); }} placeholder="e.g. Romovac, Tube..." /></div>
            <div><label style={{ ...lbl, fontSize: "0.6rem" }}>Site</label><input style={inp} value={dr.site} onChange={e => { const n = [...o.drainList]; n[i] = { ...n[i], site: e.target.value }; setO({ ...o, drainList: n }); }} placeholder="e.g. Subhepatic, Pelvis..." /></div>
            <button onClick={() => { const n = o.drainList.filter((_, j) => j !== i); setO({ ...o, drainList: n, drains: n.length === 0 ? "No" : "Yes" }); }} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "1rem", fontWeight: 700, paddingBottom: 6 }}>✕</button>
          </div>
        ))}
        {o.drains === "Yes" && <button onClick={() => setO({ ...o, drainList: [...(o.drainList || []), { type: "", site: "" }] })} style={{ marginTop: 6, padding: "4px 12px", borderRadius: 6, border: "1px solid #fca5a5", background: "#fef2f2", fontSize: "0.7rem", fontWeight: 600, color: "#c62828", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>+ Add Drain</button>}
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Stoma</label><input style={inp} value={o.stoma} onChange={e => setO({ ...o, stoma: e.target.value })} placeholder="Type if applicable..." /></div>
          {o.stoma && <div><label style={lbl}>Stoma Type / Site</label><input style={inp} value={o.stomaSite} onChange={e => setO({ ...o, stomaSite: e.target.value })} placeholder="e.g. Loop Ileostomy, RIF..." /></div>}
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginTop: 10 }}>
          {[["Ryles Tube","rylesTube"],["Foley's Catheter","foleysCatheter"],["Epidural","epidural"],["Extubation","extubation"]].map(([l,k]) => (
            <div key={k} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <label style={{ fontSize: "0.7rem", fontWeight: 600, color: "#475569" }}>{l}</label>
              <div style={{ display: "flex", gap: 2 }}>
                {["Yes","No"].map(v => <button key={v} onClick={() => setO({ ...o, [k]: v })} style={chip(o[k] === v, v === "Yes" ? "#2e7d32" : "#94a3b8")}>{v}</button>)}
              </div>
            </div>
          ))}
        </div>
        <div style={{ ...g2, marginTop: 10 }}>
          <div><label style={lbl}>Thoracostomy Tube</label>
            <div style={{ display: "flex", gap: 4 }}>{["None","Right","Left","Bilateral"].map(v => <button key={v} onClick={() => setO({ ...o, thoracostomy: v })} style={chip(o.thoracostomy === v, "#c62828")}>{v}</button>)}</div>
          </div>
          <div><label style={lbl}>Abdominal Closure</label>
            <div style={{ display: "flex", gap: 3, flexWrap: "wrap" }}>
              {["Standard Layer", "Mass Closure (PDS)", "Mass Closure (Nylon)", "Tension Sutures", "Skin Staples", "Subcuticular", "Open / Delayed", "Other"].map(v => <button key={v} onClick={() => setO({ ...o, abdominalClosure: v })} style={chip(o.abdominalClosure === v, "#c62828")}>{v}</button>)}
            </div>
          </div>
        </div>
        <div style={{ ...g2, marginTop: 8 }}>
          <div><label style={lbl}>Patient Shifted To</label><select style={inp} value={o.shiftedTo} onChange={e => setO({ ...o, shiftedTo: e.target.value })}><option value="">Select</option>{SHIFTED_TO.map(s => <option key={s}>{s}</option>)}</select></div>
        </div>
        <div style={{ marginTop: 8 }}><label style={lbl}>Other Important Information</label><textarea style={{ ...inp, minHeight: 40, resize: "vertical" }} value={o.otherInfo} onChange={e => setO({ ...o, otherInfo: e.target.value })} /></div>
      </CollapseSection>

      {/* Op Validation Warning Modal */}
      {opFormWarnings && <div style={{ position: "fixed", inset: 0, background: "rgba(11,20,32,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 9999, padding: 20 }}>
        <div style={{ background: "#fff", borderRadius: 16, padding: "24px 22px", maxWidth: 400, width: "100%", boxShadow: "0 20px 60px rgba(0,0,0,0.25)", fontFamily: "'Outfit',sans-serif" }}>
          {opFormWarnings.step === "warnings" && <>
            <div style={{ fontSize: "1.1rem", fontWeight: 700, color: "#e65100", marginBottom: 14 }}>{"⚠️"} Missing Information</div>
            {opFormWarnings.missingFields && opFormWarnings.missingFields.length > 0 && <>
              <div style={{ fontSize: "0.78rem", fontWeight: 700, color: "#c62828", marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.04em" }}>Key Fields Missing</div>
              <div style={{ marginBottom: 14 }}>
                {opFormWarnings.missingFields.map((w, i) => (
                  <div key={i} style={{ padding: "7px 12px", marginBottom: 3, background: "#fef2f2", borderRadius: 8, fontSize: "0.84rem", color: "#c62828", fontWeight: 600, borderLeft: "3px solid #c62828" }}>{"⚠️"} {w}</div>
                ))}
              </div>
            </>}
            {opFormWarnings.emptySections && opFormWarnings.emptySections.length > 0 && <>
              <div style={{ fontSize: "0.78rem", fontWeight: 700, color: "#e65100", marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.04em" }}>Empty Sections</div>
              <div style={{ marginBottom: 14 }}>
                {opFormWarnings.emptySections.map((w, i) => (
                  <div key={i} style={{ padding: "7px 12px", marginBottom: 3, background: "#fff3e0", borderRadius: 8, fontSize: "0.84rem", color: "#e65100", fontWeight: 600, borderLeft: "3px solid #e65100" }}>{"📋"} {w}</div>
                ))}
              </div>
            </>}
            <div style={{ fontSize: "0.8rem", color: "#64748b", marginBottom: 16 }}>You can proceed and complete these later via admin edit.</div>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <button onClick={() => setOpFormWarnings(null)} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Go Back</button>
              <button onClick={() => setOpFormWarnings({ ...opFormWarnings, step: "confirm" })} style={{ padding: "10px 20px", background: "linear-gradient(135deg,#e65100,#ff8f00)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.84rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Proceed Anyway</button>
            </div>
          </>}
          {opFormWarnings.step === "confirm" && <>
            <div style={{ fontSize: "1.1rem", fontWeight: 700, color: "#c62828", marginBottom: 14 }}>{"🔪"} Confirm Operation</div>
            <div style={{ padding: "12px 14px", background: "#f8fafc", borderRadius: 10, border: "1px solid #e2e8f0", marginBottom: 16 }}>
              <div style={{ fontSize: "0.88rem", fontWeight: 700, color: "#1e293b", marginBottom: 8 }}>{patient.name}</div>
              <div style={{ fontSize: "0.8rem", color: "#475569", lineHeight: 1.7 }}>
                <div><b>Procedure:</b> {o.primaryProcedure || "—"}</div>
                <div><b>Surgeon:</b> {o.operatingSurgeon === "__other" ? o.surgeonOther : (o.operatingSurgeon || "—")}</div>
                <div><b>Date:</b> {o.surgeryDateActual || "—"}</div>
                <div><b>Access:</b> {o.opAccessMode || "—"}</div>
              </div>
            </div>
            <div style={{ fontSize: "0.8rem", color: "#c62828", fontWeight: 600, marginBottom: 14 }}>Patient will be moved to Operated status.</div>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <button onClick={() => setOpFormWarnings(null)} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Cancel</button>
              <button onClick={() => { setOpFormWarnings(null); onSave(o); }} style={{ padding: "10px 22px", background: "linear-gradient(135deg,#c62828,#e53935)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.88rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>{"✓"} Confirm Operation</button>
            </div>
          </>}
        </div>
      </div>}

      <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
        <button onClick={onCancel} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Cancel</button>
        <button onClick={() => {
          const emptySections = [];
          const missingFields = [];
          // Key field — always warn
          if (!o.operatingSurgeon) missingFields.push("Operating Surgeon");
          // Surgery & Team — check if ANY team field filled
          const hasTeam = o.surgeryDateActual || o.operatingSurgeon || o.anaesthesia || o.anaesthetist || o.firstAssistant || o.patientPosition;
          if (!hasTeam) emptySections.push("Surgery & Team (Date, Surgeon, Anaesthesia)");
          // Procedure Details — check if ANY procedure field filled
          const hasProcedure = o.primaryProcedure || o.opAccessMode || o.adjunctProcedure || o.secondaryProcedure || o.operativeNote || (o.intraFindings || []).filter(Boolean).length > 0;
          if (!hasProcedure) emptySections.push("Procedure Details (Procedure, Access Mode, Note)");
          // Intra-Op Details — check if ANY intra-op field filled
          const hasIntraOp = o.bloodLoss || o.complication1 || o.complication2 || o.drains === "Yes" || o.stoma || o.shiftedTo || o.rylesTube === "Yes" || o.foleysCatheter === "Yes";
          if (!hasIntraOp) emptySections.push("Intra-Op Details (Blood Loss, Drains, Shifted To)");
          if (missingFields.length > 0 || emptySections.length > 0) {
            setOpFormWarnings({ missingFields, emptySections, step: "warnings" });
          } else {
            setOpFormWarnings({ missingFields: [], emptySections: [], step: "confirm" });
          }
        }} style={{ padding: "10px 24px", background: "linear-gradient(135deg,#c62828,#e53935)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.88rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>{"✓"} Confirm Operation</button>
      </div>
    </div>
  );
}

const FOLLOWUP_CONDITIONS = ["Improving", "Stable", "Fully Recovered", "Wound Issues", "Complications Present", "Worsened", "Readmitted", "Lost to Follow-Up", "Referred", "Expired"];

// ═══ FOLLOW-UP FIELD DEFINITIONS (procedure-specific input fields) ═══
// Common reusable field sets
const F_WOUND = { key: "wound", label: "Wound Status", type: "select", opts: ["Healthy", "Clean & Dry", "Mild Erythema", "Serous Discharge", "Purulent Discharge", "Dehiscence", "Gaping", "Indurated", "Other"] };
const F_SUTURE = { key: "sutureRemoval", label: "Sutures Removed", type: "select", opts: ["Yes - All", "Yes - Alternate", "Not Yet", "Already Removed", "N/A"] };
const F_PAIN = { key: "pain", label: "Pain (0-10)", type: "number" };
const F_DIET = { key: "diet", label: "Diet Tolerance", type: "select", opts: ["Normal", "Soft Diet", "Liquids Only", "Poor Appetite", "Nausea / Vomiting"] };
const F_ACTIVITY = { key: "activity", label: "Activity Level", type: "select", opts: ["Full Activity", "Light Activity", "Restricted", "Bed-bound"] };
const F_HPE = { key: "hpeCollected", label: "HPE Report", type: "select", opts: ["Collected - Benign", "Collected - Malignant", "Collected - Awaiting", "Not Ready Yet", "Not Applicable"] };
const F_DRAIN = { key: "drainStatus", label: "Drain Status", type: "select", opts: ["Removed", "In Situ - Minimal Output", "In Situ - Moderate Output", "In Situ - High Output", "N/A"] };
const F_DRAINVOL = { key: "drainOutput", label: "Drain Output (ml)", type: "number" };
const F_NOTES = { key: "notes", label: "Clinical Notes", type: "text" };
const F_PLAN = { key: "plan", label: "Plan / Advice", type: "text" };
const F_NEXTVISIT = { key: "nextVisit", label: "Next Visit Date", type: "date" };
const F_RECURRENCE = { key: "recurrence", label: "Recurrence", type: "select", opts: ["No Recurrence", "Suspected", "Confirmed", "N/A"] };
const F_ONCREF = { key: "oncologyRef", label: "Oncology Referral", type: "select", opts: ["Referred", "Already Under Onco", "Not Indicated", "Pending"] };
// Lab fields
const F_HB = { key: "hb", label: "Hb (g/dL)", type: "number" };
const F_TLC = { key: "tlc", label: "TLC", type: "number" };
const F_CREAT = { key: "creatinine", label: "Creatinine", type: "number" };
const F_TBIL = { key: "tbil", label: "T. Bilirubin", type: "number" };
const F_AST = { key: "ast", label: "AST", type: "number" };
const F_ALT = { key: "alt", label: "ALT", type: "number" };
const F_ALP = { key: "alp", label: "ALP", type: "number" };
const F_RBS = { key: "rbs", label: "RBS", type: "number" };
const F_CA = { key: "calcium", label: "S. Calcium", type: "number" };
const F_PTH = { key: "pth", label: "PTH", type: "number" };
const F_TSH = { key: "tsh", label: "TSH", type: "number" };
const F_FT4 = { key: "ft4", label: "fT4", type: "number" };
const F_CEA = { key: "cea", label: "CEA", type: "number" };
const F_CA199 = { key: "ca199", label: "CA 19-9", type: "number" };
const F_AFP = { key: "afp", label: "AFP", type: "number" };
const F_INR = { key: "inr", label: "INR", type: "number" };

const FOLLOWUP_SCHEDULES = {
  "Cholecystectomy": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_SUTURE, F_PAIN, F_DIET, F_HPE, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_WOUND, F_DIET, { key: "symptoms", label: "Symptoms", type: "select", opts: ["None", "Bloating", "Diarrhoea", "Dyspepsia", "Pain", "Other"] }, F_TBIL, F_AST, F_ALT, F_ACTIVITY, F_NOTES, F_PLAN] },
  ],
  "CBD Exploration": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, { key: "tTubeStatus", label: "T-Tube Status", type: "select", opts: ["In Situ - Functioning", "Clamped", "Removed", "N/A"] }, { key: "tTubeCholangio", label: "T-Tube Cholangiogram", type: "select", opts: ["Done - Normal", "Done - Retained Stone", "Not Done Yet", "N/A"] }, F_TBIL, F_AST, F_ALT, F_ALP, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_WOUND, { key: "tTubeRemoved", label: "T-Tube Removed", type: "select", opts: ["Yes", "No - Planned", "N/A"] }, F_TBIL, F_AST, F_ALT, F_ALP, { key: "usgAbdomen", label: "USG Abdomen", type: "text" }, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [F_TBIL, F_ALT, F_ALP, { key: "mrcp", label: "MRCP", type: "text" }, F_NOTES, F_PLAN] },
  ],
  "Hernioplasty": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_PAIN, { key: "seroma", label: "Seroma / SSI", type: "select", opts: ["None", "Seroma - Small", "Seroma - Large / Aspirated", "SSI - Superficial", "SSI - Deep", "Other"] }, F_NOTES, F_PLAN] },
    { visit: 2, days: 42, label: "6 Weeks", fields: [F_WOUND, F_RECURRENCE, F_PAIN, F_ACTIVITY, F_NOTES, F_PLAN] },
  ],
  "Laparoscopic Hernia Repair": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_PAIN, F_ACTIVITY, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_RECURRENCE, F_PAIN, F_ACTIVITY, F_NOTES, F_PLAN] },
  ],
  "Appendicectomy": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_SUTURE, F_HPE, F_DIET, F_PAIN, F_NOTES, F_PLAN] },
  ],
  "Thyroidectomy": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_SUTURE, { key: "voice", label: "Voice Assessment", type: "select", opts: ["Normal", "Hoarseness - Mild", "Hoarseness - Significant", "Cord Palsy Suspected"] }, F_CA, F_PTH, F_HPE, { key: "thyroxineStarted", label: "Levothyroxine Started", type: "select", opts: ["Yes", "No - Not Needed", "No - Pending HPE", "Already On"] }, F_NOTES, F_PLAN] },
    { visit: 2, days: 42, label: "6 Weeks", fields: [F_WOUND, { key: "voice6w", label: "Voice Status", type: "select", opts: ["Normal", "Improved", "Persistent Hoarseness", "Worsened"] }, F_TSH, F_FT4, F_CA, { key: "thyroxineDose", label: "Thyroxine Dose (mcg)", type: "number" }, { key: "doseAdjust", label: "Dose Adjusted", type: "select", opts: ["No Change", "Increased", "Decreased", "Started"] }, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [F_TSH, F_FT4, { key: "neckUSG", label: "Neck USG", type: "text" }, F_ONCREF, F_NOTES, F_PLAN] },
  ],
  "Hemithyroidectomy": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_SUTURE, { key: "voice", label: "Voice", type: "select", opts: ["Normal", "Hoarseness"] }, F_HPE, F_NOTES, F_PLAN] },
    { visit: 2, days: 42, label: "6 Weeks", fields: [F_TSH, F_FT4, { key: "completionPlan", label: "Completion Thyroidectomy", type: "select", opts: ["Not Needed", "Planned", "Under Discussion", "Done"] }, F_NOTES, F_PLAN] },
  ],
  "Parathyroidectomy": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_SUTURE, F_CA, F_PTH, { key: "symptoms", label: "Hypocalcemia Sx", type: "select", opts: ["None", "Perioral Tingling", "Carpopedal Spasm", "Chvostek +ve", "Trousseau +ve"] }, { key: "caSupplements", label: "Ca/VitD Supplements", type: "text" }, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_CA, F_PTH, { key: "vitD", label: "Vit D Level", type: "number" }, F_NOTES, F_PLAN] },
  ],
  "Gastrectomy": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_DIET, { key: "weight", label: "Weight (kg)", type: "number" }, F_HPE, F_DRAIN, F_HB, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [{ key: "weight", label: "Weight (kg)", type: "number" }, F_DIET, F_HB, { key: "albumin", label: "Albumin", type: "number" }, F_ONCREF, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [{ key: "cect", label: "CECT Abdomen", type: "text" }, F_CEA, { key: "weight", label: "Weight (kg)", type: "number" }, F_NOTES, F_PLAN] },
  ],
  "Whipple Procedure": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_DRAIN, F_DRAINVOL, F_HPE, F_RBS, { key: "pancEnzymes", label: "Pancreatic Enzymes", type: "select", opts: ["Started - Adequate", "Started - Needs Increase", "Not Started", "Not Needed"] }, F_DIET, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_HB, F_TBIL, F_ALT, F_RBS, F_CA199, { key: "weight", label: "Weight (kg)", type: "number" }, F_ONCREF, { key: "chemoStarted", label: "Chemo Started", type: "select", opts: ["Yes", "Planned", "Not Indicated", "Deferred"] }, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [{ key: "cect", label: "CECT Abdomen", type: "text" }, F_CA199, F_RBS, { key: "weight", label: "Weight (kg)", type: "number" }, F_NOTES, F_PLAN] },
  ],
  "Colectomy": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_HPE, { key: "stomaStatus", label: "Stoma Status", type: "select", opts: ["Healthy", "Retracted", "Prolapsed", "Necrotic", "N/A"] }, F_DIET, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_WOUND, F_CEA, F_ONCREF, { key: "chemoStarted", label: "Chemo Started", type: "select", opts: ["Yes", "Planned", "Not Indicated", "Deferred"] }, F_NOTES, F_PLAN] },
    { visit: 3, days: 365, label: "1 Year", fields: [{ key: "colonoscopy", label: "Surveillance Colonoscopy", type: "text" }, { key: "cect", label: "CECT", type: "text" }, F_CEA, F_RECURRENCE, F_NOTES, F_PLAN] },
  ],
  "Anterior Resection": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_HPE, { key: "stomaStatus", label: "Stoma Status", type: "select", opts: ["Healthy", "Retracted", "Prolapsed", "N/A"] }, { key: "bowelFx", label: "Bowel Function", type: "select", opts: ["Normal", "Frequency", "Urgency", "Incontinence", "Constipation"] }, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_CEA, F_ONCREF, { key: "stomaReversal", label: "Stoma Reversal Plan", type: "select", opts: ["Planned", "Done", "Not Applicable", "Deferred"] }, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [{ key: "cect", label: "CECT Pelvis", type: "text" }, F_CEA, { key: "bowelFx", label: "Bowel Function", type: "select", opts: ["Normal", "LARS - Minor", "LARS - Major", "Improving"] }, F_NOTES, F_PLAN] },
  ],
  "Mastectomy": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_DRAIN, F_DRAINVOL, F_HPE, { key: "receptors", label: "ER/PR/HER2 Status", type: "text" }, { key: "armMobility", label: "Arm Mobility", type: "select", opts: ["Full ROM", "Mild Restriction", "Moderate Restriction", "Frozen"] }, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_WOUND, { key: "armMobility", label: "Arm Mobility", type: "select", opts: ["Full ROM", "Mild Restriction", "Moderate Restriction", "Frozen"] }, { key: "lymphedema", label: "Lymphedema", type: "select", opts: ["None", "Mild", "Moderate", "Severe"] }, F_ONCREF, { key: "chemoRT", label: "Chemo/RT Status", type: "select", opts: ["Chemo Started", "RT Started", "Both Started", "Planned", "Not Indicated"] }, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [{ key: "mammogram", label: "Mammogram / USG Contralateral", type: "text" }, { key: "lymphedema", label: "Lymphedema", type: "select", opts: ["None", "Mild", "Moderate", "Severe"] }, F_RECURRENCE, F_NOTES, F_PLAN] },
  ],
  "Breast Conservation Surgery": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, { key: "margins", label: "Margin Status", type: "select", opts: ["Clear", "Close (<2mm)", "Positive - Re-excision Planned", "Awaiting"] }, { key: "slnResult", label: "SLN Result", type: "select", opts: ["Negative", "Positive - ALND Planned", "Positive - No ALND", "Awaiting", "N/A"] }, F_HPE, F_NOTES, F_PLAN] },
    { visit: 2, days: 21, label: "3 Weeks", fields: [F_WOUND, { key: "radiationRef", label: "Radiation Oncology", type: "select", opts: ["Referred", "Started", "Planned", "Not Indicated"] }, { key: "oncotype", label: "Oncotype Dx Score", type: "number" }, F_NOTES, F_PLAN] },
  ],
  "Hemorrhoidectomy": [
    { visit: 1, days: 14, label: "2 Weeks", fields: [F_WOUND, F_PAIN, { key: "bleeding", label: "Bleeding", type: "select", opts: ["None", "Minimal", "Secondary Hemorrhage", "Significant"] }, { key: "continence", label: "Continence", type: "select", opts: ["Normal", "Minor Soiling", "Incontinence to Flatus", "Incontinence to Stool"] }, { key: "sitzBaths", label: "Sitz Baths", type: "select", opts: ["Compliant", "Irregular", "Not Doing"] }, F_NOTES, F_PLAN] },
    { visit: 2, days: 42, label: "6 Weeks", fields: [F_WOUND, F_PAIN, { key: "healing", label: "Healing", type: "select", opts: ["Complete", "Partial", "Delayed", "Non-healing"] }, { key: "continence", label: "Continence", type: "select", opts: ["Normal", "Minor Soiling", "Incontinence to Flatus", "Incontinence to Stool"] }, F_NOTES, F_PLAN] },
  ],
  "Fistulectomy": [
    { visit: 1, days: 14, label: "2 Weeks", fields: [F_WOUND, F_PAIN, { key: "setonStatus", label: "Seton Status", type: "select", opts: ["In Situ - Loose", "In Situ - Tight", "Removed", "N/A"] }, { key: "sitzBaths", label: "Sitz Baths", type: "select", opts: ["Compliant", "Irregular", "Not Doing"] }, F_NOTES, F_PLAN] },
    { visit: 2, days: 42, label: "6 Weeks", fields: [F_WOUND, { key: "healing", label: "Healing", type: "select", opts: ["Complete", "Partial", "Delayed", "Non-healing"] }, { key: "continence", label: "Continence", type: "select", opts: ["Normal", "Minor Soiling", "Incontinence"] }, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [F_RECURRENCE, { key: "mriPelvis", label: "MRI Pelvis", type: "text" }, F_NOTES, F_PLAN] },
  ],
  "Nephrectomy": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_CREAT, { key: "kft_urea", label: "Urea", type: "number" }, F_HPE, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_CREAT, { key: "usgAbdomen", label: "USG Abdomen", type: "text" }, F_ONCREF, F_NOTES, F_PLAN] },
  ],
  "Excision Biopsy": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_SUTURE, F_HPE, F_PLAN, F_NOTES] },
  ],
  "Incision and Drainage": [
    { visit: 1, days: 5, label: "5 Days", fields: [F_WOUND, { key: "cultureResult", label: "Culture & Sensitivity", type: "text" }, { key: "antibiotics", label: "Antibiotics", type: "text" }, F_NOTES, F_PLAN] },
    { visit: 2, days: 14, label: "2 Weeks", fields: [F_WOUND, { key: "healing", label: "Healing", type: "select", opts: ["Complete", "Partial", "Needs Secondary Closure", "Non-healing"] }, F_NOTES, F_PLAN] },
  ],
  "_malignancy": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_DRAIN, F_HPE, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_WOUND, F_ONCREF, F_HB, F_TBIL, F_CREAT, F_NOTES, F_PLAN] },
    { visit: 3, days: 90, label: "3 Months", fields: [{ key: "imaging", label: "Imaging", type: "text" }, F_RECURRENCE, F_NOTES, F_PLAN] },
  ],
  "_laparoscopic": [
    { visit: 1, days: 7, label: "1 Week", fields: [F_WOUND, F_PAIN, F_DIET, F_HPE, F_NOTES, F_PLAN] },
  ],
  "_open_major": [
    { visit: 1, days: 10, label: "10 Days", fields: [F_WOUND, F_SUTURE, F_PAIN, F_DIET, F_NOTES, F_PLAN] },
    { visit: 2, days: 30, label: "1 Month", fields: [F_WOUND, F_ACTIVITY, F_NOTES, F_PLAN] },
  ],
  "_minor": [
    { visit: 1, days: 5, label: "5 Days", fields: [F_WOUND, F_PAIN, F_NOTES, F_PLAN] },
  ],
};

const getFollowUpSchedule = (patient, customTemplates, researchProtocols) => {
  const proc = patient.opDetails?.primaryProcedure || patient.plannedProcedure || "";
  const diag = patient.diagnosis || patient.clinical?.preOp?.primaryDx || patient.malignancySite || "";
  const isMalig = patient.type === "malignancy";
  const isLap = (patient.opDetails?.opAccessMode || "").toLowerCase().includes("lap");
  const procLow = proc.toLowerCase();
  const diagLow = diag.toLowerCase();
  const ptProtocolNames = (patient.researchProtocols || []).map(rpId => {
    const rp = (researchProtocols || []).find(r => r.id === rpId);
    return rp ? rp.name.toLowerCase() : "";
  }).filter(Boolean);
  // Check custom templates first (higher priority)
  for (const tpl of (customTemplates || [])) {
    const mp = (tpl.matchProcedure || "").toLowerCase();
    const md = (tpl.matchDiagnosis || "").toLowerCase();
    const mpr = (tpl.matchProtocol || "").toLowerCase();
    if (mpr && ptProtocolNames.includes(mpr)) return { key: tpl.name, schedule: tpl.visits, isCustom: true };
    if (mp && (procLow === mp || procLow.includes(mp))) return { key: tpl.name, schedule: tpl.visits, isCustom: true };
    if (md && (diagLow === md || diagLow.includes(md))) return { key: tpl.name, schedule: tpl.visits, isCustom: true };
    const malSite = (patient.malignancySite || patient.clinical?.preOp?.malSite || "").toLowerCase();
    if (md && malSite === md) return { key: tpl.name, schedule: tpl.visits, isCustom: true };
  }
  for (const key of Object.keys(FOLLOWUP_SCHEDULES)) {
    if (key.startsWith("_")) continue;
    if (procLow.includes(key.toLowerCase()) || key.toLowerCase().includes(procLow.replace("laparoscopic ", "").replace("open ", ""))) return { key, schedule: FOLLOWUP_SCHEDULES[key] };
  }
  for (const key of Object.keys(FOLLOWUP_SCHEDULES)) {
    if (key.startsWith("_")) continue;
    const words = key.toLowerCase().split(" ").filter(w => w.length > 3);
    if (words.some(w => procLow.includes(w))) return { key, schedule: FOLLOWUP_SCHEDULES[key] };
  }
  if (isMalig) return { key: "_malignancy", schedule: FOLLOWUP_SCHEDULES["_malignancy"] };
  if (isLap) return { key: "_laparoscopic", schedule: FOLLOWUP_SCHEDULES["_laparoscopic"] };
  if (procLow.includes("excision") || procLow.includes("biopsy") || procLow.includes("drainage")) return { key: "_minor", schedule: FOLLOWUP_SCHEDULES["_minor"] };
  return { key: "_open_major", schedule: FOLLOWUP_SCHEDULES["_open_major"] };
};

function FollowUpSection({ patient, onSave, customTemplates, researchProtocols }) {
  const existing = patient.followUps || [];
  const existingHpe = patient.postOp?.hpeReport || "";
  const [fups, setFups] = useState([...existing]);
  const [hpe, setHpe] = useState(existingHpe);
  const [hpeEdit, setHpeEdit] = useState(false);
  const [openVisit, setOpenVisit] = useState(null);
  const inp4 = { width: "100%", padding: "7px 10px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" };
  const lbl4 = { display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#475569", marginBottom: 2, textTransform: "uppercase", letterSpacing: "0.04em" };

  const { key: schedKey, schedule, isCustom } = getFollowUpSchedule(patient, customTemplates, researchProtocols);
  const surgDate = patient.opDetails?.surgeryDateActual || "";
  const calcDate = (days) => { if (!surgDate) return ""; const d = new Date(surgDate + "T00:00:00"); d.setDate(d.getDate() + days); return d.toISOString().slice(0, 10); };

  const addFup = () => { if (fups.length >= 6) return; setFups([...fups, { date: "", remarks: "", condition: "", data: {}, expired: false, readmission: false, complication: false }]); setOpenVisit(fups.length); };
  const addFromSchedule = (visit, visitNum) => {
    const visitLabel = `Follow-Up ${visitNum}`;
    if (fups.find(f => f.visitLabel === visitLabel)) return;
    const newIdx = fups.length;
    setFups([...fups, { date: calcDate(visit.days), visitLabel, scheduleTiming: visit.label, scheduleDays: visit.days, remarks: "", condition: "", data: {}, fieldDefs: visit.fields, expired: false, readmission: false, complication: false }]);
    setOpenVisit(newIdx);
  };
  const updFup = (i, k, v) => { const n = [...fups]; n[i] = { ...n[i], [k]: v }; setFups(n); };
  const updData = (i, k, v) => { const n = [...fups]; n[i] = { ...n[i], data: { ...(n[i].data || {}), [k]: v } }; setFups(n); };
  const removeFup = (i) => { setFups(fups.filter((_, j) => j !== i)); if (openVisit === i) setOpenVisit(null); else if (openVisit > i) setOpenVisit(openVisit - 1); };

  const filledCount = (f) => { const d = f.data || {}; return Object.values(d).filter(v => v && v !== "").length; };
  const totalFields = (f) => { return (f.fieldDefs || []).length; };

  return <div style={{ marginBottom: 12, border: "2px solid #1565c0", borderRadius: 10, overflow: "hidden" }}>
    <div style={{ padding: "8px 14px", background: "#e3f2fd08", fontWeight: 700, fontSize: "0.82rem", color: "#1565c0", borderBottom: "1px solid #e2e8f0", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <span>{"📅"} Follow-Ups & Outcomes</span>
      <div style={{ display: "flex", gap: 6 }}>
        {!hpeEdit && <button onClick={() => setHpeEdit(true)} style={{ padding: "3px 10px", borderRadius: 6, border: "1px solid #ce93d8", background: "#f3e5f5", fontSize: "0.68rem", fontWeight: 600, color: "#6a1b9a", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"📝"} {existingHpe ? "Edit" : "Add"} HPE Report</button>}
      </div>
    </div>
    <div style={{ padding: "12px 14px" }}>
      {hpeEdit && <div style={{ marginBottom: 12, padding: 10, background: "#faf4ff", borderRadius: 8, border: "1px solid #e1bee7" }}>
        <label style={lbl4}>HPE Report</label>
        <textarea style={{ ...inp4, minHeight: 50, resize: "vertical", borderColor: "#ce93d8" }} value={hpe} onChange={e => setHpe(e.target.value)} placeholder="Histopathology findings..." />
        <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", marginTop: 6 }}>
          <button onClick={() => setHpeEdit(false)} style={{ padding: "4px 12px", border: "1px solid #e2e8f0", borderRadius: 6, background: "#fff", fontSize: "0.72rem", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Cancel</button>
          <button onClick={() => { onSave({ followUps: fups, hpeReport: hpe }); setHpeEdit(false); }} style={{ padding: "4px 12px", border: "none", borderRadius: 6, background: "#6a1b9a", color: "#fff", fontSize: "0.72rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Save HPE</button>
        </div>
      </div>}
      {existingHpe && !hpeEdit && <div style={{ marginBottom: 10, padding: "6px 10px", background: "#faf4ff", borderRadius: 6, border: "1px solid #e1bee7" }}>
        <div style={lbl4}>HPE Report</div>
        <div style={{ fontSize: "0.82rem", color: "#1e293b" }}>{existingHpe}</div>
      </div>}

      {/* Suggested follow-up schedule */}
      {schedule.length > 0 && <div style={{ marginBottom: 12, padding: "8px 12px", background: "#fff8e1", borderRadius: 8, border: "1px solid #ffe082" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
          <div style={{ fontSize: "0.7rem", fontWeight: 700, color: "#f57f17" }}>{"💡"} Follow-Up Protocol — {schedKey.startsWith("_") ? (schedKey === "_malignancy" ? "Malignancy" : schedKey === "_laparoscopic" ? "Laparoscopic Surgery" : "General Surgery") : schedKey} {isCustom && <span style={{ fontSize: "0.6rem", padding: "1px 6px", borderRadius: 4, background: "#e3f2fd", color: "#1565c0", fontWeight: 600, marginLeft: 4 }}>Custom</span>}</div>
          {schedule.length > 1 && !schedule.every((v, i) => fups.find(f => f.visitLabel === `Follow-Up ${i + 1}`)) && <button onClick={() => {
            const toAdd = schedule.filter((v, i) => !fups.find(f => f.visitLabel === `Follow-Up ${i + 1}`));
            const newFups = [...fups];
            toAdd.forEach((v, j) => {
              const visitNum = schedule.indexOf(v) + 1;
              newFups.push({ date: calcDate(v.days), visitLabel: `Follow-Up ${visitNum}`, scheduleTiming: v.label, scheduleDays: v.days, remarks: "", condition: "", data: {}, fieldDefs: v.fields, expired: false, readmission: false, complication: false });
            });
            setFups(newFups);
            setOpenVisit(fups.length);
          }} style={{ padding: "3px 10px", borderRadius: 6, border: "1px solid #f57f17", background: "#fff8e1", fontSize: "0.64rem", fontWeight: 600, color: "#f57f17", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Add All Visits ({schedule.length})</button>}
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {schedule.map((v, i) => {
            const visitNum = i + 1;
            const visitLabel = `Follow-Up ${visitNum}`;
            const alreadyAdded = fups.find(f => f.visitLabel === visitLabel);
            const expectedDate = calcDate(v.days);
            return <button key={i} onClick={() => !alreadyAdded && (() => {
              if (fups.find(f => f.visitLabel === visitLabel)) return;
              const newIdx = fups.length;
              setFups([...fups, { date: expectedDate, visitLabel, scheduleTiming: v.label, scheduleDays: v.days, remarks: "", condition: "", data: {}, fieldDefs: v.fields, expired: false, readmission: false, complication: false }]);
              setOpenVisit(newIdx);
            })()} disabled={!!alreadyAdded}
              style={{ padding: "6px 12px", borderRadius: 7, border: alreadyAdded ? "1.5px solid #a5d6a7" : "1.5px solid #ffe082", background: alreadyAdded ? "#e8f5e9" : "#fff", cursor: alreadyAdded ? "default" : "pointer", fontFamily: "'Outfit',sans-serif", fontSize: "0.72rem", fontWeight: 600, color: alreadyAdded ? "#2e7d32" : "#f57f17", opacity: alreadyAdded ? 0.7 : 1, textAlign: "left", lineHeight: 1.3 }}>
              <div>{alreadyAdded ? "✓ " : "+ "}Follow-Up {visitNum}</div>
              <div style={{ fontSize: "0.58rem", fontWeight: 400, color: alreadyAdded ? "#64748b" : "#a1887f", marginTop: 1 }}>
                {v.label} · {v.fields.length} fields{expectedDate && ` · ${new Date(expectedDate + "T00:00:00").toLocaleDateString("en-IN", { day: "2-digit", month: "short" })}`}
              </div>
            </button>;
          })}
        </div>
      </div>}

      {fups.length === 0 && !hpeEdit && <div style={{ color: "#94a3b8", fontSize: "0.82rem", textAlign: "center", padding: 12 }}>No follow-ups recorded. Add a visit from the schedule above or create a custom one below.</div>}

      <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: fups.length > 0 ? 8 : 0 }}>
        {fups.length < 6 && <button onClick={addFup} style={{ padding: "3px 10px", borderRadius: 6, border: "1px solid #90caf9", background: "#e3f2fd", fontSize: "0.68rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>+ Add Custom Follow-Up</button>}
      </div>

      {fups.map((f, i) => {
        const isOpen = openVisit === i;
        const fields = f.fieldDefs || [];
        const filled = filledCount(f);
        const total = totalFields(f);
        const data = f.data || {};
        const hasSummary = filled > 0 || f.condition || f.remarks;

        return (
        <div key={i} style={{ marginBottom: 10, borderRadius: 8, border: isOpen ? "2px solid #1565c0" : f.completed ? "1.5px solid #a5d6a7" : f.expired ? "1.5px solid #ef9a9a" : "1px solid #e2e8f0", overflow: "hidden", opacity: f.completed && !isOpen ? 0.85 : 1 }}>
          {/* Visit header — clickable to expand/collapse */}
          <div onClick={() => setOpenVisit(isOpen ? null : i)} style={{ padding: "8px 10px", background: isOpen ? "#e3f2fd" : "#f8fafc", cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: "0.78rem", fontWeight: 700, color: "#1565c0" }}>{f.visitLabel || `Follow-Up ${i + 1}`}</span>
              {f.scheduleTiming && <span style={{ fontSize: "0.6rem", padding: "1px 6px", borderRadius: 4, background: "#f5f5f5", color: "#64748b", fontWeight: 500 }}>{f.scheduleTiming}</span>}
              {f.date && <span style={{ fontSize: "0.68rem", color: "#64748b" }}>{new Date(f.date + "T00:00:00").toLocaleDateString("en-IN", { day: "2-digit", month: "short", year: "numeric" })}</span>}
              {total > 0 && <span style={{ fontSize: "0.62rem", padding: "1px 6px", borderRadius: 8, background: filled === total && total > 0 ? "#e8f5e9" : filled > 0 ? "#fff3e0" : "#f1f5f9", color: filled === total && total > 0 ? "#2e7d32" : filled > 0 ? "#e65100" : "#94a3b8", fontWeight: 600 }}>{filled}/{total}</span>}
              {f.condition && <span style={{ fontSize: "0.62rem", padding: "1px 6px", borderRadius: 8, background: f.condition === "Improved" ? "#e8f5e9" : f.condition === "Worse" || f.condition === "Deteriorated" ? "#ffebee" : "#f5f5f5", color: f.condition === "Improved" ? "#2e7d32" : f.condition === "Worse" || f.condition === "Deteriorated" ? "#c62828" : "#475569", fontWeight: 600 }}>{f.condition}</span>}
            </div>
            <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
              {f.completed && <span style={{ fontSize: "0.6rem", background: "#e8f5e9", color: "#2e7d32", padding: "1px 5px", borderRadius: 4, fontWeight: 600 }}>{"✓"} Done</span>}
              {f.expired && <span style={{ fontSize: "0.6rem", background: "#ffebee", color: "#c62828", padding: "1px 5px", borderRadius: 4, fontWeight: 600 }}>Expired</span>}
              {f.complication && <span style={{ fontSize: "0.6rem", background: "#fff3e0", color: "#e65100", padding: "1px 5px", borderRadius: 4, fontWeight: 600 }}>Complication</span>}
              {f.readmission && <span style={{ fontSize: "0.6rem", background: "#fce4ec", color: "#c62828", padding: "1px 5px", borderRadius: 4, fontWeight: 600 }}>Readmitted</span>}
              {!f.completed && !f.expired && f.date && new Date(f.date) < new Date() && filled === 0 && <span style={{ fontSize: "0.6rem", background: "#fff3e0", color: "#e65100", padding: "1px 5px", borderRadius: 4, fontWeight: 600 }}>Overdue</span>}
              <span style={{ fontSize: "0.7rem", color: "#94a3b8" }}>{isOpen ? "▲" : "▼"}</span>
            </div>
          </div>

          {/* Compact summary when collapsed */}
          {!isOpen && hasSummary && <div style={{ padding: "4px 10px 6px", fontSize: "0.72rem", color: "#475569", display: "flex", flexWrap: "wrap", gap: "2px 10px" }}>
            {Object.entries(data).filter(([, v]) => v && v !== "").map(([k, v]) => {
              const fd = fields.find(ff => ff.key === k);
              return <span key={k}><b>{fd?.label || k}:</b> {v}</span>;
            })}
            {f.remarks && <span><b>Remarks:</b> {f.remarks}</span>}
          </div>}

          {/* Expanded form */}
          {isOpen && <div style={{ padding: "10px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "140px 1fr 160px", gap: 8, marginBottom: 8 }}>
              <div><label style={lbl4}>Date</label><input style={inp4} type="date" value={f.date} onChange={e => updFup(i, "date", e.target.value)} /></div>
              <div><label style={lbl4}>General Remarks</label><input style={inp4} value={f.remarks} onChange={e => updFup(i, "remarks", e.target.value)} placeholder="Overall impression..." /></div>
              <div><label style={lbl4}>Condition</label><select style={inp4} value={f.condition} onChange={e => updFup(i, "condition", e.target.value)}><option value="">Select...</option>{FOLLOWUP_CONDITIONS.map(c => <option key={c}>{c}</option>)}</select></div>
            </div>

            {/* Procedure-specific fields */}
            {fields.length > 0 && <div style={{ padding: "8px 10px", background: "#f0f9ff", borderRadius: 8, border: "1px solid #b3e5fc", marginBottom: 8 }}>
              <div style={{ fontSize: "0.62rem", fontWeight: 700, color: "#0277bd", marginBottom: 6, textTransform: "uppercase" }}>Clinical Assessment</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: "6px 10px" }}>
                {fields.map(fd => {
                  const val = data[fd.key] || "";
                  if (fd.type === "select") return <div key={fd.key}>
                    <label style={lbl4}>{fd.label}</label>
                    <select style={{ ...inp4, background: val ? "#e8f5e9" : "#fff" }} value={val} onChange={e => updData(i, fd.key, e.target.value)}>
                      <option value="">Select...</option>
                      {fd.opts.map(o => <option key={o} value={o}>{o}</option>)}
                    </select>
                  </div>;
                  if (fd.type === "number") return <div key={fd.key}>
                    <label style={lbl4}>{fd.label}</label>
                    <input style={{ ...inp4, background: val ? "#e8f5e9" : "#fff" }} type="number" step="any" value={val} onChange={e => updData(i, fd.key, e.target.value)} placeholder="—" />
                  </div>;
                  if (fd.type === "date") return <div key={fd.key}>
                    <label style={lbl4}>{fd.label}</label>
                    <input style={{ ...inp4, background: val ? "#e8f5e9" : "#fff" }} type="date" value={val} onChange={e => updData(i, fd.key, e.target.value)} />
                  </div>;
                  return <div key={fd.key} style={{ gridColumn: (fd.key === "notes" || fd.key === "plan") ? "1 / -1" : undefined }}>
                    <label style={lbl4}>{fd.label}</label>
                    <input style={{ ...inp4, background: val ? "#e8f5e9" : "#fff" }} value={val} onChange={e => updData(i, fd.key, e.target.value)} placeholder={fd.label + "..."} />
                  </div>;
                })}
              </div>
            </div>}

            <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 6, paddingTop: 6, borderTop: "1px solid #e2e8f0" }}>
              <label style={{ display: "flex", alignItems: "center", gap: 4, fontSize: "0.72rem", color: f.completed ? "#2e7d32" : "#94a3b8", fontWeight: f.completed ? 600 : 400, cursor: "pointer" }}>
                <input type="checkbox" checked={!!f.completed} onChange={e => updFup(i, "completed", e.target.checked)} style={{ accentColor: "#2e7d32" }} /> {"✓"} Visit Completed
              </label>
              {[["Expired","expired","#c62828"], ["Readmission","readmission","#e65100"], ["Complication","complication","#ff8f00"]].map(([l, k, clr]) => (
                <label key={k} style={{ display: "flex", alignItems: "center", gap: 4, fontSize: "0.72rem", color: f[k] ? clr : "#94a3b8", fontWeight: f[k] ? 600 : 400, cursor: "pointer" }}>
                  <input type="checkbox" checked={!!f[k]} onChange={e => updFup(i, k, e.target.checked)} style={{ accentColor: clr }} /> {l}
                </label>
              ))}
              <button onClick={() => removeFup(i)} style={{ marginLeft: "auto", border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.72rem", fontWeight: 600 }}>{"🗑"} Remove</button>
            </div>
          </div>}
        </div>
        );
      })}

      {fups.length > 0 && <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 8 }}>
        <button onClick={() => onSave({ followUps: fups, hpeReport: hpe })} style={{ padding: "8px 18px", background: "linear-gradient(135deg,#1565c0,#1976d2)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.8rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>{"💾"} Save Follow-Ups</button>
      </div>}
    </div>
  </div>;
}


function DischargeCertificate({ patient, onClose }) {
  const p = patient;
  const cl = p.clinical || {};
  const od = p.opDetails || {};
  const pp = p.postOp || {};
  const preOp = cl.preOp || {};

  // Build diagnosis string (pre-op)
  const buildDx = () => {
    if (preOp.lesionType === "malignancy" || p.type === "malignancy") {
      const histo = preOp.preOpHistology === "Others" ? preOp.histologyOther : preOp.preOpHistology;
      return [histo, preOp.malSite || p.malignancySite].filter(Boolean).join(" ") || "Malignancy";
    }
    let dx = preOp.primaryDx || p.diagnosis || "";
    if (preOp.primaryLaterality) dx += " (" + preOp.primaryLaterality + ")";
    if (preOp.secondaryDx) { dx += " + " + preOp.secondaryDx; if (preOp.secondaryLaterality) dx += " (" + preOp.secondaryLaterality + ")"; }
    return dx;
  };

  // Build final/post-op diagnosis string
  const fd = pp.finalDx || {};
  const buildFinalDx = () => {
    if (!fd.type) return "";
    if (fd.type === "malignancy") {
      const histo = fd.histology === "Others" ? fd.histologyOther : fd.histology;
      return [histo, fd.malSite].filter(Boolean).join(" ") + (fd.pathStage ? " (" + fd.pathStage + ")" : "");
    }
    let dx = fd.primaryDx || "";
    if (fd.primaryLaterality) dx += " (" + fd.primaryLaterality + ")";
    if (fd.secondaryDx) { dx += " + " + fd.secondaryDx; if (fd.secondaryLaterality) dx += " (" + fd.secondaryLaterality + ")"; }
    return dx;
  };
  const finalDxStr = buildFinalDx();

  const proc = od.primaryProcedure || p.plannedProcedure || "";
  const access = od.opAccessMode === "Other" ? od.opAccessOther : (od.opAccessMode || "");
  const surgeon = od.operatingSurgeon === "__other" ? od.surgeonOther : (od.operatingSurgeon || "");
  const asst1 = od.firstAssistant === "__other" ? od.assistantOther : (od.firstAssistant || "");
  const asst2 = od.secondAssistant === "__other" ? od.assistant2Other : (od.secondAssistant || "");
  const asst3 = od.thirdAssistant === "__other" ? od.thirdAssistantOther : (od.thirdAssistant || "");
  const asst4 = od.fourthAssistant === "__other" ? od.fourthAssistantOther : (od.fourthAssistant || "");
  const asst5 = od.fifthAssistant === "__other" ? od.fifthAssistantOther : (od.fifthAssistant || "");
  const assistants = [asst1, asst2, asst3, asst4, asst5].filter(Boolean).join(", ");
  const complaints = (cl.chiefComplaints || []).filter(Boolean).join(", ");
  const exam = [cl.pulse && ("Pulse: " + cl.pulse + "/min"), cl.bp && ("BP: " + cl.bp), cl.spo2 && ("SpO2: " + cl.spo2 + "%"), cl.abdominalFindings && ("Abdomen: " + cl.abdominalFindings)].filter(Boolean).join(". ");
  const comorbStr = [...(cl.comorbidities || []), cl.comorbidOther].filter(Boolean).join(", ");

  const investStr = [cl.cbc?.hb && ("Hb: " + cl.cbc.hb), cl.cbc?.tlc && ("TLC: " + cl.cbc.tlc), cl.cbc?.plt && ("PLT: " + cl.cbc.plt), cl.kft?.creatinine && ("Creat: " + cl.kft.creatinine), cl.kft?.na && ("Na: " + cl.kft.na), cl.kft?.k && ("K: " + cl.kft.k), cl.lft?.tbil && ("T.Bil: " + cl.lft.tbil), cl.lft?.ast && ("AST: " + cl.lft.ast), cl.lft?.alt && ("ALT: " + cl.lft.alt), cl.glucose?.fbs && ("FBS: " + cl.glucose.fbs), cl.glucose?.hba1c && ("HbA1c: " + cl.glucose.hba1c), cl.coagulation?.inr && ("INR: " + cl.coagulation.inr), cl.serology?.hiv && ("HIV: " + cl.serology.hiv), cl.serology?.hbsag && ("HBsAg: " + cl.serology.hbsag)].filter(Boolean).join(", ");

  const imagingArr = [...IMAGING_KEYS, ...ENDO_KEYS].map(k => { const img = cl[k]; if (!img) return null; const obj = typeof img === "object" ? img : { done: true, findings: img }; if (!obj.done && !obj.findings) return null; const labels = { ...IMAGING_LABELS, ...ENDO_LABELS }; return [labels[k], obj.region && ("(" + obj.region + ")"), obj.findings].filter(Boolean).join(" "); }).filter(Boolean).join("; ");
  const pathoStr = PATHO_KEYS.map(k => { const img = cl[k]; if (!img) return null; const obj = typeof img === "object" ? img : { done: true, findings: img }; if (!obj.done && !obj.findings) return null; return [PATHO_LABELS[k], obj.site && ("(" + obj.site + ")"), obj.findings].filter(Boolean).join(" "); }).filter(Boolean).join("; ");

  const findings = (od.intraFindings || []).filter(Boolean).join("; ");

  // Build post-op stay string
  const drainRemStr = (pp.drainRemoval || []).map(r => { const dr = (od.drainList || [])[r.drainIdx]; return (dr ? [dr.type, dr.site].filter(Boolean).join(" ") : ("Drain " + (r.drainIdx + 1))) + ": " + (r.pod || ""); }).join(", ");
  const postOpParts = [
    pp.flatusDay && ("Flatus: " + pp.flatusDay),
    pp.bowelsDay && ("Bowels: " + pp.bowelsDay),
    pp.oralsDay && ("Orals: " + pp.oralsDay),
    pp.ambulationDay && ("Ambulation: " + pp.ambulationDay),
    drainRemStr && ("Drain removal: " + drainRemStr),
    !drainRemStr && pp.drainRemovalDay && ("Drain removed: POD " + pp.drainRemovalDay),
    (pp.rylesRemoval || pp.rylesRemovalDay) && ("RT: " + (pp.rylesRemoval || ("POD " + pp.rylesRemovalDay))),
    (pp.catheterRemoval || pp.catheterRemovalDay) && ("Catheter: " + (pp.catheterRemoval || ("POD " + pp.catheterRemovalDay))),
    (pp.complications || []).filter(c => c && c !== "None").length > 0 && ("Complications: " + pp.complications.filter(c => c && c !== "None").join(", ")),
  ].filter(Boolean).join(". ");

  const admDate = p.admittedAt ? new Date(p.admittedAt).toLocaleDateString("en-IN", { day: "2-digit", month: "2-digit", year: "numeric" }) : "";
  const disDate = p.dischargeDate ? new Date(p.dischargeDate + "T00:00:00").toLocaleDateString("en-IN", { day: "2-digit", month: "2-digit", year: "numeric" }) : new Date().toLocaleDateString("en-IN", { day: "2-digit", month: "2-digit", year: "numeric" });

  const printRef = React.useRef(null);

  const doPrint = () => {
    const el = printRef.current;
    if (!el) return;
    const w = window.open("", "_blank", "width=800,height=1000");
    w.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Discharge Summary - ${p.name}</title>
<style>
@page { size: A4; margin: 1.6cm 1.4cm; }
* { box-sizing: border-box; }
body { font-family: 'Times New Roman', serif; font-size: 13px; color: #000; line-height: 1.5; margin: 0; padding: 16px; }
b { font-weight: 700; }
span[contenteditable] { border-bottom: none !important; }
@media print {
  body { padding: 0; }
  .no-print { display: none !important; }
  span[contenteditable] { border-bottom: none !important; }
}
</style></head><body>`);
    w.document.write(el.innerHTML);
    w.document.write("</body></html>");
    w.document.close();
    setTimeout(() => { w.print(); }, 300);
  };

  const E = ({ val, ph, wide }) => {
    return <span contentEditable suppressContentEditableWarning style={{ borderBottom: "1px dotted #999", minWidth: wide ? 200 : 60, display: "inline-block", padding: "0 2px", outline: "none" }}>{val || ph || "________"}</span>;
  };

  const ovStyle = { position: "fixed", top: 0, left: 0, right: 0, bottom: 0, zIndex: 9999, background: "#f5f5f5", display: "flex", flexDirection: "column" };
  const toolStyle = { padding: "8px 16px", background: "#fff", borderBottom: "2px solid #e0e0e0", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, flexShrink: 0 };
  const pageStyle = { flex: 1, overflow: "auto", padding: "20px", display: "flex", justifyContent: "center" };
  const paperStyle = { width: "210mm", minHeight: "297mm", background: "#fff", padding: "1.8cm 1.5cm", boxShadow: "0 2px 20px rgba(0,0,0,0.15)", fontFamily: "'Times New Roman', serif", fontSize: "13px", color: "#000", lineHeight: "1.55" };

  const R = ({ margin }) => <div style={{ margin: margin || "3px 0", minHeight: 16 }}></div>;
  const Sec = ({ children }) => <div style={{ fontWeight: 700, textDecoration: "underline", margin: "8px 0 3px", fontSize: 13, letterSpacing: "0.3px" }}>{children}</div>;
  const Row = ({ children }) => <div style={{ margin: "2px 0", minHeight: 16, lineHeight: 1.5 }}>{children}</div>;
  const Lbl = ({ children }) => <span style={{ fontWeight: 700 }}>{children}</span>;
  const Pair = ({ children }) => <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 4, margin: "2px 0" }}>{children}</div>;

  return <div style={ovStyle}>
    <div style={toolStyle} className="no-print">
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <button onClick={onClose} style={{ padding: "6px 16px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.82rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"\u2190"} Back</button>
        <span style={{ fontWeight: 700, fontSize: "0.88rem", color: "#1e293b", fontFamily: "'Outfit',sans-serif" }}>Discharge Summary {"\u2014"} {p.name}</span>
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        <span style={{ fontSize: "0.68rem", color: "#94a3b8", alignSelf: "center" }}>Click any field to edit before printing</span>
        <button onClick={doPrint} style={{ padding: "8px 20px", background: "linear-gradient(135deg,#6a1b9a,#8e24aa)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.84rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"\uD83D\uDDA8\uFE0F"} Print / Save PDF</button>
      </div>
    </div>
    <div style={pageStyle}>
      <div ref={printRef} style={paperStyle}>
        {/* ── HEADER ── */}
        <div style={{ textAlign: "center", marginBottom: 6, borderBottom: "2px solid #000", paddingBottom: 6 }}>
          <div style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.35, letterSpacing: "0.5px" }}>DEPARTMENT OF MEDICAL RECORDS</div>
          <div style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.35 }}>GOVERNMENT S.M.H.S. HOSPITAL, SRINAGAR, KASHMIR</div>
          <div style={{ fontSize: 10, fontWeight: 400, lineHeight: 1.3 }}>(An Associate Hospital of Govt. Medical College, Srinagar)</div>
          <div style={{ fontSize: 15, fontWeight: 700, marginTop: 4, textDecoration: "underline", letterSpacing: "1px" }}>DISCHARGE SUMMARY</div>
        </div>

        {/* ── INSTITUTIONAL ROW ── */}
        <Pair><span>No. <E val="" ph="________"/></span><span style={{ fontWeight: 600 }}>Department Of General Surgery</span><span>M.R.D.No. <b><E val={cl.mrd || ""} ph="________"/></b></span></Pair>
        <Pair><span>Head of Unit: <b>Prof. (Dr.) Iqbal Saleem Mir</b></span><span>SU-1</span><span>Ward No. 18</span><span>Bed No. <E val="" ph="______"/></span></Pair>

        <div style={{ borderTop: "1px solid #000", margin: "5px 0" }}></div>

        {/* ── PATIENT PARTICULARS ── */}
        <Pair>
          <span><Lbl>Name:</Lbl> <b><E val={p.name}/></b></span>
          <span><Lbl>Age/Sex:</Lbl> <E val={p.age + "y / " + p.sex}/></span>
          <span><Lbl>Phone:</Lbl> <E val={p.phone}/></span>
        </Pair>
        <Pair>
          <span><Lbl>Parentage:</Lbl> <E val={cl.parentage || ""} ph="________________" wide/></span>
          <span><Lbl>Occupation:</Lbl> <E val={cl.occupation || ""} ph="________"/></span>
        </Pair>
        <Row><Lbl>Address:</Lbl> <E val={[cl.district, cl.state].filter(Boolean).join(", ")} ph="________________" wide/></Row>
        <Pair>
          <span><Lbl>Date of Admission:</Lbl> <E val={admDate}/></span>
          <span><Lbl>Date of Surgery:</Lbl> <E val={od.surgeryDateActual ? fmtD(od.surgeryDateActual) : ""}/></span>
          <span><Lbl>Date of Discharge:</Lbl> <E val={disDate}/></span>
        </Pair>

        {/* ── DIAGNOSIS ── */}
        <Sec>DIAGNOSIS:</Sec>
        <Row><E val={finalDxStr || buildDx()} ph="Enter diagnosis..." wide/></Row>
        {finalDxStr && finalDxStr !== buildDx() && <Row style={{ fontSize: "0.72rem", color: "#64748b" }}><Lbl>Pre-Op Diagnosis:</Lbl> <E val={buildDx()} /></Row>}
        {fd.notes && <Row><Lbl>Notes:</Lbl> <E val={fd.notes} wide/></Row>}
        {comorbStr && <Row><Lbl>Co-morbidities:</Lbl> <E val={comorbStr} wide/></Row>}

        {/* ── CASE SUMMARY ── */}
        <Sec>CASE SUMMARY:</Sec>
        <Row><Lbl>Chief Complaints:</Lbl> <E val={complaints} ph="Enter complaints..." wide/></Row>
        <Row><Lbl>Examination:</Lbl> <E val={exam} ph="Enter findings..." wide/></Row>

        {/* ── INVESTIGATIONS ── */}
        <Sec>INVESTIGATIONS:</Sec>
        <Row><E val={investStr} ph="Lab results..." wide/></Row>
        {imagingArr && <Row><Lbl>Imaging/Endoscopy:</Lbl> <E val={imagingArr} wide/></Row>}
        {pathoStr && <Row><Lbl>Pathology:</Lbl> <E val={pathoStr} wide/></Row>}
        {pp.postOpImaging && <Row><Lbl>Post-Op Imaging:</Lbl> <E val={pp.postOpImaging} wide/></Row>}
        {pp.postOpInvestigations && <Row><E val={pp.postOpInvestigations} wide/></Row>}

        {/* ── TREATMENT / MANAGEMENT ── */}
        <Sec>TREATMENT / MANAGEMENT:</Sec>
        <Row><Lbl>Surgery:</Lbl> <E val={(access ? access + " " : "") + proc} wide/></Row>
        <Pair>
          <span><Lbl>Operating Surgeon:</Lbl> <E val={surgeon}/></span>
          <span><Lbl>Assistant(s):</Lbl> <E val={assistants} wide/></span>
        </Pair>
        {od.anaesthetist && <Row><Lbl>Anaesthetist:</Lbl> <E val={od.anaesthetist}/></Row>}
        <Row><Lbl>Intra-Op Findings:</Lbl> <E val={findings} ph="Findings..." wide/></Row>
        {od.operativeNote && <Row><Lbl>Operative Note:</Lbl> <E val={od.operativeNote} wide/></Row>}
        {(pp.hpeReport || pp.hpeStage) && <Row><Lbl>HPE Report:</Lbl> <E val={(pp.hpeReport || "") + (pp.hpeStage ? " \u2014 Stage: " + pp.hpeStage : "")} wide/></Row>}

        {/* ── POST-OP COURSE ── */}
        <Sec>IN-HOSPITAL STAY / POST-OPERATIVE COURSE:</Sec>
        <Row><E val={postOpParts || "Uneventful recovery"} wide/></Row>
        {pp.hospitalStayNotes && <Row><E val={pp.hospitalStayNotes} wide/></Row>}
        <Pair>
          {(pp.woundCondition || true) && <span><Lbl>Wound:</Lbl> <E val={pp.woundCondition || ""} ph="Healthy / SSI"/></span>}
          {(pp.sutureRemovalDay || true) && <span><Lbl>Suture Removal:</Lbl> <E val={pp.sutureRemovalDay || ""} ph="POD __"/></span>}
        </Pair>

        {/* ── CONDITION AT DISCHARGE ── */}
        <Sec>CONDITION AT DISCHARGE:</Sec>
        <Row><E val={p.dischargeCondition || pp.conditionAtDischarge || ""} ph="Improved / Stable / Unchanged" wide/></Row>

        {/* ── ADVICE ON DISCHARGE ── */}
        <Sec>ADVICE ON DISCHARGE:</Sec>
        {pp.dischargeMedications && <Row><Lbl>Medications:</Lbl> <E val={pp.dischargeMedications} wide/></Row>}
        {pp.dietInstructions && <Row><Lbl>Diet:</Lbl> <E val={pp.dietInstructions} wide/></Row>}
        <Row><E val={pp.adviceOnDischarge || ""} ph="Advice on discharge..." wide/></Row>
        {pp.followUpDate && <Row><Lbl>Follow-Up:</Lbl> <E val={fmtD(pp.followUpDate) + (pp.followUpInstructions ? " \u2014 " + pp.followUpInstructions : "")} wide/></Row>}

        {/* ── SIGNATURES ── */}
        <div style={{ marginTop: 36, display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ borderTop: "1px solid #000", width: 160, paddingTop: 3, fontSize: 11, fontWeight: 600 }}>Junior Resident</div>
          </div>
          <div style={{ textAlign: "center" }}>
            <div style={{ borderTop: "1px solid #000", width: 160, paddingTop: 3, fontSize: 11, fontWeight: 600 }}>Senior Resident</div>
          </div>
          <div style={{ textAlign: "center" }}>
            <div style={{ borderTop: "1px solid #000", width: 160, paddingTop: 3, fontSize: 11, fontWeight: 600 }}>Head of Unit</div>
          </div>
        </div>
        <div style={{ marginTop: 16, fontSize: 9, color: "#888", textAlign: "center" }}>This is a computer-generated discharge summary. For any queries, contact the Department of Minimal Access & General Surgery, GMC Srinagar.</div>
      </div>
    </div>
  </div>;
}

const WOUND_STATUS = ["Clean & Dry", "Healthy Granulation", "Mild Erythema", "Serous Discharge", "Purulent Discharge", "Dehiscence", "Necrotic", "Drain Site Healthy", "Other"];
const DRAIN_OUTPUT = ["None", "Minimal (<50ml)", "Moderate (50-200ml)", "High (>200ml)", "Bilious", "Hemorrhagic", "Purulent"];
const DIET_STATUS = ["NPO", "Sips", "Clear Liquids", "Soft Diet", "Regular Diet", "Full Diet"];
const MOBILITY_STATUS = ["Bed Bound", "Sitting Up", "Dangling", "Ambulating with Support", "Ambulating Independently"];
const RESP_STATUS = ["On Ventilator", "O2 via Mask", "O2 via Nasal Cannula", "Room Air", "Incentive Spirometry"];

function DailyProgressSection({ patient, onSave }) {
  const notes = patient.dailyNotes || [];
  const [entries, setEntries] = useState([...notes]);
  const [adding, setAdding] = useState(false);

  const surgDate = patient.opDetails?.surgeryDateActual || "";
  const calcPOD = (dateStr) => {
    if (!surgDate || !dateStr) return "";
    const s = new Date(surgDate + "T00:00:00"); const d = new Date(dateStr + "T00:00:00");
    const diff = Math.round((d - s) / (1000 * 60 * 60 * 24));
    return diff >= 0 ? diff : "";
  };

  const today = new Date().toISOString().slice(0, 10);
  const emptyNote = () => ({
    date: today, time: new Date().toTimeString().slice(0, 5),
    pulse: "", bp: "", spo2: "", temp: "", rr: "",
    wound: "", drainOutput: "", drainOutputVol: "",
    oralTolerance: "", flatus: false, bowels: false,
    mobility: "", respiratory: "", diet: "",
    uop: "", ivFluids: "",
    pain: "", antibiotics: "", otherMeds: "",
    cbcHb: "", tlc: "", creatinine: "", rbs: "", otherLabs: "",
    complication: "", plan: "", notes: "",
  });

  const [cur, setCur] = useState(emptyNote());
  const inp5 = { width: "100%", padding: "6px 9px", border: "1.5px solid #e2e8f0", borderRadius: 7, fontSize: "0.8rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" };
  const lbl5 = { display: "block", fontSize: "0.62rem", fontWeight: 600, color: "#475569", marginBottom: 1, textTransform: "uppercase", letterSpacing: "0.04em" };
  const g2m = { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(130px, 1fr))", gap: 6 };

  const doAdd = () => {
    const pod = calcPOD(cur.date);
    const newEntry = { ...cur, pod: pod !== "" ? `POD ${pod}` : "" };
    const updated = [newEntry, ...entries];
    setEntries(updated);
    onSave(updated);
    setCur(emptyNote());
    setAdding(false);
  };

  const doDelete = (i) => {
    const updated = entries.filter((_, j) => j !== i);
    setEntries(updated);
    onSave(updated);
  };

  return <div style={{ marginBottom: 12, border: "2px solid #0277bd", borderRadius: 10 }}>
    <div style={{ padding: "8px 14px", background: "#e1f5fe08", fontWeight: 700, fontSize: "0.82rem", color: "#0277bd", borderBottom: "1px solid #e2e8f0", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <span>🩺 Daily Progress Notes {entries.length > 0 && `(${entries.length})`}</span>
      {!adding && <button onClick={() => setAdding(true)} style={{ padding: "3px 10px", borderRadius: 6, border: "1px solid #4fc3f7", background: "#e1f5fe", fontSize: "0.68rem", fontWeight: 600, color: "#0277bd", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>+ Add Today's Note</button>}
    </div>
    <div style={{ padding: "10px 14px" }}>
      {adding && <div style={{ padding: 12, background: "#f0f9ff", borderRadius: 8, border: "1px solid #b3e5fc", marginBottom: 10 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
          <span style={{ fontWeight: 700, fontSize: "0.78rem", color: "#0277bd" }}>New Entry — {calcPOD(cur.date) !== "" ? `POD ${calcPOD(cur.date)}` : "Enter date"}</span>
          <button onClick={() => setAdding(false)} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.72rem", fontWeight: 600 }}>✕ Cancel</button>
        </div>

        {/* Date & Time */}
        <div style={{ display: "grid", gridTemplateColumns: "140px 100px 1fr", gap: 6, marginBottom: 8 }}>
          <div><label style={lbl5}>Date</label><input style={inp5} type="date" value={cur.date} onChange={e => setCur({ ...cur, date: e.target.value })} /></div>
          <div><label style={lbl5}>Time</label><input style={inp5} type="time" value={cur.time} onChange={e => setCur({ ...cur, time: e.target.value })} /></div>
          <div style={{ display: "flex", alignItems: "flex-end", fontSize: "0.72rem", color: "#64748b", paddingBottom: 6 }}>{calcPOD(cur.date) !== "" && <b style={{ color: "#0277bd" }}>POD {calcPOD(cur.date)}</b>}</div>
        </div>

        {/* Vitals */}
        <div style={{ fontSize: "0.68rem", fontWeight: 700, color: "#0277bd", marginBottom: 4, textTransform: "uppercase" }}>Vitals</div>
        <div style={g2m}>
          <div><label style={lbl5}>Pulse (bpm)</label><input style={inp5} value={cur.pulse} onChange={e => setCur({ ...cur, pulse: e.target.value })} placeholder="72" /></div>
          <div><label style={lbl5}>BP (mmHg)</label><input style={inp5} value={cur.bp} onChange={e => setCur({ ...cur, bp: e.target.value })} placeholder="120/80" /></div>
          <div><label style={lbl5}>SpO2 (%)</label><input style={inp5} value={cur.spo2} onChange={e => setCur({ ...cur, spo2: e.target.value })} placeholder="98" /></div>
          <div><label style={lbl5}>Temp (°F)</label><input style={inp5} value={cur.temp} onChange={e => setCur({ ...cur, temp: e.target.value })} placeholder="98.6" /></div>
          <div><label style={lbl5}>RR (/min)</label><input style={inp5} value={cur.rr} onChange={e => setCur({ ...cur, rr: e.target.value })} placeholder="16" /></div>
        </div>

        {/* Surgical Assessment */}
        <div style={{ fontSize: "0.68rem", fontWeight: 700, color: "#0277bd", margin: "8px 0 4px", textTransform: "uppercase" }}>Surgical Assessment</div>
        <div style={g2m}>
          <div><label style={lbl5}>Wound Status</label><select style={inp5} value={cur.wound} onChange={e => setCur({ ...cur, wound: e.target.value })}><option value="">Select...</option>{WOUND_STATUS.map(w => <option key={w}>{w}</option>)}</select></div>
          <div><label style={lbl5}>Drain Output</label><select style={inp5} value={cur.drainOutput} onChange={e => setCur({ ...cur, drainOutput: e.target.value })}><option value="">Select...</option>{DRAIN_OUTPUT.map(d => <option key={d}>{d}</option>)}</select></div>
          <div><label style={lbl5}>Drain Vol (ml)</label><input style={inp5} value={cur.drainOutputVol} onChange={e => setCur({ ...cur, drainOutputVol: e.target.value })} placeholder="50" /></div>
          <div><label style={lbl5}>Pain (0-10)</label><input style={inp5} value={cur.pain} onChange={e => setCur({ ...cur, pain: e.target.value })} placeholder="3" /></div>
        </div>

        {/* GI & Functional */}
        <div style={{ fontSize: "0.68rem", fontWeight: 700, color: "#0277bd", margin: "8px 0 4px", textTransform: "uppercase" }}>GI & Functional Status</div>
        <div style={g2m}>
          <div><label style={lbl5}>Diet / Oral Tolerance</label><select style={inp5} value={cur.diet} onChange={e => setCur({ ...cur, diet: e.target.value })}><option value="">Select...</option>{DIET_STATUS.map(d => <option key={d}>{d}</option>)}</select></div>
          <div><label style={lbl5}>Mobility</label><select style={inp5} value={cur.mobility} onChange={e => setCur({ ...cur, mobility: e.target.value })}><option value="">Select...</option>{MOBILITY_STATUS.map(m => <option key={m}>{m}</option>)}</select></div>
          <div><label style={lbl5}>Respiratory</label><select style={inp5} value={cur.respiratory} onChange={e => setCur({ ...cur, respiratory: e.target.value })}><option value="">Select...</option>{RESP_STATUS.map(r => <option key={r}>{r}</option>)}</select></div>
          <div><label style={lbl5}>Urine Output (ml/24h)</label><input style={inp5} value={cur.uop} onChange={e => setCur({ ...cur, uop: e.target.value })} placeholder="1500" /></div>
        </div>
        <div style={{ display: "flex", gap: 12, marginTop: 6, flexWrap: "wrap" }}>
          {[["Flatus", "flatus", "#2e7d32"], ["Bowels", "bowels", "#2e7d32"]].map(([l, k, clr]) => (
            <label key={k} style={{ display: "flex", alignItems: "center", gap: 4, fontSize: "0.72rem", color: cur[k] ? clr : "#94a3b8", fontWeight: cur[k] ? 600 : 400, cursor: "pointer" }}>
              <input type="checkbox" checked={!!cur[k]} onChange={e => setCur({ ...cur, [k]: e.target.checked })} style={{ accentColor: clr }} /> {l} ✓
            </label>
          ))}
        </div>

        {/* Medications & I/O */}
        <div style={{ fontSize: "0.68rem", fontWeight: 700, color: "#0277bd", margin: "8px 0 4px", textTransform: "uppercase" }}>Medications & I/O</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 6 }}>
          <div><label style={lbl5}>IV Fluids</label><input style={inp5} value={cur.ivFluids} onChange={e => setCur({ ...cur, ivFluids: e.target.value })} placeholder="NS 500ml, RL 1000ml..." /></div>
          <div><label style={lbl5}>Antibiotics</label><input style={inp5} value={cur.antibiotics} onChange={e => setCur({ ...cur, antibiotics: e.target.value })} placeholder="Inj. Ceftriaxone 1g BD..." /></div>
          <div><label style={lbl5}>Other Medications</label><input style={inp5} value={cur.otherMeds} onChange={e => setCur({ ...cur, otherMeds: e.target.value })} placeholder="Analgesics, PPI..." /></div>
        </div>

        {/* Investigations */}
        <div style={{ fontSize: "0.68rem", fontWeight: 700, color: "#0277bd", margin: "8px 0 4px", textTransform: "uppercase" }}>Investigations</div>
        <div style={g2m}>
          <div><label style={lbl5}>Hb (g/dL)</label><input style={inp5} value={cur.cbcHb} onChange={e => setCur({ ...cur, cbcHb: e.target.value })} placeholder="12.5" /></div>
          <div><label style={lbl5}>TLC</label><input style={inp5} value={cur.tlc} onChange={e => setCur({ ...cur, tlc: e.target.value })} placeholder="8000" /></div>
          <div><label style={lbl5}>Creatinine</label><input style={inp5} value={cur.creatinine} onChange={e => setCur({ ...cur, creatinine: e.target.value })} placeholder="0.9" /></div>
          <div><label style={lbl5}>RBS (mg/dL)</label><input style={inp5} value={cur.rbs} onChange={e => setCur({ ...cur, rbs: e.target.value })} placeholder="110" /></div>
        </div>
        <div style={{ marginTop: 6 }}><label style={lbl5}>Other Labs / Reports</label><input style={inp5} value={cur.otherLabs} onChange={e => setCur({ ...cur, otherLabs: e.target.value })} placeholder="PT/INR, electrolytes, drain fluid analysis..." /></div>

        {/* Complications & Plan */}
        <div style={{ fontSize: "0.68rem", fontWeight: 700, color: "#0277bd", margin: "8px 0 4px", textTransform: "uppercase" }}>Complications & Plan</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 6 }}>
          <div><label style={lbl5}>Complication (if any)</label><input style={inp5} value={cur.complication} onChange={e => setCur({ ...cur, complication: e.target.value })} placeholder="None / SSI / Fever..." /></div>
          <div><label style={lbl5}>Plan</label><input style={inp5} value={cur.plan} onChange={e => setCur({ ...cur, plan: e.target.value })} placeholder="Continue antibiotics, remove drain..." /></div>
        </div>
        <div style={{ marginTop: 6 }}><label style={lbl5}>Additional Notes</label><textarea style={{ ...inp5, minHeight: 36, resize: "vertical" }} value={cur.notes} onChange={e => setCur({ ...cur, notes: e.target.value })} placeholder="Free text notes..." /></div>

        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 10 }}>
          <button onClick={doAdd} style={{ padding: "8px 18px", background: "linear-gradient(135deg,#0277bd,#0288d1)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.8rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>💾 Save Entry</button>
        </div>
      </div>}

      {/* Existing entries */}
      {entries.length === 0 && !adding && <div style={{ color: "#94a3b8", fontSize: "0.82rem", textAlign: "center", padding: 10 }}>No daily notes yet. Click "+ Add Today's Note" to start.</div>}
      {entries.map((e, i) => (
        <div key={i} style={{ marginBottom: 8, padding: "8px 10px", background: i === 0 ? "#f0f9ff" : "#f8fafc", borderRadius: 8, border: `1px solid ${i === 0 ? "#b3e5fc" : "#e2e8f0"}`, fontSize: "0.76rem" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
            <div style={{ fontWeight: 700, color: "#0277bd" }}>{e.pod || ""} {e.date && `— ${new Date(e.date + "T00:00:00").toLocaleDateString("en-IN", { day: "numeric", month: "short" })}`} {e.time && `at ${e.time}`}</div>
            <button onClick={() => doDelete(i)} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.68rem", fontWeight: 600 }}>🗑</button>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: "2px 12px", color: "#475569", lineHeight: 1.6 }}>
            {e.pulse && <span><b>P:</b> {e.pulse}</span>}
            {e.bp && <span><b>BP:</b> {e.bp}</span>}
            {e.spo2 && <span><b>SpO2:</b> {e.spo2}%</span>}
            {e.temp && <span><b>T:</b> {e.temp}°F</span>}
            {e.rr && <span><b>RR:</b> {e.rr}</span>}
            {e.wound && <span><b>Wound:</b> {e.wound}</span>}
            {e.drainOutput && <span><b>Drain:</b> {e.drainOutput}{e.drainOutputVol && ` (${e.drainOutputVol}ml)`}</span>}
            {e.pain && <span><b>Pain:</b> {e.pain}/10</span>}
            {e.diet && <span><b>Diet:</b> {e.diet}</span>}
            {e.flatus && <span style={{ color: "#2e7d32" }}>✓ Flatus</span>}
            {e.bowels && <span style={{ color: "#2e7d32" }}>✓ Bowels</span>}
            {e.mobility && <span><b>Mobility:</b> {e.mobility}</span>}
            {e.respiratory && <span><b>Resp:</b> {e.respiratory}</span>}
            {e.uop && <span><b>UOP:</b> {e.uop}ml</span>}
            {e.ivFluids && <span><b>IV:</b> {e.ivFluids}</span>}
            {e.antibiotics && <span><b>Abx:</b> {e.antibiotics}</span>}
            {e.otherMeds && <span><b>Meds:</b> {e.otherMeds}</span>}
            {e.cbcHb && <span><b>Hb:</b> {e.cbcHb}</span>}
            {e.tlc && <span><b>TLC:</b> {e.tlc}</span>}
            {e.creatinine && <span><b>Cr:</b> {e.creatinine}</span>}
            {e.rbs && <span><b>RBS:</b> {e.rbs}</span>}
            {e.otherLabs && <span><b>Labs:</b> {e.otherLabs}</span>}
            {e.complication && <span style={{ color: "#c62828" }}><b>⚠ Complication:</b> {e.complication}</span>}
            {e.plan && <span style={{ color: "#0277bd" }}><b>Plan:</b> {e.plan}</span>}
            {e.notes && <span style={{ color: "#64748b" }}><b>Notes:</b> {e.notes}</span>}
          </div>
        </div>
      ))}
    </div>
  </div>;
}

function PostOpForm({ patient, onSave, onDischarge, repo }) {
  const existingPP = patient.postOp || {};
  // Auto-prefill finalDx from pre-op if not already set
  const initFinalDx = () => {
    if (existingPP.finalDx && (existingPP.finalDx.type || existingPP.finalDx.primaryDx || existingPP.finalDx.malSite)) return existingPP.finalDx;
    const preOp = patient.clinical?.preOp || {};
    if (preOp.lesionType || patient.type) {
      return {
        type: preOp.lesionType || patient.type || "",
        primaryDx: preOp.primaryDx || patient.diagnosis || "",
        primaryLaterality: preOp.primaryLaterality || "",
        secondaryDx: preOp.secondaryDx || "",
        secondaryLaterality: preOp.secondaryLaterality || "",
        malSite: preOp.malSite || patient.malignancySite || "",
        histology: preOp.preOpHistology || "",
        histologyOther: preOp.histologyOther || "",
        changed: false,
      };
    }
    return {};
  };
  const [pp, setPP] = useState({ ...emptyPostOp(), ...existingPP, finalDx: initFinalDx() });
  const [dischCond, setDischCond] = useState("");
  const inp3 = { width: "100%", padding: "7px 10px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" };
  const lbl3 = { display: "block", fontSize: "0.68rem", fontWeight: 600, color: "#475569", marginBottom: 3, textTransform: "uppercase", letterSpacing: "0.04em" };
  return <div style={{ marginBottom: 12, border: "2px solid #e65100", borderRadius: 10, overflow: "hidden" }}>
    <div style={{ padding: "8px 14px", background: "#fff3e008", fontWeight: 700, fontSize: "0.82rem", color: "#e65100", borderBottom: "1px solid #e2e8f0" }}>📋 Post-Operative Course</div>
    <div style={{ padding: "12px 14px" }}>
      <div><label style={lbl3}>Post-Op Complications</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginBottom: 6 }}>
          {POST_OP_COMPLICATIONS.map(c => <button key={c} onClick={() => {
            const cur = pp.complications.filter(Boolean);
            setPP({ ...pp, complications: cur.includes(c) ? cur.filter(x => x !== c) : [...cur.filter(x => x !== "None"), ...(c === "None" ? ["None"] : [c])] });
          }} style={{ padding: "3px 9px", borderRadius: 14, border: `1.5px solid ${pp.complications.includes(c) ? (c === "None" ? "#4caf50" : "#c62828") : "#e2e8f0"}`, background: pp.complications.includes(c) ? (c === "None" ? "#e8f5e9" : "#fce4ec") : "#fff", cursor: "pointer", fontSize: "0.7rem", fontFamily: "'Outfit',sans-serif", fontWeight: pp.complications.includes(c) ? 600 : 400, color: pp.complications.includes(c) ? (c === "None" ? "#2e7d32" : "#c62828") : "#94a3b8" }}>{c}</button>)}
        </div>
      </div>

      {/* Drain removal — one row per drain from operative details */}
      {(() => {
        const od = patient.opDetails || {};
        const drainList = od.drainList || (od.drains && od.drains !== "No" && od.drains !== "0" ? [{ type: od.drainType || "", site: od.drainSite || "" }] : []);
        const drainRem = pp.drainRemoval || [];
        if (drainList.length === 0) return null;
        return <div style={{ marginTop: 8, padding: "8px 10px", background: "#fef2f2", borderRadius: 8, border: "1px solid #fecaca" }}>
          <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#c62828", marginBottom: 6 }}>Drain Removal</div>
          {drainList.map((dr, i) => {
            const rem = drainRem.find(r => r.drainIdx === i) || { drainIdx: i, pod: "", status: "" };
            const updateRem = (u) => { const n = drainRem.filter(r => r.drainIdx !== i); setPP({ ...pp, drainRemoval: [...n, { ...rem, ...u }] }); };
            return <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginBottom: 4 }}>
              <div style={{ fontSize: "0.74rem", color: "#475569", alignSelf: "center" }}>Drain {i+1}: <b>{[dr.type, dr.site].filter(Boolean).join(" — ") || "—"}</b></div>
              <select style={inp3} value={rem.pod || ""} onChange={e => updateRem({ pod: e.target.value })}>
                <option value="">Select POD...</option>
                {["POD 1","POD 2","POD 3","POD 4","POD 5","POD 6","POD 7","POD 8","POD 9","POD 10","POD 14","POD 21","In Situ at Discharge"].map(v => <option key={v} value={v}>{v}</option>)}
              </select>
            </div>;
          })}
        </div>;
      })()}

      {/* RT and Catheter removal — only if placed */}
      {(() => {
        const od = patient.opDetails || {};
        const hasRT = od.rylesTube === "Yes";
        const hasCath = od.foleysCatheter === "Yes";
        if (!hasRT && !hasCath) return null;
        return <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 8 }}>
          {hasRT && <div><label style={lbl3}>Ryles Tube Removal</label>
            <select style={inp3} value={pp.rylesRemoval || ""} onChange={e => setPP({ ...pp, rylesRemoval: e.target.value })}>
              <option value="">Select POD...</option>
              {["POD 1","POD 2","POD 3","POD 4","POD 5","POD 6","POD 7","In Situ at Discharge"].map(v => <option key={v} value={v}>{v}</option>)}
            </select>
          </div>}
          {hasCath && <div><label style={lbl3}>Foley's Catheter Removal</label>
            <select style={inp3} value={pp.catheterRemoval || ""} onChange={e => setPP({ ...pp, catheterRemoval: e.target.value })}>
              <option value="">Select POD...</option>
              {["POD 1","POD 2","POD 3","POD 4","POD 5","POD 6","POD 7","POD 14","In Situ at Discharge"].map(v => <option key={v} value={v}>{v}</option>)}
            </select>
          </div>}
        </div>;
      })()}

      {/* Recovery milestones */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 8 }}>
        <div><label style={lbl3}>Flatus (POD)</label>
          <select style={inp3} value={pp.flatusDay} onChange={e => setPP({ ...pp, flatusDay: e.target.value })}>
            <option value="">Select...</option>
            {["POD 0","POD 1","POD 2","POD 3","POD 4","POD 5","POD 6","POD 7"].map(v => <option key={v} value={v}>{v}</option>)}
          </select>
        </div>
        <div><label style={lbl3}>Bowels (POD)</label>
          <select style={inp3} value={pp.bowelsDay} onChange={e => setPP({ ...pp, bowelsDay: e.target.value })}>
            <option value="">Select...</option>
            {["POD 0","POD 1","POD 2","POD 3","POD 4","POD 5","POD 6","POD 7","POD 8","POD 10"].map(v => <option key={v} value={v}>{v}</option>)}
          </select>
        </div>
        <div><label style={lbl3}>Orals (POD)</label>
          <select style={inp3} value={pp.oralsDay} onChange={e => setPP({ ...pp, oralsDay: e.target.value })}>
            <option value="">Select...</option>
            {["POD 0","POD 1","POD 2","POD 3","POD 4","POD 5","POD 6","POD 7"].map(v => <option key={v} value={v}>{v}</option>)}
          </select>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 8 }}>
        <div><label style={lbl3}>Ambulation (POD)</label>
          <select style={inp3} value={pp.ambulationDay} onChange={e => setPP({ ...pp, ambulationDay: e.target.value })}>
            <option value="">Select...</option>
            {["POD 0","POD 1","POD 2","POD 3","POD 4","POD 5","POD 6","POD 7"].map(v => <option key={v} value={v}>{v}</option>)}
          </select>
        </div>
        <div><label style={lbl3}>Suture / Staple Removal</label>
          <select style={inp3} value={pp.sutureRemovalDay} onChange={e => setPP({ ...pp, sutureRemovalDay: e.target.value })}>
            <option value="">Select...</option>
            {["POD 5","POD 7","POD 8","POD 10","POD 12","POD 14","POD 21"].map(v => <option key={v} value={v}>{v}</option>)}
          </select>
        </div>
        <div><label style={lbl3}>Wound Condition</label>
          <select style={inp3} value={pp.woundCondition} onChange={e => setPP({ ...pp, woundCondition: e.target.value })}>
            <option value="">Select...</option>
            <option>Healthy</option><option>Mild Erythema</option><option>Seroma</option><option>SSI — Superficial</option><option>SSI — Deep</option><option>Wound Dehiscence</option><option>Burst Abdomen</option>
          </select>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 10 }}>
        <div><label style={lbl3}>Post-Op Imaging</label><textarea style={{ ...inp3, minHeight: 40, resize: "vertical" }} value={pp.postOpImaging} onChange={e => setPP({ ...pp, postOpImaging: e.target.value })} placeholder="USG, CT findings..." /></div>
        <div><label style={lbl3}>Post-Op Investigations</label><textarea style={{ ...inp3, minHeight: 40, resize: "vertical" }} value={pp.postOpInvestigations} onChange={e => setPP({ ...pp, postOpInvestigations: e.target.value })} placeholder="Labs, cultures..." /></div>
      </div>
      <div style={{ marginTop: 8 }}><label style={lbl3}>In-Hospital Stay Notes</label><textarea style={{ ...inp3, minHeight: 40, resize: "vertical" }} value={pp.hospitalStayNotes} onChange={e => setPP({ ...pp, hospitalStayNotes: e.target.value })} placeholder="Recovery course..." /></div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 8 }}>
        <div><label style={lbl3}>HPE Report</label><textarea style={{ ...inp3, minHeight: 45, resize: "vertical" }} value={pp.hpeReport} onChange={e => setPP({ ...pp, hpeReport: e.target.value })} placeholder="Histopathology findings..." /></div>
        <div><label style={lbl3}>HPE Stage (if malignancy)</label><input style={inp3} value={pp.hpeStage} onChange={e => setPP({ ...pp, hpeStage: e.target.value })} placeholder="e.g. pT2N1M0, Stage IIIA..." /></div>
      </div>

      {/* ── FINAL / POST-OPERATIVE DIAGNOSIS ── */}
      <div style={{ marginTop: 12, padding: "10px 12px", background: "#faf4ff", borderRadius: 8, border: "1.5px solid #ce93d8" }}>
        <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#6a1b9a", marginBottom: 8 }}>{"📋"} Final / Post-Operative Diagnosis</div>
        {(() => {
          const fd = pp.finalDx || {};
          const setFD = (u) => setPP({ ...pp, finalDx: { ...fd, ...u } });

          return <>
            {!fd.changed && fd.type && <div style={{ fontSize: "0.66rem", color: "#94a3b8", marginBottom: 6, fontStyle: "italic" }}>Pre-filled from pre-op diagnosis. Edit if final diagnosis differs.</div>}
            {!fd.type && <div style={{ fontSize: "0.66rem", color: "#94a3b8", marginBottom: 6 }}>Select type to record final diagnosis.</div>}
            <div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
              <button onClick={() => setFD({ type: "benign", malSite: "", histology: "", histologyOther: "", changed: true })} style={{ flex: 1, padding: "7px", borderRadius: 8, border: fd.type === "benign" ? "2px solid #2e7d32" : "1.5px solid #e2e8f0", background: fd.type === "benign" ? "#e8f5e9" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 600, fontSize: "0.78rem", color: fd.type === "benign" ? "#2e7d32" : "#94a3b8" }}>{"🟢"} Benign</button>
              <button onClick={() => setFD({ type: "malignancy", primaryDx: "", primaryLaterality: "", secondaryDx: "", changed: true })} style={{ flex: 1, padding: "7px", borderRadius: 8, border: fd.type === "malignancy" ? "2px solid #c62828" : "1.5px solid #e2e8f0", background: fd.type === "malignancy" ? "#fce4ec" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 600, fontSize: "0.78rem", color: fd.type === "malignancy" ? "#c62828" : "#94a3b8" }}>{"🔴"} Malignant</button>
            </div>

            {fd.type === "benign" && <>
              <div style={{ marginBottom: 6 }}>
                <label style={lbl3}>Final Diagnosis</label>
                <SearchSelect clearable options={[...(repo?.allBenignDx || []).map(d => d.dx), "Other (Enter Manually)"]} value={fd.primaryDx || ""} onChange={v => {
                  if (v === "Other (Enter Manually)") { setFD({ primaryDx: "", primaryDxManual: true, changed: true }); return; }
                  setFD({ primaryDx: v, primaryDxManual: false, changed: true });
                }} placeholder="Select final diagnosis..." />
                {fd.primaryDxManual && <input style={{ ...inp3, marginTop: 4, borderColor: "#6a1b9a" }} value={fd.primaryDx || ""} onChange={e => setFD({ primaryDx: e.target.value })} placeholder="Enter diagnosis manually..." />}
              </div>
              <div>
                <label style={lbl3}>Secondary Diagnosis (if any)</label>
                <SearchSelect clearable options={[...(repo?.allBenignDx || []).map(d => d.dx), "Other (Enter Manually)"]} value={fd.secondaryDx || ""} onChange={v => {
                  if (v === "Other (Enter Manually)") { setFD({ secondaryDx: "", secondaryDxManual: true, changed: true }); return; }
                  setFD({ secondaryDx: v, secondaryDxManual: false, changed: true });
                }} placeholder="Optional..." />
                {fd.secondaryDxManual && <input style={{ ...inp3, marginTop: 4, borderColor: "#6a1b9a" }} value={fd.secondaryDx || ""} onChange={e => setFD({ secondaryDx: e.target.value })} placeholder="Enter secondary diagnosis..." />}
              </div>
            </>}

            {fd.type === "malignancy" && <>
              <div style={{ marginBottom: 6 }}>
                <label style={lbl3}>Malignancy Site</label>
                <SearchSelect clearable options={Object.keys(repo?.maligSites || {})} value={fd.malSite || ""} onChange={v => setFD({ malSite: v, changed: true })} placeholder="Select site..." />
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                <div>
                  <label style={lbl3}>Histology (Final)</label>
                  <select style={inp3} value={fd.histology || ""} onChange={e => setFD({ histology: e.target.value, changed: true })}>
                    <option value="">Select...</option>
                    {HISTOLOGY_TYPES.map(h => <option key={h} value={h}>{h}</option>)}
                  </select>
                  {fd.histology === "Others" && <input style={{ ...inp3, marginTop: 4, borderColor: "#6a1b9a" }} value={fd.histologyOther || ""} onChange={e => setFD({ histologyOther: e.target.value })} placeholder="Specify histology..." />}
                </div>
                <div>
                  <label style={lbl3}>Pathological Staging</label>
                  <input style={inp3} value={fd.pathStage || ""} onChange={e => setFD({ pathStage: e.target.value, changed: true })} placeholder="e.g. pT2N1M0" />
                </div>
              </div>
            </>}

            {fd.type && <div style={{ marginTop: 6 }}>
              <label style={lbl3}>Final Diagnosis Notes</label>
              <input style={inp3} value={fd.notes || ""} onChange={e => setFD({ notes: e.target.value })} placeholder="Additional details, incidental findings..." />
            </div>}
          </>;
        })()}
        <PhotoUpload label={"📁 Case File (reports, images, PDFs)"} photos={pp.caseFiles || []} onChange={v => setPP({ ...pp, caseFiles: v })} maxPhotos={15} accept="image/jpeg,image/png,image/webp,application/pdf" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 8 }}>
        <div><label style={lbl3}>Discharge Medications</label><textarea style={{ ...inp3, minHeight: 45, resize: "vertical" }} value={pp.dischargeMedications} onChange={e => setPP({ ...pp, dischargeMedications: e.target.value })} placeholder="Antibiotics, analgesics, PPI, DVT prophylaxis..." /></div>
        <div><label style={lbl3}>Diet Instructions</label><textarea style={{ ...inp3, minHeight: 45, resize: "vertical" }} value={pp.dietInstructions} onChange={e => setPP({ ...pp, dietInstructions: e.target.value })} placeholder="Soft diet, low fat, diabetic diet..." /></div>
      </div>
      <div style={{ marginTop: 8 }}><label style={lbl3}>Advice on Discharge</label><textarea style={{ ...inp3, minHeight: 45, resize: "vertical" }} value={pp.adviceOnDischarge} onChange={e => setPP({ ...pp, adviceOnDischarge: e.target.value })} placeholder="Wound care, activity restrictions, warning signs..." /></div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 8 }}>
        <div><label style={lbl3}>Follow-Up Date</label><input style={inp3} type="date" value={pp.followUpDate} onChange={e => setPP({ ...pp, followUpDate: e.target.value })} /></div>
        <div><label style={lbl3}>Follow-Up Instructions</label><input style={inp3} value={pp.followUpInstructions} onChange={e => setPP({ ...pp, followUpInstructions: e.target.value })} placeholder="OPD visit, labs before visit..." /></div>
      </div>
      {/* Tailored follow-up suggestion */}
      {!pp.followUpDate && !pp.followUpInstructions && (() => {
        const { schedule } = getFollowUpSchedule(patient);
        const first = schedule?.[0];
        if (!first) return null;
        const suggestedDate = patient.opDetails?.surgeryDateActual ? (() => { const d = new Date(patient.opDetails.surgeryDateActual + "T00:00:00"); d.setDate(d.getDate() + first.days); return d.toISOString().slice(0, 10); })() : "";
        const instructions = first.fields.map(f => f.label).join(", ") + ".";
        return <div style={{ marginTop: 6, padding: "8px 12px", background: "#fff8e1", borderRadius: 8, border: "1px solid #ffe082", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: "0.7rem", fontWeight: 700, color: "#f57f17", marginBottom: 2 }}>{"💡"} Suggested 1st Follow-Up — {first.label} ({first.days} days post-op)</div>
            <div style={{ fontSize: "0.68rem", color: "#5d4037", lineHeight: 1.4 }}>{instructions}</div>
          </div>
          <button onClick={() => setPP({ ...pp, followUpDate: suggestedDate, followUpInstructions: instructions })} style={{ padding: "5px 12px", background: "#f57f17", color: "#fff", border: "none", borderRadius: 6, fontSize: "0.7rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif", whiteSpace: "nowrap" }}>Apply</button>
        </div>;
      })()}
      <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16, flexWrap: "wrap", alignItems: "center" }}>
        <button onClick={() => onSave(pp)} style={{ padding: "10px 20px", background: "linear-gradient(135deg,#1565c0,#1976d2)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.84rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>💾 Save Progress</button>
        <select value={dischCond} onChange={e => setDischCond(e.target.value)} style={{ padding: "8px 10px", border: "1.5px solid #a5d6a7", borderRadius: 8, fontSize: "0.8rem", fontFamily: "'Outfit',sans-serif", background: dischCond ? "#e8f5e9" : "#fff", fontWeight: 600, color: dischCond ? "#2e7d32" : "#94a3b8" }}>
          <option value="">Condition at Discharge...</option>
          <option>Improved</option><option>Stable</option><option>Unchanged</option><option>Against Medical Advice</option><option>Referred</option><option>Expired</option>
        </select>
        <button disabled={!dischCond} onClick={() => onDischarge({ ...pp, dischargeCondition: dischCond })} style={{ padding: "10px 20px", background: dischCond ? "linear-gradient(135deg,#2e7d32,#43a047)" : "#e2e8f0", color: dischCond ? "#fff" : "#94a3b8", border: "none", borderRadius: 10, fontSize: "0.84rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: dischCond ? "pointer" : "not-allowed" }}>🏠 Discharge Patient</button>
      </div>
    </div>
  </div>;
}

// ═════════════════════════════════════════════════════════════
// MAIN APP
// ═════════════════════════════════════════════════════════════

function SystemDiagPanel({ show }) {
  const [diag, setDiag] = useState(null);
  const [diagLoading, setDiagLoading] = useState(false);
  const runDiag = async () => {
    setDiagLoading(true);
    try {
      const res = await fetch("/api/index.php?route=diag&_t=" + Date.now());
      const d = await res.json();
      setDiag(d);
    } catch (e) { setDiag({ error: e.message }); }
    setDiagLoading(false);
  };
  useEffect(() => { runDiag(); }, []);
  const fmtBytes = (b) => b > 1048576 ? (b / 1048576).toFixed(1) + " MB" : b > 1024 ? (b / 1024).toFixed(1) + " KB" : b + " B";
  return <>
    <div style={{ padding: 16, borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0", marginBottom: 16 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#1e293b", margin: 0 }}>{"🛡️"} System Diagnostics</h3>
        <button onClick={runDiag} disabled={diagLoading} style={{ padding: "5px 14px", background: "#1565c0", color: "#fff", border: "none", borderRadius: 6, fontSize: "0.72rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif", opacity: diagLoading ? 0.5 : 1 }}>{diagLoading ? "Checking..." : "🔄 Refresh"}</button>
      </div>
      {diag?.error && <div style={{ padding: 10, background: "#fef2f2", borderRadius: 8, color: "#c62828", fontSize: "0.82rem", fontWeight: 600 }}>{"⚠️"} Error: {diag.error}</div>}
      {diag?.data && <>
        <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#475569", textTransform: "uppercase", marginBottom: 6 }}>Data Storage</div>
        <div style={{ display: "grid", gap: 6, marginBottom: 16 }}>
          {diag.data.map(d => (
            <div key={d.key} style={{ padding: "8px 12px", background: d.is_empty ? "#fef2f2" : "#f0fdf4", borderRadius: 8, border: d.is_empty ? "1px solid #fecaca" : "1px solid #bbf7d0", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <span style={{ fontWeight: 700, fontSize: "0.8rem", color: "#1e293b" }}>{d.key}</span>
                <span style={{ marginLeft: 8, fontSize: "0.68rem", color: "#64748b" }}>{d.record_count !== null ? d.record_count + " records" : "object"} · {fmtBytes(d.size_bytes)}</span>
              </div>
              <div style={{ fontSize: "0.66rem", color: "#94a3b8" }}>{d.updated_at}</div>
            </div>
          ))}
        </div>
        {diag.mysql_max_packet_mb && <div style={{ fontSize: "0.72rem", color: "#64748b", marginBottom: 12 }}>MySQL max_allowed_packet: <b>{diag.mysql_max_packet_mb} MB</b></div>}
      </>}
      {diag?.backups && diag.backups.length > 0 && <>
        <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#475569", textTransform: "uppercase", marginBottom: 6 }}>Automatic Backups</div>
        <div style={{ maxHeight: 200, overflowY: "auto", marginBottom: 16 }}>
          {diag.backups.map(b => (
            <div key={b.id || b.created_at} style={{ padding: "5px 10px", fontSize: "0.72rem", borderBottom: "1px solid #f1f5f9", display: "flex", justifyContent: "space-between" }}>
              <span><b>{b.data_key}</b> — {b.record_count} records ({fmtBytes(b.data_size)})</span>
              <span style={{ color: "#94a3b8" }}>{b.created_at}</span>
            </div>
          ))}
        </div>
      </>}
      {diag?.log && diag.log.length > 0 && <>
        <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#475569", textTransform: "uppercase", marginBottom: 6 }}>Write Log (Recent)</div>
        <div style={{ maxHeight: 250, overflowY: "auto", fontSize: "0.68rem" }}>
          {diag.log.map((l, i) => (
            <div key={i} style={{ padding: "4px 8px", borderBottom: "1px solid #f1f5f9", background: l.action === "BLOCKED" ? "#fef2f2" : l.action === "ERROR" ? "#fff3e0" : "#fff", display: "flex", gap: 8, flexWrap: "wrap" }}>
              <span style={{ color: "#94a3b8", minWidth: 120 }}>{l.created_at}</span>
              <span style={{ fontWeight: 700, color: l.action === "BLOCKED" ? "#c62828" : l.action === "ERROR" ? "#e65100" : l.action === "RESTORE" ? "#6a1b9a" : "#2e7d32", minWidth: 60 }}>{l.action}</span>
              <span style={{ color: "#475569" }}>{l.data_key}</span>
              <span style={{ color: "#94a3b8" }}>{fmtBytes(l.data_size)} · {l.record_count}r</span>
              <span style={{ color: l.action === "BLOCKED" ? "#c62828" : "#64748b", flex: 1 }}>{l.message}</span>
            </div>
          ))}
        </div>
      </>}
    </div>
    <div style={{ padding: 16, borderRadius: 12, background: "#eff6ff", border: "1px solid #bfdbfe" }}>
      <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#1565c0", margin: "0 0 8px" }}>{"🔧"} Re-run Setup</h3>
      <p style={{ fontSize: "0.76rem", color: "#64748b", margin: "0 0 14px" }}>Creates any missing tables (backup table, write log). Safe to run — never deletes existing data.</p>
      <button onClick={async () => {
        try {
          const res = await fetch("/api/index.php?route=setup");
          const d = await res.json();
          show(d.success ? "Setup complete! " + d.tables.join(", ") : "Error: " + (d.error || "unknown"));
          runDiag();
        } catch (e) { show("Setup failed: " + e.message, "error"); }
      }} style={{ padding: "8px 18px", background: "#1565c0", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.82rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"🔧"} Run Setup</button>
    </div>
  </>;
}

window.__SurgeryApp = function SurgTrack() {
  const [loading, setLoading] = useState(true);
  const [dataReady, setDataReady] = useState({ users: false, patients: false, config: false });
  const [users, setUsers] = useState([]);
  const [patients, setPatients] = useState([]);
  const [config, setConfig] = useState(DEFAULT_CONFIG);
  const [me, setMe] = useState(null);
  const [view, setView] = useState("home");
  const [lf, setLf] = useState({ u: "", p: "" });
  const [lErr, setLErr] = useState("");
  const [toast, setToast] = useState(null);
  const [confirm, setConfirm] = useState(null);
  const [selDate, setSelDate] = useState("");
  const [search, setSearch] = useState("");
  const [fCat, setFCat] = useState("all");
  const [fType, setFType] = useState("all");

  const empty = { type: "", bCat: "", diag: "", diagC: "", proc: "", procC: "", name: "", age: "", sex: "Male", phone: "", date: "", notes: "", mSite: "", mPlan: "Definitive", mProc: "", mProcC: "", priority: "3" };
  const [pf, setPf] = useState({ ...empty });
  const [editId, setEditId] = useState(null);
  const [nuf, setNuf] = useState({ name: "", username: "", pin: "", role: "resident" });
  const [newHol, setNewHol] = useState({ date: "", name: "" });
  const [settingsTab, setSettingsTab] = useState("general");
  // Custom data stored inside config for persistence
  const customFupTemplates = config.customFupTemplates || [];
  const setCustomFupTemplates = (fn) => updateConfig(prev => ({ ...prev, customFupTemplates: typeof fn === "function" ? fn(prev.customFupTemplates || []) : fn }));
  const customRepo = config.customRepo || { benignDx: {}, maligSites: {}, opProcs: [] };
  const setCustomRepo = (fn) => updateConfig(prev => ({ ...prev, customRepo: typeof fn === "function" ? fn(prev.customRepo || { benignDx: {}, maligSites: {}, opProcs: [] }) : fn }));
  // Merged getters that combine built-in + custom
  const mergedBenignCats = React.useMemo(() => {
    const m = {};
    for (const [k, v] of Object.entries(EXPANDED_BENIGN)) {
      m[k] = { ...v, diagnoses: { ...v.diagnoses } };
    }
    for (const [cat, dxObj] of Object.entries(customRepo.benignDx || {})) {
      if (!m[cat]) m[cat] = { label: cat.charAt(0).toUpperCase() + cat.slice(1), icon: "📌", color: "#546e7a", diagnoses: {} };
      for (const [dx, procs] of Object.entries(dxObj)) {
        if (m[cat].diagnoses[dx]) { m[cat].diagnoses[dx] = [...new Set([...m[cat].diagnoses[dx], ...procs])]; }
        else { m[cat].diagnoses[dx] = [...procs]; }
      }
    }
    return m;
  }, [customRepo]);
  const mergedMaligSites = React.useMemo(() => {
    const m = { ...MALIGNANCY_SITES };
    for (const [site, obj] of Object.entries(customRepo.maligSites || {})) {
      if (m[site]) { m[site] = { procedures: [...new Set([...m[site].procedures, ...obj.procedures])] }; }
      else { m[site] = { procedures: [...obj.procedures] }; }
    }
    return m;
  }, [customRepo]);
  const mergedOpProcs = React.useMemo(() => {
    return [...new Set([...OP_PROCEDURES, ...(customRepo.opProcs || [])])];
  }, [customRepo]);
  const mergedAllBenignDx = React.useMemo(() => {
    const arr = [];
    Object.entries(mergedBenignCats).forEach(([catKey, cat]) => {
      Object.keys(cat.diagnoses).forEach(dx => {
        arr.push({ dx, category: catKey, catLabel: cat.label, procedures: cat.diagnoses[dx] });
      });
    });
    return arr;
  }, [mergedBenignCats]);
  const [editingTemplate, setEditingTemplate] = useState(null); // template being edited
  const [excelModal, setExcelModal] = useState(null); // { columns: {key: bool} }
  const [repoTab, setRepoTab] = useState("benign");
  const [newBenignCat, setNewBenignCat] = useState("others");
  const [newBenignDx, setNewBenignDx] = useState("");
  const [newBenignProcs, setNewBenignProcs] = useState("");
  const [newMaligSite, setNewMaligSite] = useState("");
  const [newMaligProcs, setNewMaligProcs] = useState("");
  const [newProc, setNewProc] = useState("");
  const [newProcCat, setNewProcCat] = useState("others");
  const [myPtSearch, setMyPtSearch] = useState("");
  const [myPtFilter, setMyPtFilter] = useState("all");
  const [emf, setEmf] = useState({ name: "", age: "", sex: "Male", mrd: "" }); // emergency form
  const [newProtocol, setNewProtocol] = useState({ name: "", linkedSurgeon: "" }); // research protocol form
  const [assignProtocolModal, setAssignProtocolModal] = useState(null); // { patient }
  const [adminEditMode, setAdminEditMode] = useState(null);
  const [adminEditPin, setAdminEditPin] = useState("");
  const [noteViewModal, setNoteViewModal] = useState(null);
  const [dischSurgDateFilter, setDischSurgDateFilter] = useState(""); // { name, notes }
  const [fName, setFName] = useState("");
  const [fPhone, setFPhone] = useState("");
  const [fResults, setFResults] = useState(null);
  const [carIdx, setCarIdx] = useState(0);
  const [reschedModal, setReschedModal] = useState(null);
  const [page, setPage] = useState("appointments"); // appointments | admissions | listed
  const [clinicalPt, setClinicalPt] = useState(null); // patient being edited for clinical details
  const [listModal, setListModal] = useState(null); // { patient, date, theater } or { patients: [...], date, theater }
  const [batchSel, setBatchSel] = useState(new Set()); // batch select for listing
  const [batchListModal, setBatchListModal] = useState(null);
  const [admDateFilter, setAdmDateFilter] = useState(""); // filter by admission date
  const [batchSelect, setBatchSelect] = useState([]); // batch listing patient IDs
  const [dischPreview, setDischPreview] = useState(null); // patient for discharge certificate
  const [listDateFilter, setListDateFilter] = useState(""); // filter by listed surgery date
  const [operativePt, setOperativePt] = useState(null); // patient for operative details
  const [postponeModal, setPostponeModal] = useState(null); // { patient, reason, from }
  const [viewPatient, setViewPatient] = useState(null); // patient for full detail view
  const [userMenu, setUserMenu] = useState(false); // slide-up user menu in sidebar

  const show = useCallback((m, t = "success") => { setToast({ m, t }); setTimeout(() => setToast(null), 4000); }, []);
  const perms = me ? PERMS[me.role] : {};
  // Priority slots: use config if available, fall back to defaults
  const pSlots = useMemo(() => {
    const base = DEFAULT_PRIORITY_SLOTS;
    const custom = config.prioritySlots || {};
    const merged = {};
    for (const k of ["1","2","3","4"]) {
      merged[k] = { label: base[k].label, color: base[k].color, slots: { ...base[k].slots, ...(custom[k]?.slots || {}) } };
    }
    return merged;
  }, [config.prioritySlots]);

  useEffect(() => { (async () => {
    // CRITICAL: Never overwrite server data with defaults on load failure
    let loadedUsers = false, loadedPatients = false, loadedConfig = false;
    try {
      const u = await load(SK.USERS, null);
      if (u && Array.isArray(u) && u.length > 0) { setUsers(u); loadedUsers = true; }
      else {
        // Retry once
        const retry = await load(SK.USERS, null);
        if (retry && Array.isArray(retry) && retry.length > 0) { setUsers(retry); loadedUsers = true; }
        else {
          // Use defaults for display ONLY — do NOT save to server
          // This prevents wiping real users if the load just failed
          setUsers(DEFAULT_USERS);
          // Only save defaults if this is truly the first run (check via a special flag)
          try {
            const check = await fetch("/api/index.php?route=data&action=users_data&_t=" + Date.now());
            const txt = await check.text();
            if (!txt || txt === "null" || txt.trim().length < 5) {
              // Truly empty — first run
              await save(SK.USERS, DEFAULT_USERS);
            }
            // else: DB has data but load failed — don't overwrite
          } catch { /* network error — don't save anything */ }
          loadedUsers = true;
        }
      }
    } catch { setUsers(DEFAULT_USERS); /* display only, no save */ }
    try {
      const p = await load(SK.PATIENTS, null);
      if (p && Array.isArray(p)) { setPatients(p); loadedPatients = true; }
    } catch { /* don't overwrite */ }
    try {
      const cfg = await load(SK.CONFIG, null);
      if (cfg && typeof cfg === "object") {
        setConfig({ ...DEFAULT_CONFIG, ...cfg, theaters: cfg.theaters || DEFAULT_CONFIG.theaters, surgeons: cfg.surgeons || DEFAULT_CONFIG.surgeons });
        loadedConfig = true;
      }
    } catch { /* don't overwrite */ }
    // Load rosters (non-critical)
    try { const d = await load("st:duty_roster", null); if (d) setDutyData(d); } catch {}
    try { const a = await load("st:acad_roster", null); if (a) setAcadData(a); } catch {}
    // Session
    try { const s = JSON.parse(sessionStorage.getItem("st:session") || "null"); if (s) { const allU = loadedUsers ? users : DEFAULT_USERS; const f = allU.find(x => x.id === s.id); if (f) { setMe(f); setView("dashboard"); } } } catch {}
    // Only allow auto-save if we successfully loaded data
    setDataReady({ users: loadedUsers, patients: loadedPatients, config: loadedConfig });
    setLoading(false);
  })(); }, []);

  // ── SAVE ARCHITECTURE ──
  // pendingSave refs track when USER makes a change (vs refresh updating display)
  // Only user-initiated changes trigger saves. Refresh NEVER saves.
  const pendingPatientsSave = useRef(false);
  const pendingConfigSave = useRef(false);
  const pendingUsersSave = useRef(false);

  // Wrapper: marks data as needing save
  const updatePatients = useCallback((updater) => {
    setPatients(updater);
    pendingPatientsSave.current = true;
  }, []);
  const updateConfig = useCallback((updater) => {
    setConfig(updater);
    pendingConfigSave.current = true;
  }, []);

  // Debounced save effects — only fire if the pending flag is set
  useEffect(() => {
    if (loading || !pendingPatientsSave.current) return;
    const t = setTimeout(() => {
      if (pendingPatientsSave.current) {
        save(SK.PATIENTS, patients);
        pendingPatientsSave.current = false;
      }
    }, 600);
    return () => clearTimeout(t);
  }, [patients, loading]);

  useEffect(() => {
    if (loading || !pendingConfigSave.current) return;
    const t = setTimeout(() => {
      if (pendingConfigSave.current) {
        save(SK.CONFIG, config);
        pendingConfigSave.current = false;
      }
    }, 600);
    return () => clearTimeout(t);
  }, [config, loading]);

  // Auto-refresh data every 30 seconds — ONLY updates display, NEVER triggers saves
  useEffect(() => {
    if (loading || !me) return;
    const interval = setInterval(async () => {
      try {
        const fp = await load(SK.PATIENTS, null);
        if (fp && Array.isArray(fp)) setPatients(fp); // direct setPatients — no pending flag
        const fu = await load(SK.USERS, null);
        if (fu && Array.isArray(fu) && fu.length > 0) setUsers(fu);
        const fc = await load(SK.CONFIG, null);
        if (fc && typeof fc === "object" && Object.keys(fc).length > 2) setConfig(fc); // direct setConfig
        const fd = await load("st:duty_roster", null);
        if (fd && typeof fd === "object") setDutyData(fd);
        const fa = await load("st:acad_roster", null);
        if (fa && typeof fa === "object") setAcadData(fa);
      } catch (e) { /* silent */ }
    }, 30000);
    return () => clearInterval(interval);
  }, [loading, me]);

  // ── Academic Roster Reminders ─────────────────────────────
  useEffect(() => {
    if (!acadData || Object.keys(acadData).length === 0) return;
    const alreadySent = sessionStorage.getItem("acadRemindersSent");
    if (alreadySent === fmt(new Date())) return;
    const today = new Date(); today.setHours(0, 0, 0, 0);
    const checks = [
      { daysAhead: 0, label: "Today",     emoji: "🔔" },
      { daysAhead: 1, label: "Tomorrow",  emoji: "⏰" },
      { daysAhead: 3, label: "In 3 days", emoji: "📌" },
    ];
    const reminders = [];
    checks.forEach(({ daysAhead, label, emoji }) => {
      const target = new Date(today); target.setDate(today.getDate() + daysAhead);
      const dateKey = fmt(target);
      const event = acadData[dateKey];
      if (event && event.trim()) reminders.push({ emoji, label, dateKey, event: event.trim() });
    });
    if (reminders.length === 0) return;
    reminders.forEach(({ emoji, label, dateKey, event }, i) => {
      setTimeout(() => {
        const body = `${fmtD(dateKey)}: ${event}`;
        notify(`${emoji} Academic — ${label}`, body.length > 150 ? body.slice(0, 147) + "…" : body, "academic-reminder");
      }, i * 2000);
    });
    sessionStorage.setItem("acadRemindersSent", fmt(new Date()));
  }, [acadData]);

  const doLogin = () => { const f = users.find(u => u.username === lf.u.trim().toLowerCase() && u.pin === lf.p.trim()); if (f) { setMe(f); sessionStorage.setItem("st:session", JSON.stringify({ id: f.id })); setView("dashboard"); setLErr(""); setLf({ u: "", p: "" }); } else setLErr("Invalid credentials."); };
  const doLogout = () => { setMe(null); sessionStorage.removeItem("st:session"); setView("home"); };

  const slotInfo = useCallback((ds) => { const info = {}; const normalSlots = pSlots["3"]?.slots || config.slots; for (const c of Object.keys(normalSlots)) { const u = slotsUsed(patients, ds, c); info[c] = { used: u, total: normalSlots[c], avail: normalSlots[c] - u }; } return info; }, [patients, config, pSlots]);

  // Patient status actions
  const doAdmit = (p) => { updatePatients(prev => prev.map(x => {
    if (x.id !== p.id) return x;
    let admissionHistory = x.admissionHistory || [];
    // Save previous admission date if exists
    if (x.admittedAt) {
      admissionHistory = [...admissionHistory, { admittedAt: x.admittedAt, dischargedAt: x.dischargedAt || null, status: x.status }];
    }
    return { ...x, status: "Admitted", admittedAt: new Date().toISOString(), admissionHistory, clinical: { ...(x.clinical || {}), listStatus: null, surgeryListDate: null, theater: null, listOutcome: null } };
  })); show(`${p.name} admitted.`); };
  const doNoShow = (p) => { updatePatients(prev => prev.map(x => x.id === p.id ? { ...x, status: "No Show" } : x)); show(`${p.name} marked No Show.`); };
  const doMovePending = (p) => {
    updatePatients(prev => prev.map(x => {
      if (x.id !== p.id) return x;
      const cl = x.clinical || {};
      let listHistory = cl.listHistory || [];
      // Preserve current listing in history
      if (cl.surgeryListDate) {
        listHistory = [...listHistory, { surgeryListDate: cl.surgeryListDate, theater: cl.theater, listOutcome: "Postponed", listedBy: cl.listedBy || "", changedAt: new Date().toISOString() }];
      }
      return { ...x, status: "Pending", postponedAt: new Date().toISOString(), updatedAt: new Date().toISOString(), clinical: { ...cl, listStatus: null, surgeryListDate: null, theater: null, listOutcome: "Postponed", listHistory } };
    }));
    show(`${p.name} moved to Pending.`);
  };
  const doReschedule = () => {
    if (!reschedModal?.newDate) { show("Pick a new date.", "error"); return; }
    updatePatients(prev => prev.map(x => x.id === reschedModal.patient.id ? { ...x, surgeryDate: reschedModal.newDate, previousDate: x.surgeryDate, originalDate: x.originalDate || x.surgeryDate, status: "Date Given", updatedAt: new Date().toISOString() } : x));
    show(`${reschedModal.patient.name} rescheduled to ${fmtD(reschedModal.newDate)}`);
    setReschedModal(null);
  };
  const doReactivate = (p) => { updatePatients(prev => prev.map(x => x.id === p.id ? { ...x, status: "Date Given" } : x)); show(`${p.name} reactivated.`); };

  const saveClinical = (pt, clinicalData, basicUpdates) => {
    updatePatients(prev => prev.map(x => {
      if (x.id !== pt.id) return x;
      const upd = { ...x, clinical: { ...clinicalData, clinicalBy: clinicalData.clinicalBy || me?.name || "", clinicalById: clinicalData.clinicalById || me?.id || "" }, updatedAt: new Date().toISOString() };
      if (basicUpdates) {
        upd.name = basicUpdates.name || x.name;
        upd.age = basicUpdates.age || x.age;
        upd.sex = basicUpdates.sex || x.sex;
        upd.phone = basicUpdates.phone || x.phone;
        upd.plannedProcedure = basicUpdates.plannedProcedure || x.plannedProcedure;
        if (basicUpdates.type) upd.type = basicUpdates.type;
        if (basicUpdates.type === "malignancy") {
          upd.malignancySite = basicUpdates.diagnosis || x.malignancySite;
          upd.malignancyPlan = basicUpdates.malignancyPlan || x.malignancyPlan;
        } else {
          upd.diagnosis = basicUpdates.diagnosis || x.diagnosis;
        }
        if (basicUpdates.benignCategory) upd.benignCategory = basicUpdates.benignCategory;
      }
      return upd;
    }));
    setClinicalPt(null);
    show(`Clinical details saved for ${pt.name}`);
  };

  const doListForSurgery = () => {
    if (!listModal?.date || !listModal?.theater) { show("Select date and theater.", "error"); return; }
    const ids = listModal.batchIds || [listModal.patient?.id].filter(Boolean);
    if (!ids.length) return;
    updatePatients(prev => prev.map(x => {
      if (!ids.includes(x.id)) return x;
      const cl = x.clinical || emptyClinical();
      let listHistory = cl.listHistory || [];
      // Save previous listing to history if it exists (any status)
      if (cl.surgeryListDate) {
        listHistory = [...listHistory, { surgeryListDate: cl.surgeryListDate, theater: cl.theater, listOutcome: cl.listOutcome || "Relisted", listedBy: cl.listedBy || "", changedAt: new Date().toISOString() }];
      }
      return { ...x, clinical: { ...cl, surgeryListDate: listModal.date, theater: listModal.theater, listStatus: "Listed", listOutcome: null, listHistory, listedBy: me?.name || "", listedById: me?.id || "" }, updatedAt: new Date().toISOString() };
    }));
    show(ids.length === 1 ? `${listModal.patient?.name || "Patient"} listed in ${listModal.theater} on ${fmtD(listModal.date)}` : `${ids.length} patients listed in ${listModal.theater} on ${fmtD(listModal.date)}`);
    setBatchSelect([]); setListModal(null);
  };

  const doCancelAdmission = (p) => {
    if (me?.role !== "admin") { show("Only admin can cancel admission.", "error"); return; }
    setDeletePinModal({ patient: p, action: "cancelAdmission" }); setDeletePin("");
  };

  const doCancelAdmissionConfirmed = (p) => {
    updatePatients(prev => prev.map(x => {
      if (x.id !== p.id) return x;
      // Strip all post-admission data, keep only appointment info
      return { ...x, status: "Date Given", clinical: null, opDetails: null, postOp: null, followUps: null, dailyNotes: null, admittedAt: null, cancelledAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
    }));
    show(`${p.name} admission cancelled. Reverted to appointment only.`);
  };

  const [dischargeModal, setDischargeModal] = useState(null); // { patient, reason }
  const doDischargeWithoutSurgery = () => {
    if (!dischargeModal) return;
    const p = dischargeModal.patient;
    const hasResched = dischargeModal.reschedDate;
    updatePatients(prev => prev.map(x => x.id === p.id ? {
      ...x,
      status: hasResched ? "Date Given" : "Discharged",
      ...(hasResched ? { surgeryDate: dischargeModal.reschedDate, previousDate: x.surgeryDate, originalDate: x.originalDate || x.surgeryDate } : {}),
      dischargeDate: new Date().toISOString().slice(0, 10),
      dischargeReason: dischargeModal.reason || "Discharged without surgery",
      clinical: null, opDetails: null, postOp: null, followUps: null, dailyNotes: null, admittedAt: null,
      updatedAt: new Date().toISOString()
    } : x));
    show(hasResched ? `${p.name} discharged & rescheduled to ${fmtD(dischargeModal.reschedDate)}.` : `${p.name} discharged.`);
    setDischargeModal(null);
  };

  const doPostpone = () => {
    if (!postponeModal?.reason?.trim()) { show("Please enter reason for postponing.", "error"); return; }
    const p = postponeModal.patient;
    updatePatients(prev => prev.map(x => {
      if (x.id !== p.id) return x;
      const cl = x.clinical || {};
      let listHistory = cl.listHistory || [];
      if (cl.surgeryListDate) {
        listHistory = [...listHistory, { surgeryListDate: cl.surgeryListDate, theater: cl.theater, listOutcome: "Postponed", reason: postponeModal.reason, listedBy: cl.listedBy || "", changedAt: new Date().toISOString() }];
      }
      return { ...x, status: "Pending", postponeReason: postponeModal.reason, postponedAt: new Date().toISOString(), updatedAt: new Date().toISOString(), clinical: { ...cl, listStatus: null, surgeryListDate: null, theater: null, listOutcome: "Postponed", listHistory } };
    }));
    show(`${p.name} postponed → moved to Pending.`);
    setPostponeModal(null);
  };

  const doConfirmOperation = (pt, opData) => {
    updatePatients(prev => prev.map(x => {
      if (x.id !== pt.id) return x;
      return { ...x, status: "Operated", opDetails: { ...opData, operatedBy: me?.name || "", operatedById: me?.id || "" }, operatedAt: new Date().toISOString(), clinical: { ...(x.clinical || {}), listOutcome: "Operated" } };
    }));
    setOperativePt(null);
    show(`${pt.name} marked as operated.`);
    notify('🔪 Surgery Completed', `${pt.name} has been operated successfully.`, 'status-change', '/', getSurgeonUserIds({ ...pt, opDetails: { ...opData, operatedById: me?.id } }, users, config));
  };

  const doDelistPatient = (pt) => {
    updatePatients(prev => prev.map(x => x.id === pt.id ? { ...x, clinical: { ...(x.clinical || {}), listOutcome: "Delisted" } } : x));
    show(`${pt.name} delisted.`);
  };

  const doRemoveFromList = (pt) => {
    if (me?.role !== "admin") { show("Only admin can remove from list.", "error"); return; }
    setDeletePinModal({ patient: pt, action: "removeFromList" }); setDeletePin("");
  };

  const doRemoveFromListConfirmed = (p) => {
    updatePatients(prev => prev.map(x => {
      if (x.id !== p.id) return x;
      // Remove from list but keep in admissions
      return { ...x, clinical: { ...(x.clinical || {}), listStatus: null, listOutcome: "Deleted", surgeryListDate: null, theater: null } };
    }));
    show(`${p.name} removed from surgery list. Patient remains in admissions.`);
  };

  const [deletePin, setDeletePin] = useState("");
  const [deletePinModal, setDeletePinModal] = useState(null); // { patient }

  const doDeletePatient = (pt) => {
    if (me?.role !== "admin") { show("Only admin can delete patients.", "error"); return; }
    setDeletePinModal({ patient: pt }); setDeletePin("");
  };
  const confirmDeleteWithPin = () => {
    if (!deletePinModal) return;
    const adminUser = users.find(u => u.id === me.id);
    const correctPin = adminUser?.pin || me?.pin;
    if (!correctPin || deletePin !== correctPin) { show("Incorrect PIN.", "error"); return; }
    if (deletePinModal.action === "cancelAdmission") {
      doCancelAdmissionConfirmed(deletePinModal.patient);
    } else if (deletePinModal.action === "removeFromList") {
      doRemoveFromListConfirmed(deletePinModal.patient);
    } else {
      updatePatients(prev => prev.filter(x => x.id !== deletePinModal.patient.id));
      show(`${deletePinModal.patient.name} deleted permanently.`);
    }
    setDeletePinModal(null); setDeletePin("");
  };

  const doUpdatePAC = (pt, status) => {
    updatePatients(prev => prev.map(x => x.id === pt.id ? { ...x, clinical: { ...(x.clinical || {}), pacStatus: status, pacClearedDate: status === "OK" ? fmt(new Date()) : (x.clinical?.pacClearedDate || null) } } : x));
    show(`${pt.name} PAC: ${status}`);
  };

  const savePostOpProgress = (pt, postOpData) => {
    updatePatients(prev => prev.map(x => x.id === pt.id ? { ...x, postOp: postOpData } : x));
    setViewPatient(prev => prev ? { ...prev, postOp: postOpData } : prev);
    show(`Post-op progress saved for ${pt.name}.`);
  };

  const doDischarge = (pt) => {
    const today = fmt(new Date());
    updatePatients(prev => prev.map(x => x.id === pt.id ? { ...x, status: "Discharged", dischargedAt: new Date().toISOString(), dischargeDate: today } : x));
    setViewPatient(null);
    show(`${pt.name} discharged.`);
    notify('✅ Patient Discharged', `${pt.name} has been discharged.`, 'status-change', '/', getSurgeonUserIds(pt, users, config));
  };

  const saveFollowUps = (pt, data) => {
    updatePatients(prev => prev.map(x => {
      if (x.id !== pt.id) return x;
      return { ...x, followUps: data.followUps, postOp: { ...(x.postOp || {}), hpeReport: data.hpeReport } };
    }));
    setViewPatient(prev => prev ? { ...prev, followUps: data.followUps, postOp: { ...(prev.postOp || {}), hpeReport: data.hpeReport } } : prev);
    show(`Follow-up data saved for ${pt.name}.`);
  };

  const saveDailyNotes = (pt, notes) => {
    updatePatients(prev => prev.map(x => x.id === pt.id ? { ...x, dailyNotes: notes } : x));
    setViewPatient(prev => prev ? { ...prev, dailyNotes: notes } : prev);
    show(`Daily note saved for ${pt.name}.`);
  };

  const EXCEL_COLUMNS = [
    { group: "Patient", cols: ["Name","Age","Sex","Phone","MRD","Blood Group","Address","Comorbidities"] },
    { group: "Diagnosis", cols: ["Type","Diagnosis","Laterality","Site/Subtype","Staging (TNM)","Histology","Plan","Planned Procedure","Access Mode"] },
    { group: "Dates", cols: ["Date of Admission","Surgery Date","Discharge Date"] },
    { group: "Operative", cols: ["Op Start","Op End","Anaesthesia","Operating Surgeon","1st Assistant","Op Access","Primary Procedure","Adjunct Procedure","Secondary Procedure","Intra-Op Findings","Blood Loss (ml)","PRBC","Intra-Op Complications","Drains","Stoma","Ryles Tube","Foleys Catheter","Shifted To"] },
    { group: "Post-Op", cols: ["Post-Op Complications","Drain Removal","RT Removal","Catheter Removal","Flatus (POD)","Bowels (POD)","Orals (POD)","Post-Op Imaging","Post-Op Investigations","HPE Report","Final Diagnosis","Final Dx Notes","Hospital Stay Notes","Advice on Discharge","Condition at Discharge"] },
    { group: "Follow-Up", cols: ["Follow-Up 1 Date","Follow-Up 1 Condition","Follow-Up 1 Remarks","Follow-Up 1 Expired","Follow-Up 1 Readmission","Follow-Up 1 Complication","Follow-Up 2 Date","Follow-Up 2 Condition","Follow-Up 2 Remarks","Follow-Up 3 Date","Follow-Up 3 Condition","Follow-Up 3 Remarks"] },
  ];
  const ALL_EXCEL_COLS = EXCEL_COLUMNS.flatMap(g => g.cols);

  const openExcelModal = () => {
    const cols = {};
    ALL_EXCEL_COLS.forEach(c => cols[c] = true);
    setExcelModal({ columns: cols });
  };

  const generateDischargeExcel = async (selectedCols) => {
    // Load SheetJS via script tag if not already loaded
    if (!window.XLSX) {
      await new Promise((resolve, reject) => {
        const s = document.createElement("script");
        s.src = "https://cdn.sheetjs.com/xlsx-0.20.1/package/dist/xlsx.full.min.js";
        s.onload = resolve;
        s.onerror = () => reject(new Error("Failed to load SheetJS"));
        document.head.appendChild(s);
      });
    }
    const XLSX = window.XLSX;
    const discharged = patients.filter(p => p.status === "Discharged");
    if (discharged.length === 0) { show("No discharged patients to export.", "error"); return; }

    const rows = discharged.map(p => {
      const cl = p.clinical || {}; const po = cl.preOp || {}; const od = p.opDetails || {}; const pp = p.postOp || {};
      const surgeon = od.operatingSurgeon === "__other" ? od.surgeonOther : (od.operatingSurgeon || "");
      const assistant = od.firstAssistant === "__other" ? od.assistantOther : (od.firstAssistant || "");
      const access = od.opAccessMode === "Other" ? od.opAccessOther : (od.opAccessMode || "");
      const dx = po.lesionType === "malignancy" ? ([po.preOpHistology === "Others" ? po.histologyOther : po.preOpHistology, po.malSite || p.malignancySite].filter(Boolean).join(" ") || "Malignancy") : [po.primaryDx || p.diagnosis, po.primaryLaterality && `(${po.primaryLaterality})`, po.secondaryDx && ("+ " + po.secondaryDx)].filter(Boolean).join(" ");
      const comps = (pp.complications || []).filter(c => c && c !== "None").join(", ") || "None";
      const intraComps = [od.complication1 === "Other" ? od.complication1Other : od.complication1, od.complication2 === "Other" ? od.complication2Other : od.complication2].filter(v => v && v !== "None").join(", ") || "None";
      const fups = p.followUps || [];
      return {
        "Name": p.name,
        "Age": p.age,
        "Sex": p.sex,
        "Phone": p.phone,
        "MRD": cl.mrd || "",
        "Blood Group": cl.bloodGroup || "",
        "Address": [cl.district, cl.state].filter(Boolean).join(", "),
        "Comorbidities": [...(cl.comorbidities || []), cl.comorbidOther].filter(Boolean).join(", "),
        "Type": po.lesionType === "malignancy" ? "Malignant" : "Benign",
        "Diagnosis": dx,
        "Laterality": po.primaryLaterality || "",
        "Site/Subtype": [po.primarySite, po.primarySubtype, po.ashClass].filter(Boolean).join(" · "),
        "Staging (TNM)": po.lesionType === "malignancy" ? [po.clinicalT, po.clinicalN, po.clinicalM].filter(Boolean).join(" ") : "",
        "Histology": po.preOpHistology || "",
        "Plan": po.plan || "",
        "Planned Procedure": po.procedure || p.plannedProcedure || "",
        "Access Mode": po.accessMode === "Others" ? po.accessOther : (po.accessMode || ""),
        "Date of Admission": p.admittedAt ? new Date(p.admittedAt).toLocaleDateString("en-IN") : "",
        "Surgery Date": od.surgeryDateActual || "",
        "Op Start": od.startTime || "",
        "Op End": od.endTime || "",
        "Anaesthesia": od.anaesthesia === "Other" ? od.anaesthesiaOther : (od.anaesthesia || ""),
        "Operating Surgeon": surgeon,
        "1st Assistant": assistant,
        "Op Access": access,
        "Primary Procedure": od.primaryProcedure || "",
        "Adjunct Procedure": od.adjunctProcedure || "",
        "Secondary Procedure": od.secondaryProcedure || "",
        "Intra-Op Findings": (od.intraFindings || []).filter(Boolean).join("; "),
        "Blood Loss (ml)": od.bloodLoss || "",
        "PRBC": od.prbcTransfusion || "",
        "Intra-Op Complications": intraComps,
        "Drains": od.drains === "Yes" && od.drainList?.length ? od.drainList.map((d, i) => `${i+1}. ${[d.type, d.site].filter(Boolean).join(" - ")}`).join("; ") : (od.drains || ""),
        "Stoma": od.stoma || "",
        "Ryles Tube": od.rylesTube || "",
        "Foleys Catheter": od.foleysCatheter || "",
        "Shifted To": od.shiftedTo || "",
        "Post-Op Complications": comps,
        "Drain Removal": (pp.drainRemoval || []).map(r => { const dr = (od.drainList || [])[r.drainIdx]; return `${dr ? [dr.type, dr.site].filter(Boolean).join(" ") : `Drain ${r.drainIdx+1}`}: ${r.pod || ""}`; }).join("; ") || pp.drainRemovalDay || "",
        "RT Removal": pp.rylesRemoval || pp.rylesRemovalDay || "",
        "Catheter Removal": pp.catheterRemoval || pp.catheterRemovalDay || "",
        "Flatus (POD)": pp.flatusDay || "",
        "Bowels (POD)": pp.bowelsDay || "",
        "Orals (POD)": pp.oralsDay || "",
        "Post-Op Imaging": pp.postOpImaging || "",
        "Post-Op Investigations": pp.postOpInvestigations || "",
        "HPE Report": pp.hpeReport || "",
        "Final Diagnosis": (() => { const fd = pp.finalDx || {}; if (!fd.type) return ""; if (fd.type === "malignancy") return [(fd.histology === "Others" ? fd.histologyOther : fd.histology), fd.malSite].filter(Boolean).join(" ") + (fd.pathStage ? " (" + fd.pathStage + ")" : ""); let d = fd.primaryDx || ""; if (fd.primaryLaterality) d += " (" + fd.primaryLaterality + ")"; if (fd.secondaryDx) d += " + " + fd.secondaryDx; return d; })(),
        "Final Dx Notes": (pp.finalDx || {}).notes || "",
        "Hospital Stay Notes": pp.hospitalStayNotes || "",
        "Advice on Discharge": pp.adviceOnDischarge || "",
        "Discharge Date": p.dischargeDate || "",
        "Condition at Discharge": pp.dischargeCondition || "",
        "Follow-Up 1 Date": fups[0]?.date || "",
        "Follow-Up 1 Condition": fups[0]?.condition || "",
        "Follow-Up 1 Remarks": fups[0]?.remarks || "",
        "Follow-Up 1 Expired": fups[0]?.expired ? "Yes" : "",
        "Follow-Up 1 Readmission": fups[0]?.readmission ? "Yes" : "",
        "Follow-Up 1 Complication": fups[0]?.complication ? "Yes" : "",
        "Follow-Up 2 Date": fups[1]?.date || "",
        "Follow-Up 2 Condition": fups[1]?.condition || "",
        "Follow-Up 2 Remarks": fups[1]?.remarks || "",
        "Follow-Up 2 Expired": fups[1]?.expired ? "Yes" : "",
        "Follow-Up 2 Readmission": fups[1]?.readmission ? "Yes" : "",
        "Follow-Up 2 Complication": fups[1]?.complication ? "Yes" : "",
        "Follow-Up 3 Date": fups[2]?.date || "",
        "Follow-Up 3 Condition": fups[2]?.condition || "",
        "Follow-Up 3 Remarks": fups[2]?.remarks || "",
        "Follow-Up 3 Expired": fups[2]?.expired ? "Yes" : "",
        "Follow-Up 3 Readmission": fups[2]?.readmission ? "Yes" : "",
        "Follow-Up 3 Complication": fups[2]?.complication ? "Yes" : "",
      };
      // Add follow-up clinical data fields dynamically
      [0, 1, 2].forEach(fi => {
        const fd = fups[fi]?.data || {};
        Object.entries(fd).forEach(([k, v]) => {
          if (v) row[`FU${fi+1} ${(fups[fi]?.fieldDefs || []).find(f => f.key === k)?.label || k}`] = v;
        });
      });
      return row;
    });

    // Filter to selected columns
    const filteredRows = rows.map(r => {
      const fr = {};
      Object.keys(r).forEach(k => { if (!selectedCols || selectedCols[k]) fr[k] = r[k]; });
      return fr;
    });

    const ws = XLSX.utils.json_to_sheet(filteredRows);
    // Auto-width columns
    const colWidths = Object.keys(filteredRows[0]).map(k => ({ wch: Math.max(k.length + 2, ...filteredRows.map(r => String(r[k] || "").length).slice(0, 20)) }));
    ws["!cols"] = colWidths.map(w => ({ wch: Math.min(w.wch, 40) }));
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Discharged Patients");
    XLSX.writeFile(wb, `SurgTrack_Discharged_${new Date().toISOString().slice(0, 10)}.xlsx`);
    show(`Exported ${discharged.length} patients (${Object.keys(filteredRows[0]).length} columns) to Excel.`);
    setExcelModal(null);
  };

  const generateDischarge = (p) => {
    setDischPreview(p);
  };

  const generatePrintList = (date, theater, tPts) => {
    const fDate = new Date(date + "T00:00:00").toLocaleDateString("en-IN", { day: "2-digit", month: "2-digit", year: "2-digit" });
    const buildDx = (p) => {
      const po = p.clinical?.preOp || {};
      if (po.lesionType === "malignancy" || p.type === "malignancy") {
        return [po.preOpHistology === "Others" ? po.histologyOther : po.preOpHistology, po.malSite || p.malignancySite].filter(Boolean).join(" ") || "Malignancy";
      }
      let dx = po.primaryDx || p.diagnosis || "—";
      if (po.primaryLaterality) dx += " (" + po.primaryLaterality + ")";
      if (po.secondaryDx) {
        dx += " + " + po.secondaryDx;
        if (po.secondaryLaterality) dx += " (" + po.secondaryLaterality + ")";
      }
      return dx;
    };
    const buildPlan = (p) => {
      const po = p.clinical?.preOp || {};
      const access = po.accessMode && po.accessMode !== "Others" ? po.accessMode : (po.accessOther || "");
      const proc = po.procedure || p.plannedProcedure || "—";
      if (po.lesionType === "malignancy" || p.type === "malignancy") {
        return (access ? access + " " : "") + proc;
      }
      return (access ? access + " " : "") + proc;
    };
    const buildComorb = (p) => {
      const cl = p.clinical || {};
      const list = [...(cl.comorbidities || [])];
      if (cl.comorbidOther) list.push(cl.comorbidOther);
      return list.join(", ") || "—";
    };
    const rows = tPts.map((p, i) => `<tr>
      <td style="text-align:center;font-weight:600">${i + 1}</td>
      <td>${p.name}</td>
      <td style="text-align:center">${p.age}/${p.sex ? p.sex[0] : ""}</td>
      <td style="text-align:center">${p.clinical?.mrd || ""}</td>
      <td>${buildDx(p)}</td>
      <td style="font-size:9px">${buildComorb(p)}</td>
      <td>${buildPlan(p)}</td>
      <td style="text-align:center"></td>
    </tr>`).join("");

    const html = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">
<head><meta charset="utf-8">
<style>
  @page { size: A4 portrait; margin: 1.5cm 1.2cm; }
  body { font-family: 'Times New Roman', serif; font-size: 12px; color: #000; }
  .header { text-align: center; margin-bottom: 8px; }
  .header h1 { font-size: 15px; margin: 0; letter-spacing: 0.5px; }
  .header h2 { font-size: 13px; margin: 2px 0; }
  .header h3 { font-size: 12px; margin: 2px 0; font-weight: normal; }
  .info { font-size: 11px; margin: 6px 0; }
  .info b { text-decoration: underline; }
  table { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 11px; }
  th, td { border: 1px solid #000; padding: 5px 6px; vertical-align: top; }
  th { background: #f0f0f0; font-size: 10px; text-align: center; font-weight: 700; }
  .footer { margin-top: 30px; font-size: 11px; }
  .footer-row { display: flex; justify-content: space-between; margin-top: 24px; }
  .footer-row span { font-weight: 700; }
  .copy { margin-top: 16px; font-size: 10px; }
  @media print { body { -webkit-print-color-adjust: exact; } }
</style></head><body>
<div class="header">
  <h1>GOVERNMENT MEDICAL COLLEGE, SRINAGAR</h1>
  <h2>POSTGRADUATE DEPARTMENT OF MINIMAL ACCESS &amp; GENERAL SURGERY</h2>
  <h3>General Surgery Unit-1 &nbsp;&nbsp; <b>${theater}</b> &nbsp;&nbsp; Date: <b>${fDate}</b></h3>
</div>
<div class="info"><b>HOD: Prof (Dr) Iqbal Saleem Mir</b></div>
<div class="info">Dr Abdul Hamid Samoon, Dr Arshad Rashid, Dr Khursheed A. Ganai</div>
<table>
  <thead><tr>
    <th style="width:30px">S.No</th>
    <th style="width:110px">Name</th>
    <th style="width:45px">Age/<br>Sex</th>
    <th style="width:55px">MRD</th>
    <th>Diagnosis</th>
    <th style="width:95px">Co-morbidities</th>
    <th>Plan</th>
    <th style="width:52px">Golden<br>Card<br>Availed</th>
  </tr></thead>
  <tbody>${rows}
    <tr><td colspan="8" style="height:28px;border:1px solid #000">&nbsp;</td></tr>
  </tbody>
</table>
<div class="footer">
  <div class="footer-row"><span>Registrar</span><span>Head of the Unit</span></div>
  <div class="copy">Copy to: &nbsp; 1. HOD Anesthesia &nbsp;&nbsp; 2. PAC Room &nbsp;&nbsp; 3. OT Incharge</div>
</div>
</body></html>`;

    const blob = new Blob([html], { type: "application/msword" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `Surgery_List_${theater}_${date}.doc`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    show(`List downloaded: ${theater} — ${fmtD(date)}`);
  };

  const handleSave = () => {
    if (!pf.name.trim()) { show("Name is required.", "error"); return; }
    if (pf.type === "benign") {
      if (!pf.bCat || !pf.diag) { show("Select category & diagnosis.", "error"); return; }
      const fd = pf.diag === "__c__" ? pf.diagC : pf.diag;
      const fp = pf.proc === "__c__" ? pf.procC : pf.proc;
      const activeSlots = pSlots[pf.priority || "3"].slots;
      const ad = pf.date || findDate(patients, config.admissionDay, pf.bCat, activeSlots);
      const base = { name: pf.name.trim(), age: pf.age ? +pf.age : null, sex: pf.sex, phone: pf.phone.trim(), diagnosis: fd, plannedProcedure: fp, surgeryDate: ad, notes: pf.notes.trim(), benignCategory: pf.bCat, type: "benign", malignancySite: "", malignancyPlan: "", priority: pf.priority || "3", updatedAt: new Date().toISOString() };
      if (editId) {
        updatePatients(p => p.map(x => {
          if (x.id !== editId) return x;
          const upd = { ...x, ...base };
          // Always reset No Show / Cancelled to Date Given on re-save
          if (x.status === "No Show" || x.status === "Cancelled") {
            upd.status = "Date Given";
            upd.previousDate = x.surgeryDate;
            upd.rescheduledFrom = x.status;
          }
          if (!upd.originalDate) upd.originalDate = x.surgeryDate || x.originalDate;
          return upd;
        }));
        show("Updated.");
      }
      else { updatePatients(p => [...p, { id: "p" + Date.now() + Math.random().toString(36).slice(2, 5), ...base, originalDate: ad, status: "Date Given", createdBy: me.id, createdByName: me.name, createdAt: new Date().toISOString() }]); show(`Scheduled → ${fmtD(ad)}`); }
    } else if (pf.type === "malignancy") {
      if (!pf.mSite) { show("Select site.", "error"); return; }
      if (!pf.date) { show("Select date for malignancy.", "error"); return; }
      const fp = pf.mProc === "__c__" ? pf.mProcC : pf.mProc;
      const base = { name: pf.name.trim(), age: pf.age ? +pf.age : null, sex: pf.sex, phone: pf.phone.trim(), diagnosis: pf.mSite, malignancySite: pf.mSite, malignancyPlan: pf.mPlan, plannedProcedure: fp, surgeryDate: pf.date, notes: pf.notes.trim(), benignCategory: "", type: "malignancy", updatedAt: new Date().toISOString() };
      if (editId) {
        updatePatients(p => p.map(x => {
          if (x.id !== editId) return x;
          const upd = { ...x, ...base };
          if (x.status === "No Show" || x.status === "Cancelled") {
            upd.status = "Date Given";
            upd.previousDate = x.surgeryDate;
            upd.rescheduledFrom = x.status;
          }
          if (!upd.originalDate) upd.originalDate = x.surgeryDate || x.originalDate;
          return upd;
        }));
        show("Updated.");
      }
      else { updatePatients(p => [...p, { id: "p" + Date.now() + Math.random().toString(36).slice(2, 5), ...base, originalDate: pf.date, status: "Date Given", createdBy: me.id, createdByName: me.name, createdAt: new Date().toISOString() }]); show(`Malignancy dated → ${fmtD(pf.date)}`); }
    } else { show("Select Benign or Malignancy.", "error"); return; }
    setPf({ ...empty }); setEditId(null); setView("dashboard");
  };

  const handleEdit = (p) => {
    if (p.type === "malignancy") {
      const sp = mergedMaligSites[p.malignancySite]?.procedures || [];
      const cp = p.plannedProcedure && !sp.includes(p.plannedProcedure);
      setPf({ ...empty, type: "malignancy", name: p.name, age: String(p.age), sex: p.sex, phone: p.phone, mSite: p.malignancySite || "", mPlan: p.malignancyPlan || "Definitive", mProc: cp ? "__c__" : (p.plannedProcedure || ""), mProcC: cp ? p.plannedProcedure : "", date: p.surgeryDate, notes: p.notes || "" });
    } else {
      const dm = p.benignCategory ? mergedBenignCats[p.benignCategory]?.diagnoses || {} : {};
      const dp = dm[p.diagnosis] || [];
      const cd = p.diagnosis && !Object.keys(dm).includes(p.diagnosis);
      const cp = p.plannedProcedure && !dp.includes(p.plannedProcedure);
      setPf({ ...empty, type: "benign", bCat: p.benignCategory || "", name: p.name, age: String(p.age), sex: p.sex, phone: p.phone, diag: cd ? "__c__" : (p.diagnosis || ""), diagC: cd ? p.diagnosis : "", proc: cp ? "__c__" : (p.plannedProcedure || ""), procC: cp ? p.plannedProcedure : "", date: p.surgeryDate, notes: p.notes || "", priority: p.priority || "3" });
    }
    setEditId(p.id); setView("schedule");
  };

  const filtered = useMemo(() => patients.filter(p => {
    const s = search.toLowerCase();
    return (!s || p.name.toLowerCase().includes(s) || p.phone.includes(s) || (p.diagnosis || "").toLowerCase().includes(s))
      && (fCat === "all" || (fCat === "malignancy" ? p.type === "malignancy" : p.benignCategory === fCat))
      && (fType === "all" || p.type === fType)
      && (!selDate || p.surgeryDate === selDate || p.originalDate === selDate);
  }).sort((a, b) => new Date(a.surgeryDate) - new Date(b.surgeryDate)), [patients, search, fCat, fType, selDate]);

  const today = new Date(); today.setHours(0, 0, 0, 0); const todayS = fmt(today);
  const nextDts = getNextAdmDates(config.admissionDay, 8);
  const avProcs = React.useMemo(() => {
    if (!(pf.type === "benign" && pf.bCat && pf.diag && pf.diag !== "__c__")) return [];
    // Get ALL procedures from the entire category
    const allCatProcs = [];
    Object.values(mergedBenignCats[pf.bCat]?.diagnoses || {}).forEach(dxProcs => {
      dxProcs.forEach(pr => { if (!allCatProcs.includes(pr)) allCatProcs.push(pr); });
    });
    // Also add standalone procs mapped to same category
    const catProcs = (customRepo.opProcs || []).filter(proc => (customRepo.procCategories || {})[proc] === pf.bCat);
    return [...new Set([...allCatProcs, ...catProcs])];
  }, [pf.type, pf.bCat, pf.diag, mergedBenignCats, customRepo]);
  const mProcs = pf.mSite ? (mergedMaligSites[pf.mSite]?.procedures || []) : [];

  const [sideOpen, setSideOpen] = useState(false);
  const isMobile = typeof window !== "undefined" && window.innerWidth < 768;

  // ─── DUTY ROSTER STATE ───
  const [dutyMonth, setDutyMonth] = useState(() => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}`; });
  const [dutyData, setDutyData] = useState({});
  const [acadMonth, setAcadMonth] = useState(() => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}`; });
  const [acadData, setAcadData] = useState({});
  const saveDuty = async (d) => { setDutyData(d); await save("st:duty_roster", d); };
  const saveAcad = async (d) => { setAcadData(d); await save("st:acad_roster", d); };

  // ─── STATS COMPUTATIONS ───
  const stats = useMemo(() => {
    const now = new Date(); const thisMonth = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}`;
    const dated = patients.filter(p => p.status === "Date Given");
    const admitted = patients.filter(p => p.status === "Admitted");
    const operated = patients.filter(p => p.status === "Operated");
    const discharged = patients.filter(p => p.status === "Discharged");
    const listed = patients.filter(p => p.clinical?.listStatus === "Listed");
    const pending = patients.filter(p => p.status === "Pending");
    const operatedThisMonth = patients.filter(p => (p.status === "Operated" || p.status === "Discharged") && p.opDetails?.surgeryDateActual?.startsWith(thisMonth));
    const benignOps = operatedThisMonth.filter(p => p.type === "benign");
    const malOps = operatedThisMonth.filter(p => p.type === "malignancy");
    const dischargedThisMonth = discharged.filter(p => p.dischargeDate?.startsWith(thisMonth));
    return { dated: dated.length, admitted: admitted.length, operated: operated.length, discharged: discharged.length, listed: listed.length, pending: pending.length, total: patients.length, operatedThisMonth: operatedThisMonth.length, benignOps: benignOps.length, malOps: malOps.length, dischargedThisMonth: dischargedThisMonth.length };
  }, [patients]);

  if (loading) return <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100vh", background: "#0b1420", color: "#4caf50", fontFamily: "'Outfit',sans-serif" }}><link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Playfair+Display:wght@700&display=swap" rel="stylesheet" />Loading...</div>;

  // ═══ CALENDAR HELPERS (used by home page + settings) ═══
  const buildCal = (ym) => {
    const [y, m] = ym.split("-").map(Number);
    const first = new Date(y, m - 1, 1); const daysInMonth = new Date(y, m, 0).getDate();
    const startDay = first.getDay(); // 0=Sun
    const weeks = []; let week = new Array(startDay).fill(null);
    for (let d = 1; d <= daysInMonth; d++) {
      week.push(d);
      if (week.length === 7) { weeks.push(week); week = []; }
    }
    if (week.length) { while (week.length < 7) week.push(null); weeks.push(week); }
    return { weeks, year: y, month: m, monthName: new Date(y, m - 1).toLocaleDateString("en-US", { month: "long", year: "numeric" }) };
  };
  const shiftMonth = (ym, delta) => {
    const [y, m] = ym.split("-").map(Number);
    const d = new Date(y, m - 1 + delta, 1);
    return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}`;
  };

  const CalCell = ({ dataObj, saveObj, dateKey, placeholder, color, readOnly }) => {
    const [editing, setEditing] = useState(false);
    const val = dataObj[dateKey] || "";
    const [txt, setTxt] = useState(val);
    useEffect(() => setTxt(dataObj[dateKey] || ""), [dataObj, dateKey]);
    if (!readOnly && editing) return <div onClick={e => e.stopPropagation()}>
      <textarea autoFocus value={txt} onChange={e => setTxt(e.target.value)} onBlur={() => { saveObj({ ...dataObj, [dateKey]: txt.trim() }); setEditing(false); }}
        style={{ width: "100%", minHeight: 38, border: `1.5px solid ${color}`, borderRadius: 4, padding: "2px 4px", fontSize: "0.6rem", fontFamily: "'Outfit',sans-serif", resize: "vertical", boxSizing: "border-box" }}
        placeholder={placeholder} />
    </div>;
    return <div onClick={(e) => { if (!readOnly) { e.stopPropagation(); setEditing(true); } }} style={{ minHeight: 20, cursor: readOnly ? "default" : "pointer", fontSize: "0.58rem", color: "#475569", lineHeight: 1.3, whiteSpace: "pre-wrap", wordBreak: "break-word" }}>
      {val || (!readOnly ? <span style={{ color: "#cbd5e1", fontStyle: "italic" }}>tap to add</span> : "")}
    </div>;
  };

  const CalendarGrid = ({ ym, setYm, data, saveData, color, title, placeholder, readOnly }) => {
    const cal = buildCal(ym);
    const today = new Date(); const todayStr = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,"0")}-${String(today.getDate()).padStart(2,"0")}`;
    const holidays = config.holidays || [];
    return <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <button onClick={() => setYm(shiftMonth(ym, -1))} style={{ border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", padding: "6px 12px", cursor: "pointer", fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif" }}>‹ Prev</button>
        <h3 style={{ margin: 0, fontSize: "1rem", fontWeight: 700, color: "#0b1420", fontFamily: "'Playfair Display',serif" }}>{cal.monthName}</h3>
        <button onClick={() => setYm(shiftMonth(ym, 1))} style={{ border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", padding: "6px 12px", cursor: "pointer", fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif" }}>Next ›</button>
      </div>
      <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 560 }}>
          <thead><tr>{["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(d => <th key={d} style={{ padding: "6px 2px", fontSize: "0.68rem", fontWeight: 700, color: d === "Sun" ? "#c62828" : "#475569", background: "#f8fafc", border: "1px solid #e2e8f0", textAlign: "center" }}>{d}</th>)}</tr></thead>
          <tbody>{cal.weeks.map((week, wi) => <tr key={wi}>{week.map((day, di) => {
            if (!day) return <td key={di} style={{ border: "1px solid #e2e8f0", background: "#f8fafc" }} />;
            const dateKey = `${ym}-${String(day).padStart(2,"0")}`;
            const isToday = dateKey === todayStr;
            const hol = holidays.find(h => h.date === dateKey);
            return <td key={di} style={{ border: "1px solid #e2e8f0", padding: "3px 4px", verticalAlign: "top", background: hol ? "#fff3e0" : (isToday ? `${color}08` : "#fff"), width: "14.28%" }}>
              <div style={{ fontSize: "0.68rem", fontWeight: 700, color: isToday ? color : (di === 0 || hol ? "#c62828" : "#0b1420"), marginBottom: 2 }}>
                {day}{isToday && <span style={{ marginLeft: 3, fontSize: "0.5rem", color, fontWeight: 600 }}>today</span>}
              </div>
              {hol && <div style={{ fontSize: "0.5rem", color: "#e65100", fontWeight: 700, lineHeight: 1.1, marginBottom: 2 }}>🎉 {hol.name}</div>}
              <CalCell dataObj={data} saveObj={saveData} dateKey={dateKey} placeholder={placeholder} color={color} readOnly={readOnly} />
            </td>;
          })}</tr>)}</tbody>
        </table>
      </div>
    </div>;
  };

  // ═══ HOME PAGE ═══
  if (view === "home" || view === "findMyDate") {
    const homeFont = <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Playfair+Display:wght@700&display=swap" rel="stylesheet" />;

    // ─── FIND YOUR APPOINTMENT PAGE ───
    if (view === "findMyDate") {
      const doFind = () => {
        const name = fName.trim().toLowerCase();
        const phone = fPhone.trim();
        if (!name && !phone) { show("Enter your name or phone number.", "error"); return; }
        const matches = patients.filter(p => {
          const nameMatch = name && p.name.toLowerCase().includes(name);
          const phoneMatch = phone && p.phone.includes(phone);
          return nameMatch || phoneMatch;
        });
        setFResults(matches);
      };
      return <div style={{ minHeight: "100vh", background: "linear-gradient(160deg, #0b1420 0%, #162032 40%, #1a2740 100%)", fontFamily: "'Outfit',sans-serif" }}>
        {homeFont}
        <div style={{ padding: "16px 20px", background: "rgba(0,0,0,0.3)", display: "flex", alignItems: "center", justifyContent: "space-between", position: "sticky", top: 0, zIndex: 100, backdropFilter: "blur(10px)" }}>
          <button onClick={() => setView("home")} style={{ border: "1px solid #334155", borderRadius: 8, background: "none", color: "#94a3b8", padding: "5px 12px", cursor: "pointer", fontSize: "0.78rem", fontFamily: "'Outfit',sans-serif" }}>← Home</button>
          <h2 style={{ margin: 0, fontSize: "1rem", color: "#fff", fontFamily: "'Playfair Display',serif" }}>Know Your Appointment Schedule</h2>
          <div style={{ width: 60 }} />
        </div>
        <div style={{ maxWidth: 500, margin: "0 auto", padding: "30px 16px" }}>
          <div style={{ background: "rgba(255,255,255,0.05)", borderRadius: 16, border: "1px solid rgba(255,255,255,0.1)", padding: "24px 20px", marginBottom: 20 }}>
            <div style={{ textAlign: "center", marginBottom: 20 }}>
              <div style={{ fontSize: "2.5rem", marginBottom: 8 }}>🔍</div>
              <h3 style={{ color: "#e2e8f0", fontSize: "1.1rem", fontWeight: 700, margin: "0 0 4px", fontFamily: "'Playfair Display',serif" }}>Find Your Appointment</h3>
              <p style={{ color: "#64748b", fontSize: "0.78rem", margin: 0 }}>Enter your name or phone number to check your scheduled date</p>
            </div>
            <div style={{ marginBottom: 12 }}>
              <label style={{ display: "block", fontSize: "0.7rem", fontWeight: 600, color: "#94a3b8", marginBottom: 4, textTransform: "uppercase" }}>Your Name</label>
              <input value={fName} onChange={e => setFName(e.target.value)} placeholder="e.g. Mohammad Ali" onKeyDown={e => e.key === "Enter" && doFind()}
                style={{ width: "100%", padding: "12px 14px", background: "rgba(255,255,255,0.06)", border: "1.5px solid rgba(255,255,255,0.12)", borderRadius: 10, color: "#e2e8f0", fontSize: "0.9rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box", outline: "none" }} />
            </div>
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: "block", fontSize: "0.7rem", fontWeight: 600, color: "#94a3b8", marginBottom: 4, textTransform: "uppercase" }}>Phone Number</label>
              <input value={fPhone} onChange={e => setFPhone(e.target.value)} placeholder="e.g. 9876543210" onKeyDown={e => e.key === "Enter" && doFind()}
                style={{ width: "100%", padding: "12px 14px", background: "rgba(255,255,255,0.06)", border: "1.5px solid rgba(255,255,255,0.12)", borderRadius: 10, color: "#e2e8f0", fontSize: "0.9rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box", outline: "none" }} />
            </div>
            <button onClick={doFind} style={{ width: "100%", padding: "12px", background: "linear-gradient(135deg,#e65100,#ff8f00)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.92rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif", cursor: "pointer", boxShadow: "0 4px 16px rgba(230,81,0,0.3)" }}>
              Search
            </button>
          </div>

          {/* Results */}
          {fResults !== null && (fResults.length === 0 ? (
            <div style={{ background: "rgba(255,255,255,0.04)", borderRadius: 12, border: "1px solid rgba(255,255,255,0.08)", padding: "24px 20px", textAlign: "center" }}>
              <div style={{ fontSize: "2rem", marginBottom: 8 }}>😕</div>
              <p style={{ color: "#94a3b8", fontSize: "0.88rem", margin: 0 }}>No appointment found. Please check your details or contact the department.</p>
            </div>
          ) : (
            <div>
              <div style={{ fontSize: "0.76rem", color: "#64748b", marginBottom: 10 }}>{fResults.length} appointment{fResults.length > 1 ? "s" : ""} found</div>
              {fResults.map(p => {
                const statusColors = { "Date Given": { bg: "#e8f5e9", c: "#2e7d32", icon: "📅" }, "Admitted": { bg: "#e3f2fd", c: "#1565c0", icon: "🏥" }, "Operated": { bg: "#f3e5f5", c: "#6a1b9a", icon: "✅" }, "Discharged": { bg: "#fff3e0", c: "#e65100", icon: "🏠" }, "Pending": { bg: "#fff8e1", c: "#f57f17", icon: "⏳" }, "No Show": { bg: "#f5f5f5", c: "#616161", icon: "✗" } };
                const sc = statusColors[p.status] || statusColors["Date Given"];
                return <div key={p.id} style={{ background: "rgba(255,255,255,0.05)", borderRadius: 14, border: "1px solid rgba(255,255,255,0.1)", padding: "18px 16px", marginBottom: 12 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start", marginBottom: 12 }}>
                    <div>
                      <div style={{ fontSize: "1rem", fontWeight: 700, color: "#e2e8f0" }}>{p.name}</div>
                      <div style={{ fontSize: "0.76rem", color: "#64748b" }}>{p.age}y / {p.sex} · {p.phone}</div>
                    </div>
                    <div style={{ padding: "4px 10px", borderRadius: 6, background: sc.bg, color: sc.c, fontSize: "0.7rem", fontWeight: 700 }}>{sc.icon} {p.status}</div>
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                    <div style={{ background: "rgba(76,175,80,0.1)", borderRadius: 8, padding: "10px 12px", border: "1px solid rgba(76,175,80,0.2)" }}>
                      <div style={{ fontSize: "0.62rem", color: "#81c784", fontWeight: 600, textTransform: "uppercase", marginBottom: 2 }}>Scheduled Date</div>
                      <div style={{ fontSize: "0.88rem", fontWeight: 700, color: "#a5d6a7" }}>{fmtD(p.surgeryDate)}</div>
                    </div>
                    <div style={{ background: "rgba(21,101,192,0.1)", borderRadius: 8, padding: "10px 12px", border: "1px solid rgba(21,101,192,0.2)" }}>
                      <div style={{ fontSize: "0.62rem", color: "#90caf9", fontWeight: 600, textTransform: "uppercase", marginBottom: 2 }}>Diagnosis</div>
                      <div style={{ fontSize: "0.82rem", fontWeight: 600, color: "#bbdefb" }}>{p.diagnosis || p.malignancySite || "—"}</div>
                    </div>
                  </div>
                  {p.plannedProcedure && <div style={{ marginTop: 8, padding: "8px 12px", background: "rgba(255,255,255,0.03)", borderRadius: 8, border: "1px solid rgba(255,255,255,0.06)" }}>
                    <span style={{ fontSize: "0.66rem", color: "#64748b", fontWeight: 600 }}>PROCEDURE: </span>
                    <span style={{ fontSize: "0.78rem", color: "#94a3b8" }}>{p.plannedProcedure}</span>
                  </div>}
                </div>;
              })}
            </div>
          ))}
        </div>
      </div>;
    }

    // ─── HOME PAGE ───
    const statCard = (icon, label, val, color, bg) => (
      <div style={{ background: bg, borderRadius: 12, padding: "14px 16px", border: `1.5px solid ${color}20`, minWidth: 0 }}>
        <div style={{ fontSize: "1.5rem", marginBottom: 4 }}>{icon}</div>
        <div style={{ fontSize: "1.4rem", fontWeight: 800, color, lineHeight: 1 }}>{val}</div>
        <div style={{ fontSize: "0.66rem", color: "#64748b", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em", marginTop: 3 }}>{label}</div>
      </div>
    );

    return <div style={{ minHeight: "100vh", background: "linear-gradient(160deg, #0b1420 0%, #162032 40%, #1a2740 100%)", fontFamily: "'Outfit',sans-serif" }}>
      {homeFont}
      <style>{`@keyframes fadeUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}`}</style>

      {/* ═══ HERO HEADER ═══ */}
      <div style={{ textAlign: "center", padding: "50px 20px 30px" }}>
        <img src={LOGO_MD} alt="SurgTrack" style={{ width: 100, height: "auto", marginBottom: 12, display: "block", margin: "0 auto 12px" }} />
        <h1 style={{ fontFamily: "'Playfair Display',serif", fontSize: "2.2rem", color: "#fff", margin: "0 0 4px", letterSpacing: "-0.02em" }}>SurgTrack</h1>
        <p style={{ color: "#94a3b8", fontSize: "0.9rem", margin: "0 0 4px" }}>Department of Minimal Access & General Surgery</p>
        <p style={{ color: "#64748b", fontSize: "0.82rem", margin: 0 }}>Government Medical College Srinagar</p>
      </div>

      {/* ═══ QUICK ACTIONS ═══ */}
      <div style={{ maxWidth: 600, margin: "0 auto", padding: "0 16px 20px", display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap", animation: "fadeUp 0.4s ease" }}>
        <button onClick={() => setView("login")} style={{ padding: "12px 28px", background: "linear-gradient(135deg,#4caf50,#2e7d32)", color: "#fff", border: "none", borderRadius: 12, fontSize: "0.9rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif", cursor: "pointer", boxShadow: "0 4px 20px rgba(76,175,80,0.3)", display: "flex", alignItems: "center", gap: 8 }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
          Sign In to Portal
        </button>
        <button onClick={() => setView("findMyDate")} style={{ padding: "12px 24px", background: "linear-gradient(135deg,#e65100,#ff8f00)", color: "#fff", border: "none", borderRadius: 12, fontSize: "0.85rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif", cursor: "pointer", boxShadow: "0 4px 20px rgba(230,81,0,0.25)", display: "flex", alignItems: "center", gap: 6 }}>
          🔍 Know Your Appointment
        </button>
        
        
      </div>

      {/* ═══ STATISTICS DASHBOARD ═══ */}
      <div style={{ maxWidth: 640, margin: "0 auto", padding: "0 16px 30px", animation: "fadeUp 0.5s ease" }}>
        <div style={{ background: "rgba(255,255,255,0.04)", borderRadius: 16, border: "1px solid rgba(255,255,255,0.08)", padding: "20px 18px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16 }}>
            <div style={{ width: 3, height: 18, borderRadius: 2, background: "#4caf50" }} />
            <h2 style={{ margin: 0, fontSize: "0.88rem", fontWeight: 700, color: "#e2e8f0", letterSpacing: "0.02em" }}>Department Statistics</h2>
          </div>

          {/* Current Status */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(100px, 1fr))", gap: 8, marginBottom: 16 }}>
            {statCard("📅", "Dated", stats.dated || 0, "#6a1b9a", "rgba(106,27,154,0.08)")}
            {statCard("🏥", "Admitted", stats.admitted, "#1565c0", "rgba(21,101,192,0.08)")}
            {statCard("✅", "Operated", stats.operated, "#2e7d32", "rgba(46,125,50,0.08)")}
            {statCard("🏠", "Discharged", stats.discharged, "#e65100", "rgba(230,81,0,0.08)")}
          </div>

          {/* Monthly Summary */}
          <div style={{ background: "rgba(255,255,255,0.03)", borderRadius: 10, padding: "12px 14px", border: "1px solid rgba(255,255,255,0.05)" }}>
            <div style={{ fontSize: "0.68rem", fontWeight: 700, color: "#64748b", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>
              This Month — {new Date().toLocaleDateString("en-US", { month: "long", year: "numeric" })}
            </div>
            <div style={{ display: "flex", gap: 16, flexWrap: "wrap" }}>
              <div style={{ textAlign: "center" }}>
                <div style={{ fontSize: "1.5rem", fontWeight: 800, color: "#4caf50" }}>{stats.operatedThisMonth}</div>
                <div style={{ fontSize: "0.62rem", color: "#94a3b8", fontWeight: 600 }}>Surgeries</div>
              </div>
              <div style={{ width: 1, background: "rgba(255,255,255,0.08)", alignSelf: "stretch" }} />
              <div style={{ textAlign: "center" }}>
                <div style={{ fontSize: "1.5rem", fontWeight: 800, color: "#64b5f6" }}>{stats.benignOps}</div>
                <div style={{ fontSize: "0.62rem", color: "#94a3b8", fontWeight: 600 }}>Benign</div>
              </div>
              <div style={{ textAlign: "center" }}>
                <div style={{ fontSize: "1.5rem", fontWeight: 800, color: "#ef5350" }}>{stats.malOps}</div>
                <div style={{ fontSize: "0.62rem", color: "#94a3b8", fontWeight: 600 }}>Malignant</div>
              </div>
              <div style={{ width: 1, background: "rgba(255,255,255,0.08)", alignSelf: "stretch" }} />
              <div style={{ textAlign: "center" }}>
                <div style={{ fontSize: "1.5rem", fontWeight: 800, color: "#ffb74d" }}>{stats.dischargedThisMonth}</div>
                <div style={{ fontSize: "0.62rem", color: "#94a3b8", fontWeight: 600 }}>Discharged</div>
              </div>
            </div>
          </div>

          {/* Total */}
          <div style={{ marginTop: 12, textAlign: "center" }}>
            <span style={{ fontSize: "0.72rem", color: "#475569" }}>Total patients in system: </span>
            <span style={{ fontSize: "0.82rem", color: "#e2e8f0", fontWeight: 700 }}>{stats.total}</span>
          </div>
        </div>
      </div>

      {/* ═══ FOOTER ═══ */}
      <div style={{ textAlign: "center", padding: "20px 16px 40px" }}>
        <p style={{ color: "#334155", fontSize: "0.68rem", margin: 0 }}>SurgTrack v1.0 — Dept. of Minimal Access & General Surgery, GMC Srinagar</p>
      </div>
    </div>;
  }

  if (view === "login") return (
    <div style={S.loginBg}><link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Playfair+Display:wght@700&display=swap" rel="stylesheet" />
      <div style={S.loginCard}>
        <div style={{ marginBottom: 8 }}>
          <button onClick={() => setView("home")} style={{ border: "none", background: "none", color: "#64748b", cursor: "pointer", fontSize: "0.78rem", fontFamily: "'Outfit',sans-serif", padding: 0 }}>← Back to Home</button>
        </div>
        <div style={{ textAlign: "center", mb: 28, marginBottom: 28 }}>
          <img src={LOGO_MD} alt="SurgTrack" style={{ width: 80, height: "auto", display: "block", margin: "0 auto 10px" }} />
          <h1 style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.9rem", color: "#0b1420", margin: "0 0 2px" }}>SurgTrack</h1>
          <p style={{ color: "#64748b", fontSize: "0.82rem", margin: 0 }}>Surgical Patient Management</p>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div><label style={S.label}>Username</label><input style={S.input} placeholder="Username" value={lf.u} onChange={e => setLf({ ...lf, u: e.target.value })} onKeyDown={e => e.key === "Enter" && doLogin()} /></div>
          <div><label style={S.label}>PIN</label><input style={S.input} type="password" placeholder="PIN" value={lf.p} onChange={e => setLf({ ...lf, p: e.target.value })} onKeyDown={e => e.key === "Enter" && doLogin()} maxLength={6} /></div>
          {lErr && <p style={{ color: "#c62828", fontSize: "0.82rem", margin: 0 }}>{lErr}</p>}
          <button style={S.btnP} onClick={doLogin}>Sign In</button>
        </div>
        <div style={{ marginTop: 20, paddingTop: 12, borderTop: "1px solid #e2e8f0", fontSize: "0.72rem", color: "#94a3b8", textAlign: "center" }}>
          SurgTrack — Surgical Patient Management
        </div>
      </div>
    </div>
  );

  return (
    <>
    {/* ═══ TOP-RIGHT USER MENU — rendered outside all containers for true fixed positioning ═══ */}
    {userMenu && <div onClick={() => setUserMenu(false)} style={{ position: "fixed", inset: 0, zIndex: 9800, background: "transparent" }} />}
    <div style={{ position: "fixed", top: 12, right: 16, zIndex: 9900 }}>
      <div onClick={() => { if (["admin","resident","faculty"].includes(me.role)) setUserMenu(prev => !prev); }} style={{ width: 36, height: 36, borderRadius: "50%", background: me.photo ? "none" : (ROLE_COLORS[me.role]?.bg || "#f5f5f5"), display: "flex", alignItems: "center", justifyContent: "center", fontSize: "0.78rem", fontWeight: 700, color: ROLE_COLORS[me.role]?.color || "#616161", cursor: ["admin","resident","faculty"].includes(me.role) ? "pointer" : "default", overflow: "hidden", border: `2.5px solid ${ROLE_COLORS[me.role]?.b || "#e2e8f0"}`, boxShadow: "0 2px 12px rgba(0,0,0,0.2)" }}>
        {me.photo ? <img src={me.photo} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : me.name.charAt(0)}
      </div>
      {userMenu && <div style={{ position: "absolute", top: 42, right: 0, background: "#fff", borderRadius: 12, boxShadow: "0 10px 40px rgba(0,0,0,0.25)", border: "1px solid #e2e8f0", minWidth: 210, overflow: "hidden", animation: "slideUp 0.15s ease" }}>
        <div style={{ padding: "10px 14px", borderBottom: "1px solid #f1f5f9", background: "#f8fafc" }}>
          <div style={{ fontSize: "0.82rem", fontWeight: 600, color: "#1e293b" }}>{me.name}</div>
          <div style={{ fontSize: "0.66rem", color: "#64748b", textTransform: "uppercase", letterSpacing: "0.04em" }}>{ROLE_LABELS[me.role]}</div>
        </div>
        <div style={{ padding: "6px" }}>
          {[
            { icon: "👤", label: "My Profile", pg: "profile", show: true },
            { icon: "📋", label: "My Patients", pg: "mypatients", show: me.linkedSurgeon && me.linkStatus === "approved" },
            { icon: "📊", label: "My Stats", pg: "mystats", show: me.linkedSurgeon && me.linkStatus === "approved" },
            { icon: "⚙️", label: "Settings", pg: "settings", show: perms.manageUsers },
          ].filter(x => x.show).map(x => (
            <button key={x.pg} onClick={() => { setPage(x.pg); setUserMenu(false); setSideOpen(false); }} style={{ width: "100%", textAlign: "left", padding: "9px 12px", border: "none", background: page === x.pg ? "#e3f2fd" : "transparent", borderRadius: 8, fontSize: "0.8rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer", color: page === x.pg ? "#1565c0" : "#1e293b", fontWeight: page === x.pg ? 600 : 400, display: "flex", alignItems: "center", gap: 8 }}>{x.icon} {x.label}</button>
          ))}
          {(!me.linkedSurgeon || me.linkStatus !== "approved") && <div style={{ padding: "8px 12px", fontSize: "0.72rem", color: "#94a3b8" }}>{"📋"} My Patients <span style={{ fontSize: "0.58rem", color: "#e65100" }}>🔗 Link profile first</span></div>}
        </div>
        <div style={{ padding: "4px 6px", borderTop: "1px solid #f1f5f9" }}>
          <button onClick={() => { setUserMenu(false); doLogout(); }} style={{ width: "100%", textAlign: "left", padding: "9px 12px", border: "none", background: "transparent", borderRadius: 8, fontSize: "0.8rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer", color: "#c62828", display: "flex", alignItems: "center", gap: 8 }}>{"🚪"} Sign Out</button>
        </div>
      </div>}
    </div>

    <div style={{ display: "flex", minHeight: "100vh", background: "#f1f5f9", fontFamily: "'Outfit',sans-serif" }}>
      <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Playfair+Display:wght@700&display=swap" rel="stylesheet" />
      <style>{`@keyframes slideUp{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@media(max-width:767px){.st-sidebar{position:fixed!important;left:0;top:0;z-index:9000;transform:translateX(-100%);transition:transform 0.25s ease}.st-sidebar.open{transform:translateX(0)}.st-main{margin-left:0!important;height:auto!important;min-height:100vh}.st-content{padding:14px!important}.st-topbar{display:flex!important}}`}</style>
      {toast && <div style={{ position: "fixed", top: 20, left: "50%", transform: "translateX(-50%)", padding: "12px 28px", borderRadius: 12, color: "#fff", fontFamily: "'Outfit',sans-serif", fontSize: "0.9rem", fontWeight: 600, zIndex: 99999, boxShadow: "0 8px 32px rgba(0,0,0,0.3)", background: toast.t === "error" ? "linear-gradient(135deg,#c62828,#e53935)" : "linear-gradient(135deg,#2e7d32,#43a047)", maxWidth: "90vw", textAlign: "center", animation: "slideUp 0.2s ease" }}>{toast.t === "error" ? "⚠️ " : "✅ "}{toast.m}</div>}
      {confirm && <div style={S.modOv}><div style={S.mod}><p style={{ margin: "0 0 18px", fontSize: "0.95rem" }}>{confirm.msg}</p><div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}><button style={S.btnS} onClick={() => setConfirm(null)}>Cancel</button><button style={{ ...S.btnP, background: "#c62828", padding: "8px 20px" }} onClick={confirm.fn}>Delete</button></div></div></div>}
      {noteViewModal && <div style={S.modOv}><div style={{ ...S.mod, maxWidth: 440 }}>
        <h3 style={{ margin: "0 0 6px", fontSize: "1rem", fontWeight: 700, color: "#1565c0" }}>{"📝"} Notes — {noteViewModal.name}</h3>
        <div style={{ padding: "12px 14px", background: "#f8fafc", borderRadius: 10, border: "1px solid #e2e8f0", marginTop: 10, marginBottom: 14, whiteSpace: "pre-wrap", fontSize: "0.88rem", color: "#1e293b", lineHeight: 1.6, maxHeight: "50vh", overflowY: "auto" }}>{noteViewModal.notes}</div>
        <div style={{ display: "flex", justifyContent: "flex-end" }}><button onClick={() => setNoteViewModal(null)} style={{ padding: "8px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Close</button></div>
      </div></div>}
      {deletePinModal && <div style={S.modOv}><div style={S.mod}>
        <h3 style={{ margin: "0 0 8px", fontSize: "1rem", color: "#c62828" }}>🔐 Admin Verification Required</h3>
        <p style={{ margin: "0 0 14px", fontSize: "0.84rem", color: "#64748b" }}>To {deletePinModal.action === "cancelAdmission" ? "cancel admission for" : deletePinModal.action === "removeFromList" ? "remove from surgery list:" : "delete"} <strong>{deletePinModal.patient.name}</strong>, enter your admin PIN:</p>
        {deletePinModal.action === "cancelAdmission" && <p style={{ margin: "0 0 10px", fontSize: "0.74rem", color: "#e65100", background: "#fff3e0", padding: "6px 10px", borderRadius: 6 }}>⚠️ This will remove all clinical data and revert patient to appointment-only status.</p>}
        {deletePinModal.action === "removeFromList" && <p style={{ margin: "0 0 10px", fontSize: "0.74rem", color: "#e65100", background: "#fff3e0", padding: "6px 10px", borderRadius: 6 }}>⚠️ Patient will be removed from surgery list but will remain in admissions.</p>}
        <input type="password" placeholder="Enter PIN" value={deletePin} onChange={e => setDeletePin(e.target.value)} onKeyDown={e => e.key === "Enter" && confirmDeleteWithPin()} style={{ width: "100%", padding: "10px 14px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "1rem", fontFamily: "'Outfit',sans-serif", textAlign: "center", letterSpacing: "0.2em", boxSizing: "border-box", marginBottom: 14 }} autoFocus />
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <button style={S.btnS} onClick={() => { setDeletePinModal(null); setDeletePin(""); }}>Cancel</button>
          <button style={{ ...S.btnP, background: "#c62828", padding: "8px 20px" }} onClick={confirmDeleteWithPin}>{deletePinModal.action === "cancelAdmission" ? "Cancel Admission" : deletePinModal.action === "removeFromList" ? "Remove from List" : "Delete"}</button>
        </div>
      </div></div>}
      {reschedModal && <div style={S.modOv}><div style={S.mod}>
        <h3 style={{ margin: "0 0 4px", fontSize: "1rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif" }}>Reschedule Patient</h3>
        <p style={{ margin: "0 0 14px", fontSize: "0.84rem", color: "#64748b" }}>Change date for <strong>{reschedModal.patient.name}</strong></p>
        <p style={{ margin: "0 0 6px", fontSize: "0.78rem", color: "#94a3b8" }}>Current: {fmtD(reschedModal.patient.surgeryDate)}</p>
        <label style={S.label}>New Date</label>
        <input style={S.input} type="date" value={reschedModal.newDate || ""} onChange={e => setReschedModal({ ...reschedModal, newDate: e.target.value })} />
        {reschedModal.newDate && (() => {
          const datePts = patients.filter(p => p.surgeryDate === reschedModal.newDate && p.id !== reschedModal.patient.id);
          if (datePts.length === 0) return <div style={{ marginTop: 8, fontSize: "0.76rem", color: "#94a3b8" }}>No patients on this date yet.</div>;
          return <div style={{ marginTop: 8, fontSize: "0.76rem", color: "#64748b" }}>{datePts.length} patient(s) already on this date.</div>;
        })()}
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}><button style={S.btnS} onClick={() => setReschedModal(null)}>Cancel</button><button style={S.btnP} onClick={doReschedule}>Reschedule</button></div>
      </div></div>}

      {/* Discharge Modal */}
      {dischargeModal && <div style={S.modOv}><div style={S.mod}>
        <h3 style={{ margin: "0 0 4px", fontSize: "1rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif" }}>🏠 Discharge Patient</h3>
        <p style={{ margin: "0 0 14px", fontSize: "0.84rem", color: "#64748b" }}>Discharge <strong>{dischargeModal.patient.name}</strong></p>
        <label style={S.label}>Reason for Discharge</label>
        <textarea style={{ ...S.input, minHeight: 60, resize: "vertical" }} value={dischargeModal.reason} onChange={e => setDischargeModal({ ...dischargeModal, reason: e.target.value })} placeholder="e.g. LAMA, Unfit for surgery, Conservative management..." />
        <label style={{ ...S.label, marginTop: 10 }}>Reschedule Date (optional)</label>
        <input type="date" style={S.input} value={dischargeModal.reschedDate || ""} onChange={e => setDischargeModal({ ...dischargeModal, reschedDate: e.target.value })} />
        <p style={{ margin: "4px 0 0", fontSize: "0.7rem", color: "#94a3b8" }}>Leave empty if no follow-up surgery planned.</p>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
          <button style={S.btnS} onClick={() => setDischargeModal(null)}>Cancel</button>
          <button style={S.btnP} onClick={doDischargeWithoutSurgery}>Discharge</button>
        </div>
      </div></div>}

      {/* Mobile overlay backdrop */}
      {sideOpen && <div onClick={() => setSideOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", zIndex: 8999 }} />}

      {/* ═══ LEFT SIDEBAR — Pages ═══ */}
      <aside className={`st-sidebar${sideOpen ? " open" : ""}`} style={S.sidebar}>
        <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
          <div style={{ padding: "20px 14px 18px", display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
            <img src={LOGO_SM} alt="SurgTrack" style={{ width: 34, height: 34, flexShrink: 0 }} />
            <div><div style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.05rem", color: "#fff", lineHeight: 1.1 }}>SurgTrack</div>
            <div style={{ fontSize: "0.56rem", color: "#64748b", letterSpacing: "0.08em", textTransform: "uppercase" }}>Surgery Manager</div></div>
          </div>

          {/* Slide-up user menu */}
          <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
            {/* Main nav */}
            <div style={{ padding: "0 10px", display: "flex", flexDirection: "column", gap: 4, flex: 1, overflowY: "auto" }}>
              <button onClick={() => { if (page !== "appointments") { setPage("appointments"); setView("dashboard"); } setSideOpen(false); }} style={page === "appointments" ? S.sideItemOn : S.sideItem}>
                <span>📅</span> Appointments
              </button>
              <button onClick={() => { setPage("admissions"); setView("admitted"); setSearch(""); setSideOpen(false); }} style={page === "admissions" ? S.sideItemOn : S.sideItem}>
                <span>🏥</span> Admissions
                {patients.filter(p => p.status === "Admitted").length > 0 && <span style={S.sideBadge}>{patients.filter(p => p.status === "Admitted").length}</span>}
              </button>
              <button onClick={() => { setPage("listed"); setSearch(""); setSideOpen(false); }} style={page === "listed" ? S.sideItemOn : S.sideItem}>
                <span>🔪</span> Listed
                {patients.filter(p => p.clinical?.listStatus === "Listed").length > 0 && <span style={{ ...S.sideBadge, background: "#6a1b9a" }}>{patients.filter(p => p.clinical?.listStatus === "Listed").length}</span>}
              </button>
              <button onClick={() => { setPage("operated"); setSearch(""); setSideOpen(false); }} style={page === "operated" ? S.sideItemOn : S.sideItem}>
                <span>✅</span> Operated
                {patients.filter(p => p.status === "Operated").length > 0 && <span style={{ ...S.sideBadge, background: "#2e7d32" }}>{patients.filter(p => p.status === "Operated").length}</span>}
              </button>
              <button onClick={() => { setPage("discharged"); setSearch(""); setSideOpen(false); }} style={page === "discharged" ? S.sideItemOn : S.sideItem}>
                <span>🏠</span> Discharged
                {patients.filter(p => p.status === "Discharged").length > 0 && <span style={{ ...S.sideBadge, background: "#6a1b9a" }}>{patients.filter(p => p.status === "Discharged").length}</span>}
              </button>
              <div style={{ borderTop: "1px solid #334155", margin: "6px 0" }} />
              <button onClick={() => { setPage("dutyRoster"); setSideOpen(false); }} style={page === "dutyRoster" ? S.sideItemOn : S.sideItem}>
                <span>📋</span> <span>Duty Roster</span>
              </button>
              <button onClick={() => { setPage("acadRoster"); setSideOpen(false); }} style={page === "acadRoster" ? S.sideItemOn : S.sideItem}>
                <span>🎓</span> <span>Academic Roster</span>
              </button>
              {(config.researchProtocols || []).length > 0 && <>
                <div style={{ borderTop: "1px solid #334155", margin: "6px 0" }} />
                <button onClick={() => { setPage("research"); setSideOpen(false); }} style={page === "research" ? S.sideItemOn : S.sideItem}>
                  <span>🔬</span> Research
                  {patients.filter(p => (p.researchProtocols || []).length > 0).length > 0 && <span style={{ ...S.sideBadge, background: "#7c3aed" }}>{patients.filter(p => (p.researchProtocols || []).length > 0).length}</span>}
                </button>
              </>}
            </div>

            {/* Account menu items moved to top-right avatar dropdown */}
          </div>
        </div>
        {/* User footer — simplified */}
        <div style={{ padding: "10px 14px", borderTop: "1px solid #1e293b", flexShrink: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{ fontSize: "0.72rem", color: "#64748b", flex: 1, overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis" }}>{me.name} · {ROLE_LABELS[me.role]}</div>
            <button style={S.navB} onClick={doLogout} title="Sign out">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
            </button>
          </div>
        </div>
      </aside>

      {/* ═══ MAIN CONTENT ═══ */}
      <main className="st-main" style={S.main}>
        {/* Mobile top bar */}
        <div style={{ display: "none", padding: "10px 14px", background: "#0b1420", alignItems: "center", justifyContent: "space-between", position: "sticky", top: 0, zIndex: 100 }} className="st-topbar">
          <button onClick={() => setSideOpen(true)} style={{ border: "none", background: "none", color: "#fff", fontSize: "1.3rem", cursor: "pointer", padding: "4px 8px" }}>☰</button>
          <span style={{ fontFamily: "'Playfair Display',serif", fontSize: "1rem", color: "#fff" }}>SurgTrack</span>
          <div style={{ width: 36 }} />{/* spacer — avatar is fixed position above */}
        </div>

        {/* Appointments Page — with tabs */}
        {page === "appointments" && <>
          <div style={S.tabs}>
            {[{ id: "dashboard", l: "📊 Dashboard" }, { id: "patients", l: "📋 All Patients" },
              ...(perms.schedule ? [{ id: "schedule", l: "➕ Give Date", accent: true }] : []),
              ...(perms.addEmergency ? [{ id: "emergency", l: "🚨 Emergency", accent: true }] : []),
              { id: "pending", l: "⏳ Pending", count: patients.filter(p => p.status === "Pending").length, warn: true },
            ].map(t => <button key={t.id} onClick={() => { setView(t.id); if (t.id === "schedule") { setEditId(null); setPf({ ...empty }); } setSearch(""); setFCat("all"); setFType("all"); setSelDate(""); }}
              style={t.accent ? (t.id === "emergency" ? { ...S.tabA, background: "linear-gradient(135deg,#c62828,#e53935)", borderColor: "#c62828" } : S.tabA) : (view === t.id ? S.tabOn : S.tab)}>
              {t.l}{t.count != null && t.count > 0 && <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", minWidth: 18, height: 18, borderRadius: 9, background: t.warn ? "#e65100" : "#1565c0", color: "#fff", fontSize: "0.6rem", fontWeight: 700, marginLeft: 5, padding: "0 4px" }}>{t.count}</span>}
            </button>)}
          </div>
          <div className="st-content" style={S.content}>

        {view === "dashboard" && <>
          {/* Summary Cards */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(130px,1fr))", gap: 10, marginBottom: 20 }}>
            {[
              { n: patients.filter(p => (p.surgeryDate === todayS || p.originalDate === todayS) && p.status !== "Operated" && p.status !== "Discharged").length, l: "Today Listed", c: "#c62828", bg: "#fef2f2" },
              { n: patients.filter(p => p.surgeryDate === todayS && p.status === "Admitted").length, l: "Today Admitted", c: "#1565c0", bg: "#eff6ff" },
              { n: patients.filter(p => p.surgeryDate === todayS && p.status === "Date Given").length, l: "Remaining", c: "#e65100", bg: "#fff3e0" },
              { n: patients.filter(p => p.status === "Date Given").length, l: "Total Scheduled", c: "#2e7d32", bg: "#f0fdf4" },
              { n: patients.filter(p => p.isEmergency && (p.status === "Admitted" || p.status === "Operated")).length, l: "Emergency", c: "#c62828", bg: "#fef2f2" },
            ].map((s, i) => (
              <div key={i} style={{ background: s.bg, borderRadius: 10, padding: "14px 12px", borderLeft: `4px solid ${s.c}` }}>
                <div style={{ fontSize: "1.5rem", fontWeight: 800, color: s.c, lineHeight: 1 }}>{s.n}</div>
                <div style={{ fontSize: "0.65rem", fontWeight: 600, color: "#64748b", textTransform: "uppercase", letterSpacing: "0.04em", marginTop: 3 }}>{s.l}</div>
              </div>
            ))}
          </div>

          {/* Today's Appointments Download */}
          {(() => {
            const addedToday = patients.filter(p => {
              if (!p.createdAt) return false;
              const d = new Date(p.createdAt);
              return fmt(d) === todayS;
            });
            if (addedToday.length === 0) return null;
            const downloadList = () => {
              const byDate = {};
              addedToday.forEach(p => {
                const d = p.surgeryDate || "No Date";
                if (!byDate[d]) byDate[d] = [];
                byDate[d].push(p);
              });
              const sortedDates = Object.keys(byDate).sort();
              let rows = "";
              sortedDates.forEach(d => {
                const pts = byDate[d];
                rows += `<tr style="background:#e8f5e9"><td colspan="8" style="font-weight:700;font-size:13px;padding:8px 10px;border:1px solid #c8e6c9">Surgery Date: ${d !== "No Date" ? fmtD(d) : "Not Assigned"} (${pts.length} patient${pts.length > 1 ? "s" : ""})</td></tr>`;
                pts.forEach((p, i) => {
                  const cat = p.type === "malignancy" ? `Malignancy - ${p.malignancySite || ""}` : (p.benignCategory || "General");
                  rows += `<tr><td style="border:1px solid #e0e0e0;padding:6px 8px;text-align:center">${i+1}</td><td style="border:1px solid #e0e0e0;padding:6px 8px;font-weight:600">${p.name}</td><td style="border:1px solid #e0e0e0;padding:6px 8px;text-align:center">${p.age || ""}/${p.sex || ""}</td><td style="border:1px solid #e0e0e0;padding:6px 8px">${p.phone || ""}</td><td style="border:1px solid #e0e0e0;padding:6px 8px">${p.diagnosis || ""}</td><td style="border:1px solid #e0e0e0;padding:6px 8px">${p.plannedProcedure || ""}</td><td style="border:1px solid #e0e0e0;padding:6px 8px;font-size:11px">${cat}</td><td style="border:1px solid #e0e0e0;padding:6px 8px;font-size:11px;color:#666">${p.notes || ""}</td></tr>`;
                });
              });
              const html = `<html><head><meta charset="utf-8"><style>@page{size:A4 landscape;margin:1.5cm}body{font-family:'Segoe UI',Arial,sans-serif;font-size:12px;color:#222}table{width:100%;border-collapse:collapse}th{background:#1565c0;color:#fff;padding:8px 10px;text-align:left;font-size:12px;border:1px solid #1565c0}td{vertical-align:top}</style></head><body><div style="text-align:center;margin-bottom:12px"><h2 style="margin:0;font-size:16px">SurgTrack — Appointments Added Today</h2><p style="margin:2px 0;color:#666;font-size:12px">Generated: ${new Date().toLocaleDateString("en-IN",{weekday:"long",day:"numeric",month:"long",year:"numeric"})} at ${new Date().toLocaleTimeString("en-IN",{hour:"2-digit",minute:"2-digit"})}</p><p style="margin:2px 0;font-size:12px"><b>Total: ${addedToday.length}</b> appointment(s) across <b>${sortedDates.length}</b> surgery date(s)</p></div><table><thead><tr><th>#</th><th>Patient Name</th><th>Age/Sex</th><th>Phone</th><th>Diagnosis</th><th>Planned Procedure</th><th>Category</th><th>Notes</th></tr></thead><tbody>${rows}</tbody></table><div style="margin-top:16px;font-size:11px;color:#888;text-align:center">Dept. of Minimal Access & General Surgery</div></body></html>`;
              const blob = new Blob([html], { type: "application/vnd.ms-word" });
              const a = document.createElement("a"); a.href = URL.createObjectURL(blob);
              a.download = "Appointments_Added_" + todayS + ".doc"; a.click(); URL.revokeObjectURL(a.href);
            };
            return <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 14px", background: "linear-gradient(135deg,#eff6ff,#f0fdf4)", borderRadius: 10, border: "1px solid #bfdbfe", marginBottom: 16 }}>
              <div>
                <div style={{ fontSize: "0.82rem", fontWeight: 700, color: "#1565c0" }}>{"📋"} {addedToday.length} Appointment{addedToday.length > 1 ? "s" : ""} Added Today</div>
                <div style={{ fontSize: "0.66rem", color: "#64748b", marginTop: 2 }}>Grouped by surgery date — download as document</div>
              </div>
              <button onClick={downloadList} style={{ padding: "8px 16px", background: "linear-gradient(135deg,#1565c0,#1976d2)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.76rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif", display: "flex", alignItems: "center", gap: 5, whiteSpace: "nowrap" }}>{"⬇"} Download</button>
            </div>;
          })()}

          {/* Swipeable Upcoming Admission Cards */}
          <h2 style={S.secT}>Upcoming Admission — {DAY_NAMES[config.admissionDay]}s</h2>
          <div style={{ position: "relative", marginBottom: 24 }}>
            <div style={{ overflow: "hidden", borderRadius: 12 }}>
              {nextDts.length > 0 && (() => {
                const d = nextDts[carIdx % nextDts.length];
                const ds = fmt(d); const si = slotInfo(ds); const isT = ds === todayS;
                return (
                  <div style={{ background: "#fff", borderRadius: 12, padding: 18, border: isT ? "2px solid #c62828" : "1px solid #e2e8f0", cursor: "pointer", transition: "all 0.2s" }} onClick={() => { setSelDate(ds); setView("patients"); }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
                      <span style={{ fontWeight: 700, fontSize: "1rem", color: isT ? "#c62828" : "#1e293b" }}>{isT ? "📍 TODAY — " : ""}{fmtD(ds)}</span>
                      <span style={{ fontSize: "0.7rem", color: "#94a3b8" }}>Tap to view all →</span>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                      {Object.keys(si).map(c => { const s = si[c]; if (!mergedBenignCats[c]) return null; const full = s.avail <= 0; return (
                        <div key={c} style={{ padding: "7px 10px", borderRadius: 8, background: full ? "#fef2f2" : "#f8fafc", border: `1px solid ${full ? "#fecaca" : "#e2e8f0"}`, fontSize: "0.76rem" }}>
                          <span style={{ fontWeight: 600, color: mergedBenignCats[c].color }}>{mergedBenignCats[c].icon} {mergedBenignCats[c].label}</span>
                          <div style={{ color: full ? "#c62828" : "#64748b", fontWeight: 500 }}>{s.used}/{s.total}{full ? " FULL" : ""}</div>
                        </div>
                      ); })}
                    </div>
                    <div style={{ marginTop: 8, fontSize: "0.76rem", color: "#b71c1c", fontWeight: 500 }}>
                      🔴 Malignancy: {patients.filter(p => p.surgeryDate === ds && p.type === "malignancy").length}
                    </div>
                  </div>
                );
              })()}
            </div>
            {/* Navigation arrows */}
            <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 16, marginTop: 12 }}>
              <button onClick={() => setCarIdx(Math.max(0, carIdx - 1))} disabled={carIdx === 0}
                style={{ width: 36, height: 36, borderRadius: "50%", border: "1.5px solid #e2e8f0", background: carIdx === 0 ? "#f8fafc" : "#fff", cursor: carIdx === 0 ? "default" : "pointer", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "1rem", color: carIdx === 0 ? "#cbd5e1" : "#475569", fontWeight: 700 }}>‹</button>
              {/* Dot indicators */}
              <div style={{ display: "flex", gap: 6 }}>
                {nextDts.slice(0, 8).map((_, i) => (
                  <div key={i} onClick={() => setCarIdx(i)} style={{ width: i === carIdx ? 18 : 7, height: 7, borderRadius: 4, background: i === carIdx ? "#2e7d32" : "#cbd5e1", cursor: "pointer", transition: "all 0.2s" }} />
                ))}
              </div>
              <button onClick={() => setCarIdx(Math.min(nextDts.length - 1, carIdx + 1))} disabled={carIdx >= nextDts.length - 1}
                style={{ width: 36, height: 36, borderRadius: "50%", border: "1.5px solid #e2e8f0", background: carIdx >= nextDts.length - 1 ? "#f8fafc" : "#fff", cursor: carIdx >= nextDts.length - 1 ? "default" : "pointer", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "1rem", color: carIdx >= nextDts.length - 1 ? "#cbd5e1" : "#475569", fontWeight: 700 }}>›</button>
            </div>
          </div>

          {/* Today's Tentative List — Grouped Table */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
            <h2 style={{ ...S.secT, margin: 0 }}>📋 Today's List — {fmtD(todayS)}</h2>
            <button onClick={async () => {
              const todayPts = patients.filter(p => (p.surgeryDate === todayS || p.originalDate === todayS) && p.status !== "Operated" && p.status !== "Discharged");
              if (todayPts.length === 0) { show("No patients in today's list.", "error"); return; }
              const names = todayPts.map((p, i) => `${i + 1}. ${p.name} (${p.diagnosis || p.malignancySite || p.plannedProcedure || ""})`).join(", ");
              const body = `${todayPts.length} patient${todayPts.length > 1 ? "s" : ""} — ${names}`;
              await notify(`📅 Today's List — ${fmtD(todayS)}`, body.length > 200 ? body.slice(0, 197) + "…" : body, "appointments");
              show("Today's list notification sent.");
            }} style={{ display: "flex", alignItems: "center", gap: 5, padding: "6px 12px", borderRadius: 8, border: "1.5px solid #f59e0b", background: "#fffbeb", color: "#92400e", fontWeight: 600, fontSize: "0.74rem", cursor: "pointer", fontFamily: "'Outfit',sans-serif", whiteSpace: "nowrap" }}>🔔 Notify</button>
          </div>
          {(() => {
            const todayPts = patients.filter(p => (p.surgeryDate === todayS || p.originalDate === todayS) && p.status !== "Operated" && p.status !== "Discharged")
              .sort((a, b) => {
                const catOrd = { gallbladder: 1, hernia: 2, obesity: 3, others: 4 };
                if (a.type === "malignancy" && b.type !== "malignancy") return -1;
                if (a.type !== "malignancy" && b.type === "malignancy") return 1;
                return (catOrd[a.benignCategory] ?? 99) - (catOrd[b.benignCategory] ?? 99);
              });
            if (todayPts.length === 0) return <div style={S.empty}>No patients listed for today.{perms.schedule && " Schedule patients via 'Give Date'."}</div>;

            // Group by type+category
            const groups = [];
            let lastKey = "";
            todayPts.forEach(p => {
              const key = p.type === "malignancy" ? "malignancy" : (p.benignCategory || "others");
              if (key !== lastKey) { groups.push({ key, patients: [] }); lastKey = key; }
              groups[groups.length - 1].patients.push(p);
            });

            return (
              <div style={{ background: "#fff", borderRadius: 12, border: "1px solid #e2e8f0", overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.8rem", minWidth: 580 }}>
                  <thead><tr>
                    <th style={{ ...S.th, width: 28 }}>#</th>
                    <th style={S.th}>Patient</th>
                    <th style={S.th}>Diagnosis / Site</th>
                    <th style={S.th}>Procedure</th>
                    <th style={{ ...S.th, width: 70 }}>Status</th>
                    {perms.admit && <th style={{ ...S.th, width: 160, textAlign: "right" }}>Actions</th>}
                  </tr></thead>
                  <tbody>
                    {groups.map(g => {
                      const isMal = g.key === "malignancy";
                      const catInfo = mergedBenignCats[g.key];
                      const catColor = isMal ? "#c62828" : (catInfo?.color || "#6a1b9a");
                      const catLabel = isMal ? "🔴 Malignancy" : `${catInfo?.icon || "🟣"} ${catInfo?.label || g.key}`;
                      const slotStr = !isMal && config.slots[g.key] ? ` — ${g.patients.length}/${config.slots[g.key]} slots` : ` — ${g.patients.length} patient${g.patients.length > 1 ? "s" : ""}`;
                      return [
                        <tr key={g.key + "-hdr"}>
                          <td colSpan={perms.admit ? 6 : 5} style={{ padding: "8px 12px", background: catColor + "0a", borderBottom: `2px solid ${catColor}22`, fontWeight: 700, fontSize: "0.76rem", color: catColor, letterSpacing: "0.03em" }}>
                            {catLabel}<span style={{ fontWeight: 500, color: "#94a3b8" }}>{slotStr}</span>
                          </td>
                        </tr>,
                        ...g.patients.map((p, idx) => {
                          const isAdmitted = p.status === "Admitted";
                          const isNoShow = p.status === "No Show";
                          const isPending = p.status === "Pending";
                          const isCancelled = p.status === "Cancelled";
                          const isInactive = isNoShow || isPending || isCancelled;
                          const rowBg = isAdmitted ? "#f0fdf4" : isNoShow ? "#fafafa" : isPending ? "#fffde7" : "#fff";
                          return (
                            <tr key={p.id} style={{ borderBottom: "1px solid #f1f5f9", background: rowBg, opacity: isInactive ? 0.65 : 1 }}>
                              <td style={{ ...S.td, color: "#94a3b8", fontWeight: 600, textAlign: "center" }}>{idx + 1}</td>
                              <td style={S.td}>
                                <div style={{ fontWeight: 600, color: "#1e293b", fontSize: "0.84rem" }}>{p.name}{p.surgeryDate !== (p.originalDate || p.surgeryDate) && <span style={{ fontSize: "0.6rem", color: "#e65100", marginLeft: 4 }}>↻ rescheduled</span>}{p.isEmergency && <span style={{ fontSize: "0.54rem", padding: "1px 4px", borderRadius: 3, background: "#fef2f2", color: "#c62828", fontWeight: 700, marginLeft: 4 }}>EMG</span>}{p.notes && <button onClick={(e) => { e.stopPropagation(); setNoteViewModal({ name: p.name, notes: p.notes }); }} title="View Notes" style={{ border: "none", background: "#eff6ff", color: "#1565c0", cursor: "pointer", fontSize: "0.6rem", fontWeight: 700, padding: "1px 5px", borderRadius: 4, marginLeft: 4, verticalAlign: "middle" }}>{"📝"}</button>}</div>
                                <div style={{ color: "#94a3b8", fontSize: "0.72rem" }}>{p.age ? p.age + "y/" : ""}{p.sex?.[0] || ""}{p.phone ? " · " + p.phone : ""}</div>
                              </td>
                              <td style={{ ...S.td, maxWidth: 170, fontSize: "0.78rem" }}>
                                {isMal ? <>{p.malignancySite}{p.malignancyPlan && <> · <span style={{ color: p.malignancyPlan === "Palliative" ? "#e65100" : "#2e7d32", fontWeight: 600 }}>{p.malignancyPlan}</span></>}</> : (p.diagnosis || "—")}
                              </td>
                              <td style={{ ...S.td, maxWidth: 170, fontSize: "0.78rem", color: "#64748b" }}>{p.plannedProcedure || "—"}</td>
                              <td style={S.td}>
                                {isAdmitted ? <Bdg bg="#e8f5e9" color="#2e7d32" border="#a5d6a7">Admitted</Bdg> :
                                 isNoShow ? <Bdg bg="#f5f5f5" color="#616161" border="#bdbdbd">No Show</Bdg> :
                                 isPending ? <Bdg bg="#fff3e0" color="#e65100" border="#ffcc80">Pending</Bdg> :
                                 isCancelled ? <Bdg bg="#fce4ec" color="#c62828" border="#ef9a9a">Cancelled</Bdg> :
                                  <Bdg bg="#eff6ff" color="#1565c0" border="#bfdbfe">Date Given</Bdg>}
                              </td>
                              {perms.admit && <td style={{ ...S.td, textAlign: "right", whiteSpace: "nowrap" }}>
                                {p.status === "Date Given" ? <>
                                  <button onClick={() => doAdmit(p)} title="Admit" style={{ ...S.actBtn, background: "#e8f5e9", color: "#2e7d32", borderColor: "#a5d6a7" }}>✅</button>
                                  <button onClick={() => setReschedModal({ patient: p, newDate: "" })} title="Change Date" style={{ ...S.actBtn, color: "#1565c0", borderColor: "#90caf9" }}>📅</button>
                                  <button onClick={() => doMovePending(p)} title="Move to Pending" style={{ ...S.actBtn, color: "#e65100", borderColor: "#ffcc80" }}>⏳</button>
                                  <button onClick={() => doNoShow(p)} title="No Show" style={{ ...S.actBtn, color: "#9e9e9e", borderColor: "#e0e0e0" }}>✗</button>
                                </> : (isNoShow || isCancelled) ? <>
                                  <button onClick={() => handleEdit(p)} title="Reschedule" style={{ ...S.actBtn, color: "#1565c0", borderColor: "#90caf9" }}>📅</button>
                                </> : <span style={{ fontSize: "0.72rem", color: "#94a3b8" }}>—</span>}
                              </td>}
                            </tr>
                          );
                        }),
                      ];
                    })}
                  </tbody>
                </table>
                {/* Summary footer */}
                <div style={{ padding: "8px 14px", borderTop: "1px solid #e2e8f0", background: "#f8fafc", display: "flex", gap: 16, fontSize: "0.73rem", color: "#64748b", flexWrap: "wrap" }}>
                  <span>Total: <b>{todayPts.length}</b></span>
                  <span>Admitted: <b style={{ color: "#2e7d32" }}>{todayPts.filter(p => p.status === "Admitted").length}</b></span>
                  <span>Remaining: <b style={{ color: "#c62828" }}>{todayPts.filter(p => p.status === "Date Given").length}</b></span>
                </div>
              </div>
            );
          })()}
        </>}

        {view === "patients" && <>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14, flexWrap: "wrap", gap: 8 }}>
            <h2 style={{ ...S.secT, margin: 0 }}>All Patients {selDate && `— ${fmtD(selDate)}`}</h2>
            <span style={{ fontSize: "0.82rem", color: "#64748b" }}>{filtered.length} patients</span>
          </div>
          {selDate && <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
            {Object.keys(slotInfo(selDate)).map(c => { const si2 = slotInfo(selDate); const s = si2[c]; if (!mergedBenignCats[c]) return null; return <div key={c} style={{ padding: "5px 12px", borderRadius: 8, background: "#fff", border: "1px solid #e2e8f0", fontSize: "0.76rem", fontWeight: 500 }}><span style={{ color: mergedBenignCats[c].color }}>{mergedBenignCats[c].icon} {mergedBenignCats[c].label}:</span> <b>{s.used}/{s.total}</b></div>; })}
            <div style={{ padding: "5px 12px", borderRadius: 8, background: "#fff", border: "1px solid #e2e8f0", fontSize: "0.76rem", fontWeight: 500 }}><span style={{ color: "#c62828" }}>🔴 Malignancy:</span> <b>{patients.filter(p => p.surgeryDate === selDate && p.type === "malignancy").length}</b></div>
            <button style={{ ...S.btnSm, fontSize: "0.74rem" }} onClick={() => setSelDate("")}>Clear date</button>
          </div>}
          <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "7px 12px", flex: 1, minWidth: 180 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2"><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>
              <input style={{ border: "none", outline: "none", fontSize: "0.84rem", width: "100%", fontFamily: "'Outfit',sans-serif", color: "#1e293b", background: "transparent" }} placeholder="Search..." value={search} onChange={e => setSearch(e.target.value)} />
            </div>
            <select style={{ ...S.input, width: "auto", minWidth: 120, padding: "7px 10px" }} value={fType} onChange={e => { setFType(e.target.value); setFCat("all"); }}><option value="all">All Types</option><option value="benign">Benign</option><option value="malignancy">Malignancy</option></select>
            {fType !== "malignancy" && <select style={{ ...S.input, width: "auto", minWidth: 130, padding: "7px 10px" }} value={fCat} onChange={e => setFCat(e.target.value)}><option value="all">All Categories</option>{Object.keys(mergedBenignCats).map(k => <option key={k} value={k}>{mergedBenignCats[k].label}</option>)}{fType === "all" && <option value="malignancy">Malignancy</option>}</select>}
            <input style={{ ...S.input, width: "auto", padding: "7px 10px" }} type="date" value={selDate} onChange={e => setSelDate(e.target.value)} />
          </div>
          {filtered.length === 0 ? <div style={S.empty}>No patients match.</div> : (
            <div style={{ overflowX: "auto", background: "#fff", borderRadius: 12, border: "1px solid #e2e8f0" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.8rem" }}>
                <thead><tr>
                  {["Patient", "Age/Sex", "Phone", "Type", "Category/Site", "Diagnosis", "Procedure", "Plan", "Date", "Status", ...(perms.edit || perms.schedule ? [""] : [])].map(h => <th key={h} style={S.th}>{h}</th>)}
                </tr></thead>
                <tbody>{filtered.map(p => <tr key={p.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                  <td style={S.td}><b>{p.name}</b>{p.notes && <button onClick={() => setNoteViewModal({ name: p.name, notes: p.notes })} title="View Notes" style={{ border: "none", background: "#eff6ff", color: "#1565c0", cursor: "pointer", fontSize: "0.6rem", fontWeight: 700, padding: "1px 5px", borderRadius: 4, marginLeft: 4, verticalAlign: "middle" }}>{"📝"}</button>}</td>
                  <td style={S.td}>{p.age}y/{p.sex[0]}</td>
                  <td style={S.td}>{p.phone}</td>
                  <td style={S.td}>{p.type === "malignancy" ? <Bdg bg="#fce4ec" color="#c62828" border="#ef9a9a">Malig</Bdg> : <Bdg bg="#e8f5e9" color="#2e7d32" border="#a5d6a7">Benign</Bdg>}</td>
                  <td style={S.td}>{p.type === "malignancy" ? p.malignancySite : (mergedBenignCats[p.benignCategory]?.label || "—")}</td>
                  <td style={{ ...S.td, maxWidth: 170 }}>{p.type === "benign" ? (p.diagnosis || "—") : "—"}</td>
                  <td style={{ ...S.td, maxWidth: 170 }}>{p.plannedProcedure || "—"}</td>
                  <td style={S.td}>{p.type === "malignancy" ? <span style={{ color: p.malignancyPlan === "Palliative" ? "#e65100" : "#2e7d32", fontWeight: 600 }}>{p.malignancyPlan}</span> : "—"}</td>
                  <td style={S.td}>{fmtD(p.surgeryDate)}</td>
                  <td style={S.td}>{(() => {
                    const sc = { "Date Given": { bg: "#e8f5e9", c: "#2e7d32", b: "#a5d6a7" }, "Admitted": { bg: "#e3f2fd", c: "#1565c0", b: "#90caf9" }, "Pending": { bg: "#fff3e0", c: "#e65100", b: "#ffcc80" }, "No Show": { bg: "#f5f5f5", c: "#616161", b: "#bdbdbd" } };
                    const st = sc[p.status] || sc["Date Given"];
                    return <Bdg bg={st.bg} color={st.c} border={st.b}>{p.status}</Bdg>;
                  })()}</td>
                  {(perms.edit || perms.schedule) && <td style={S.td}><div style={{ display: "flex", gap: 4 }}>
                    <button style={S.btnSm} onClick={() => handleEdit(p)}>✏️</button>
                    {perms.schedule && <button style={{ ...S.btnSm, color: "#c62828" }} onClick={() => setConfirm({ msg: `Remove ${p.name}?`, fn: () => { updatePatients(x => x.filter(y => y.id !== p.id)); show("Removed."); setConfirm(null); } })}>🗑</button>}
                  </div></td>}
                </tr>)}</tbody>
              </table>
            </div>
          )}
        </>}

        {/* ═══ PENDING POOL ═══ */}
        {view === "pending" && (() => {
          const pending = patients.filter(p => p.status === "Pending").sort((a, b) => {
            if (a.type === "malignancy" && b.type !== "malignancy") return -1;
            if (a.type !== "malignancy" && b.type === "malignancy") return 1;
            return new Date(a.surgeryDate) - new Date(b.surgeryDate);
          });
          return <>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <h2 style={{ ...S.secT, margin: 0 }}>⏳ Pending Cases — Priority Pool</h2>
              <span style={{ fontSize: "0.82rem", color: "#64748b" }}>{pending.length} patients</span>
            </div>
            <div style={{ padding: "10px 14px", borderRadius: 8, background: "#fff3e0", border: "1px solid #ffcc80", fontSize: "0.78rem", color: "#e65100", marginBottom: 16 }}>
              Patients here were postponed and need admission on priority. Admit directly or reschedule to a specific date.
            </div>
            {pending.length === 0 ? <div style={S.empty}>No pending cases. Patients moved from today's list will appear here.</div> : (
              <div style={{ background: "#fff", borderRadius: 12, border: "1px solid #e2e8f0", overflow: "hidden" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.8rem" }}>
                  <thead><tr>
                    <th style={{ ...S.th, width: 28 }}>#</th>
                    <th style={S.th}>Patient</th>
                    <th style={S.th}>Type</th>
                    <th style={S.th}>Diagnosis/Site</th>
                    <th style={S.th}>Procedure</th>
                    <th style={S.th}>Orig. Date</th>
                    <th style={S.th}>Reason for Postponing</th>
                    {perms.admit && <th style={{ ...S.th, width: 100, textAlign: "right" }}>Actions</th>}
                  </tr></thead>
                  <tbody>{pending.map((p, i) => {
                    const isMal = p.type === "malignancy";
                    const catInfo = mergedBenignCats[p.benignCategory];
                    const catColor = isMal ? "#c62828" : (catInfo?.color || "#6a1b9a");
                    return (
                      <tr key={p.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                        <td style={{ ...S.td, color: "#94a3b8", fontWeight: 600, textAlign: "center" }}>{i + 1}</td>
                        <td style={S.td}>
                          <div style={{ fontWeight: 600, color: "#1e293b", fontSize: "0.84rem" }}>{p.name}</div>
                          <div style={{ color: "#94a3b8", fontSize: "0.72rem" }}>{p.age}y/{p.sex[0]} · {p.phone}</div>
                        </td>
                        <td style={S.td}>{isMal ? <Bdg bg="#fce4ec" color="#c62828" border="#ef9a9a">Malig</Bdg> : <Bdg bg={catColor + "18"} color={catColor} border={catColor + "44"}>{catInfo?.icon} {catInfo?.label}</Bdg>}</td>
                        <td style={{ ...S.td, maxWidth: 160 }}>{isMal ? p.malignancySite : (p.diagnosis || "—")}</td>
                        <td style={{ ...S.td, maxWidth: 160, color: "#64748b" }}>{p.plannedProcedure || "—"}</td>
                        <td style={S.td}>{fmtD(p.surgeryDate)}</td>
                        <td style={{ ...S.td, color: "#e65100", fontSize: "0.76rem", maxWidth: 160 }}>{p.postponeReason || p.clinical?.listOutcomeReason || "—"}</td>
                        {perms.admit && <td style={{ ...S.td, textAlign: "right", whiteSpace: "nowrap" }}>
                          <button onClick={() => doAdmit(p)} title="Admit Now" style={{ ...S.actBtn, background: "#e8f5e9", color: "#2e7d32", borderColor: "#a5d6a7" }}>✅</button>
                          <button onClick={() => setReschedModal({ patient: p, newDate: "" })} title="Reschedule" style={{ ...S.actBtn, color: "#1565c0", borderColor: "#90caf9" }}>📅</button>
                        </td>}
                      </tr>
                    );
                  })}</tbody>
                </table>
              </div>
            )}
          </>;
        })()}

        {view === "schedule" && perms.schedule && <>
          <div style={S.formC}>
            <h2 style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.25rem", color: "#0b1420", margin: "0 0 4px" }}>{editId ? "Edit Patient" : "Give Date — Schedule Surgery"}</h2>
            <p style={{ color: "#64748b", fontSize: "0.83rem", margin: "0 0 22px" }}>{editId ? "Update details." : "Select type, category, diagnosis, and schedule."}</p>

            <div style={{ marginBottom: 18 }}>
              <label style={S.label}>Patient Type *</label>
              <div style={{ display: "flex", gap: 10 }}>
                {[{ v: "benign", l: "Benign", c: "#2e7d32" }, { v: "malignancy", l: "Malignancy", c: "#c62828" }].map(t => (
                  <button key={t.v} onClick={() => setPf({ ...empty, type: t.v, name: pf.name, age: pf.age, sex: pf.sex, phone: pf.phone, notes: pf.notes })}
                    style={{ flex: 1, padding: 13, borderRadius: 10, border: pf.type === t.v ? `2.5px solid ${t.c}` : "1.5px solid #e2e8f0", background: pf.type === t.v ? t.c + "0d" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontSize: "0.95rem", fontWeight: 700, color: pf.type === t.v ? t.c : "#94a3b8" }}>{t.l}</button>
                ))}
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
              <div style={{ gridColumn: "1/-1" }}><label style={S.label}>Name *</label><input style={S.input} placeholder="Full name" value={pf.name} onChange={e => setPf({ ...pf, name: e.target.value })} /></div>
              <div><label style={S.label}>Age</label><input style={S.input} type="number" min="0" max="120" value={pf.age} onChange={e => setPf({ ...pf, age: e.target.value })} /></div>
              <div><label style={S.label}>Sex</label><select style={S.input} value={pf.sex} onChange={e => setPf({ ...pf, sex: e.target.value })}><option>Male</option><option>Female</option><option>Other</option></select></div>
              <div style={{ gridColumn: "1/-1" }}><label style={S.label}>Phone</label><input style={S.input} type="tel" placeholder="Mobile" value={pf.phone} onChange={e => setPf({ ...pf, phone: e.target.value })} /></div>
            </div>

            {pf.type === "benign" && <>
              <div style={{ marginBottom: 14 }}>
                <label style={S.label}>Category *</label>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(115px,1fr))", gap: 8 }}>
                  {Object.entries(mergedBenignCats).map(([k, v]) => (
                    <button key={k} onClick={() => setPf({ ...pf, bCat: k, diag: "", proc: "", diagC: "", procC: "" })}
                      style={{ padding: "11px 8px", borderRadius: 10, border: pf.bCat === k ? `2.5px solid ${v.color}` : "1.5px solid #e2e8f0", background: pf.bCat === k ? v.color + "0d" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 600, fontSize: "0.84rem", color: pf.bCat === k ? v.color : "#64748b" }}>
                      {v.icon} {v.label}
                    </button>
                  ))}
                </div>
              </div>
              {pf.bCat && <>
                <SearchSelect label="Diagnosis" req options={[...Object.keys(mergedBenignCats[pf.bCat].diagnoses), "Other (Custom)"].map(o => o)} value={pf.diag === "__c__" ? "Other (Custom)" : pf.diag} onChange={v => { setPf({ ...pf, diag: v === "Other (Custom)" ? "__c__" : v, proc: "", procC: "", diagC: "" }); }} placeholder="Select diagnosis..." />
                {pf.diag === "__c__" && <div style={{ marginTop: 8 }}><label style={S.label}>Custom Diagnosis</label><input style={S.input} value={pf.diagC} onChange={e => setPf({ ...pf, diagC: e.target.value })} /></div>}
                {(avProcs.length > 0 || pf.diag === "__c__") && <div style={{ marginTop: 12 }}>
                  <SearchSelect label="Procedure" req options={[...(pf.diag === "__c__" ? [] : avProcs), "Other (Custom)"]} value={pf.proc === "__c__" ? "Other (Custom)" : pf.proc} onChange={v => setPf({ ...pf, proc: v === "Other (Custom)" ? "__c__" : v, procC: "" })} placeholder="Select procedure..." />
                  {pf.proc === "__c__" && <div style={{ mt: 8, marginTop: 8 }}><label style={S.label}>Custom Procedure</label><input style={S.input} value={pf.procC} onChange={e => setPf({ ...pf, procC: e.target.value })} /></div>}
                </div>}
                <div style={{ marginTop: 14, padding: 14, borderRadius: 10, background: "#f0fdf4", border: "1px solid #bbf7d0" }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 8, marginBottom: 8 }}>
                    <div style={{ fontSize: "0.76rem", fontWeight: 600, color: "#2e7d32" }}>📅 Auto-Assigned Date</div>
                    <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                      {Object.entries(pSlots).map(([k, v]) => (
                        <button key={k} onClick={() => setPf({ ...pf, priority: k })} style={{ padding: "3px 10px", borderRadius: 6, border: pf.priority === k ? `2px solid ${v.color}` : "1.5px solid #e2e8f0", background: pf.priority === k ? `${v.color}12` : "#fff", color: pf.priority === k ? v.color : "#94a3b8", fontSize: "0.66rem", fontWeight: 700, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{k}. {v.label}</button>
                      ))}
                    </div>
                  </div>
                  {(() => {
                    const activeSlots = pSlots[pf.priority || "3"].slots;
                    const ad = pf.date || findDate(patients, config.admissionDay, pf.bCat, activeSlots);
                    const used = slotsUsed(patients, ad, pf.bCat);
                    const total = activeSlots[pf.bCat];
                    return <>
                      <div style={{ fontSize: "1rem", fontWeight: 700, color: "#1e293b" }}>{fmtD(ad)}</div>
                      <div style={{ fontSize: "0.76rem", color: "#64748b", marginTop: 3 }}>Slots: {used}/{total} ({mergedBenignCats[pf.bCat].label}) — <span style={{ color: pSlots[pf.priority || "3"].color, fontWeight: 700 }}>{pSlots[pf.priority || "3"].label} Priority</span>{used >= total ? " — ⚠️ FULL, will go to next week" : ""}</div>
                    </>;
                  })()}
                  {(() => {
                    const activeSlots = pSlots[pf.priority || "3"].slots;
                    const ds = pf.date || findDate(patients, config.admissionDay, pf.bCat, activeSlots);
                    const d = new Date(ds + "T00:00:00"); const dayOfWeek = d.getDay();
                    const weekStart = new Date(d); weekStart.setDate(d.getDate() - dayOfWeek);
                    const weekHols = (config.holidays || []).filter(h => { const hd = new Date(h.date + "T00:00:00"); return hd >= weekStart && hd < new Date(weekStart.getTime() + 7 * 86400000); });
                    if (weekHols.length === 0) return null;
                    return <div style={{ marginTop: 6, padding: "6px 10px", background: "#fff3e0", borderRadius: 6, border: "1px solid #ffe082" }}>
                      <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#e65100" }}>⚠️ Holiday(s) this week:</div>
                      {weekHols.map((h, i) => <div key={i} style={{ fontSize: "0.7rem", color: "#bf360c" }}>🎉 {fmtD(h.date)} — {h.name}</div>)}
                    </div>;
                  })()}
                  {/* Duplicate diagnosis warning for "others" category */}
                  {pf.bCat === "others" && pf.diag && pf.diag !== "__c__" && (() => {
                    const activeSlots = pSlots[pf.priority || "3"].slots;
                    const ds = pf.date || findDate(patients, config.admissionDay, pf.bCat, activeSlots);
                    const dupes = patients.filter(p => p.surgeryDate === ds && p.diagnosis === pf.diag && p.type === "benign" && (editId ? p.id !== editId : true));
                    if (dupes.length === 0) return null;
                    return <div style={{ marginTop: 6, padding: "6px 10px", background: "#fce4ec", borderRadius: 6, border: "1px solid #f48fb1" }}>
                      <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#c62828" }}>⚠️ Same diagnosis already on this date:</div>
                      {dupes.map((p, i) => <div key={i} style={{ fontSize: "0.7rem", color: "#880e4f" }}>• {p.name} — {p.diagnosis}</div>)}
                    </div>;
                  })()}
                  <div style={{ marginTop: 8 }}><label style={{ ...S.label, fontSize: "0.68rem" }}>Override Date (Admin)</label><input style={{ ...S.input, maxWidth: 200 }} type="date" value={pf.date} onChange={e => setPf({ ...pf, date: e.target.value })} /></div>
                </div>
                {/* Mini patient list for this date */}
                {(() => {
                  const activeSlots = pSlots[pf.priority || "3"].slots;
                  const previewDate = pf.date || findDate(patients, config.admissionDay, pf.bCat, activeSlots);
                  const datePts = patients.filter(p => p.surgeryDate === previewDate && (editId ? p.id !== editId : true));
                  if (datePts.length === 0) return <div style={{ marginTop: 10, padding: "10px 14px", borderRadius: 8, background: "#f8fafc", border: "1px solid #e2e8f0", fontSize: "0.78rem", color: "#94a3b8" }}>No other patients scheduled for this date yet.</div>;
                  const grouped = {};
                  datePts.forEach(p => {
                    const key = p.type === "malignancy" ? "malignancy" : (p.benignCategory || "others");
                    if (!grouped[key]) grouped[key] = [];
                    grouped[key].push(p);
                  });
                  return (
                    <div style={{ marginTop: 10, padding: "12px 14px", borderRadius: 10, background: "#fff", border: "1px solid #e2e8f0" }}>
                      <div style={{ fontSize: "0.74rem", fontWeight: 700, color: "#475569", marginBottom: 8, textTransform: "uppercase", letterSpacing: "0.04em" }}>📋 Cases on {fmtD(previewDate)} ({datePts.length} total)</div>
                      {Object.entries(grouped).map(([cat, pts]) => {
                        const catInfo = mergedBenignCats[cat];
                        const isMal = cat === "malignancy";
                        const catLabel = isMal ? "🔴 Malignancy" : `${catInfo?.icon || "🟣"} ${catInfo?.label || cat}`;
                        const catColor = isMal ? "#c62828" : (catInfo?.color || "#6a1b9a");
                        const slotStr = !isMal && config.slots[cat] ? ` (${pts.length}/${config.slots[cat]})` : "";
                        return (
                          <div key={cat} style={{ marginBottom: 8 }}>
                            <div style={{ fontSize: "0.72rem", fontWeight: 700, color: catColor, marginBottom: 3 }}>{catLabel}{slotStr}</div>
                            {pts.map((p, i) => (
                              <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 0 4px 12px", fontSize: "0.78rem", color: "#475569", borderLeft: `2px solid ${catColor}22` }}>
                                <span style={{ color: "#94a3b8", fontWeight: 600, minWidth: 16 }}>{i + 1}.</span>
                                <span style={{ fontWeight: 600, color: "#1e293b" }}>{p.name}</span>
                                <span style={{ color: "#94a3b8" }}>{p.age}y/{p.sex[0]}</span>
                                <span style={{ color: "#64748b", flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.type === "malignancy" ? p.malignancySite : (p.diagnosis || "")}</span>
                              </div>
                            ))}
                          </div>
                        );
                      })}
                    </div>
                  );
                })()}
              </>}
            </>}

            {pf.type === "malignancy" && <>
              <SearchSelect label="Site of Malignancy" req options={Object.keys(mergedMaligSites)} value={pf.mSite} onChange={v => setPf({ ...pf, mSite: v, mProc: "", mProcC: "" })} placeholder="Select site..." />
              <div style={{ marginTop: 12 }}>
                <label style={S.label}>Treatment Plan *</label>
                <div style={{ display: "flex", gap: 10 }}>
                  {["Definitive", "Palliative"].map(p2 => <button key={p2} onClick={() => setPf({ ...pf, mPlan: p2 })} style={{ flex: 1, padding: 10, borderRadius: 10, border: pf.mPlan === p2 ? `2.5px solid ${p2 === "Palliative" ? "#e65100" : "#2e7d32"}` : "1.5px solid #e2e8f0", background: pf.mPlan === p2 ? (p2 === "Palliative" ? "#fff3e0" : "#e8f5e9") : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 600, fontSize: "0.88rem", color: pf.mPlan === p2 ? (p2 === "Palliative" ? "#e65100" : "#2e7d32") : "#94a3b8" }}>{p2 === "Definitive" ? "🎯" : "🤲"} {p2}</button>)}
                </div>
              </div>
              {mProcs.length > 0 && <div style={{ marginTop: 12 }}>
                <SearchSelect label="Procedure" options={[...mProcs, "Other (Custom)"]} value={pf.mProc === "__c__" ? "Other (Custom)" : pf.mProc} onChange={v => setPf({ ...pf, mProc: v === "Other (Custom)" ? "__c__" : v, mProcC: "" })} placeholder="Select procedure..." />
                {pf.mProc === "__c__" && <div style={{ marginTop: 8 }}><label style={S.label}>Custom Procedure</label><input style={S.input} value={pf.mProcC} onChange={e => setPf({ ...pf, mProcC: e.target.value })} /></div>}
              </div>}
              <div style={{ marginTop: 14, padding: 14, borderRadius: 10, background: "#fef2f2", border: "1px solid #fecaca" }}>
                <div style={{ fontSize: "0.76rem", fontWeight: 600, color: "#c62828", marginBottom: 6 }}>📅 Manual Date (Malignancy)</div>
                <input style={S.input} type="date" value={pf.date} onChange={e => setPf({ ...pf, date: e.target.value })} />
                {pf.date && (() => {
                  const d = new Date(pf.date + "T00:00:00"); const dayOfWeek = d.getDay();
                  const weekStart = new Date(d); weekStart.setDate(d.getDate() - dayOfWeek);
                  const weekHols = (config.holidays || []).filter(h => { const hd = new Date(h.date + "T00:00:00"); return hd >= weekStart && hd < new Date(weekStart.getTime() + 7 * 86400000); });
                  if (weekHols.length === 0) return null;
                  return <div style={{ marginTop: 6, padding: "6px 10px", background: "#fff3e0", borderRadius: 6, border: "1px solid #ffe082" }}>
                    <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#e65100" }}>⚠️ Holiday(s) this week:</div>
                    {weekHols.map((h, i) => <div key={i} style={{ fontSize: "0.7rem", color: "#bf360c" }}>🎉 {fmtD(h.date)} — {h.name}</div>)}
                  </div>;
                })()}
              </div>
              {/* Mini patient list for malignancy date */}
              {pf.date && (() => {
                const datePts = patients.filter(p => p.surgeryDate === pf.date && (editId ? p.id !== editId : true));
                if (datePts.length === 0) return <div style={{ marginTop: 10, padding: "10px 14px", borderRadius: 8, background: "#f8fafc", border: "1px solid #e2e8f0", fontSize: "0.78rem", color: "#94a3b8" }}>No other patients scheduled for this date yet.</div>;
                const grouped = {};
                datePts.forEach(p => {
                  const key = p.type === "malignancy" ? "malignancy" : (p.benignCategory || "others");
                  if (!grouped[key]) grouped[key] = [];
                  grouped[key].push(p);
                });
                return (
                  <div style={{ marginTop: 10, padding: "12px 14px", borderRadius: 10, background: "#fff", border: "1px solid #e2e8f0" }}>
                    <div style={{ fontSize: "0.74rem", fontWeight: 700, color: "#475569", marginBottom: 8, textTransform: "uppercase", letterSpacing: "0.04em" }}>📋 Cases on {fmtD(pf.date)} ({datePts.length} total)</div>
                    {Object.entries(grouped).map(([cat, pts]) => {
                      const catInfo = mergedBenignCats[cat];
                      const isMal = cat === "malignancy";
                      const catLabel = isMal ? "🔴 Malignancy" : `${catInfo?.icon || "🟣"} ${catInfo?.label || cat}`;
                      const catColor = isMal ? "#c62828" : (catInfo?.color || "#6a1b9a");
                      const slotStr = !isMal && config.slots[cat] ? ` (${pts.length}/${config.slots[cat]})` : "";
                      return (
                        <div key={cat} style={{ marginBottom: 8 }}>
                          <div style={{ fontSize: "0.72rem", fontWeight: 700, color: catColor, marginBottom: 3 }}>{catLabel}{slotStr}</div>
                          {pts.map((p, i) => (
                            <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 0 4px 12px", fontSize: "0.78rem", color: "#475569", borderLeft: `2px solid ${catColor}22` }}>
                              <span style={{ color: "#94a3b8", fontWeight: 600, minWidth: 16 }}>{i + 1}.</span>
                              <span style={{ fontWeight: 600, color: "#1e293b" }}>{p.name}</span>
                              <span style={{ color: "#94a3b8" }}>{p.age}y/{p.sex[0]}</span>
                              <span style={{ color: "#64748b", flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.type === "malignancy" ? p.malignancySite : (p.diagnosis || "")}</span>
                            </div>
                          ))}
                        </div>
                      );
                    })}
                  </div>
                );
              })()}
            </>}

            {pf.type && <div style={{ marginTop: 14 }}><label style={S.label}>Notes</label><textarea style={{ ...S.input, minHeight: 55, resize: "vertical" }} placeholder="Comorbidities, special instructions..." value={pf.notes} onChange={e => setPf({ ...pf, notes: e.target.value })} /></div>}

            <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 22, paddingTop: 16, borderTop: "1px solid #e2e8f0" }}>
              <button style={S.btnS} onClick={() => { setView("dashboard"); setPf({ ...empty }); setEditId(null); }}>Cancel</button>
              <button style={S.btnP} onClick={handleSave}>{editId ? "Update" : "Schedule"}</button>
            </div>
          </div>
        </>}

        {/* ═══ EMERGENCY CASE ═══ */}
        {view === "emergency" && perms.addEmergency && <>
          <div style={{ maxWidth: 480, margin: "0 auto" }}>
            <div style={{ padding: "16px 20px", background: "linear-gradient(135deg,#fef2f2,#fff5f5)", borderRadius: 14, border: "2px solid #ef9a9a", marginBottom: 20 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                <span style={{ fontSize: "1.6rem" }}>{"🚨"}</span>
                <div>
                  <div style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.2rem", color: "#c62828", fontWeight: 700 }}>Emergency Case</div>
                  <div style={{ fontSize: "0.72rem", color: "#64748b" }}>Patient will be admitted immediately and operated in EOT</div>
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 12 }}>
                <div><label style={{ ...S.label, color: "#c62828" }}>Patient Name *</label><input style={{ ...S.input, borderColor: "#ef9a9a" }} value={emf.name} onChange={e => setEmf({ ...emf, name: e.target.value })} placeholder="Full name" autoFocus /></div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
                  <div><label style={S.label}>Age</label><input style={S.input} type="number" min="0" max="120" value={emf.age} onChange={e => setEmf({ ...emf, age: e.target.value })} /></div>
                  <div><label style={S.label}>Sex</label>
                    <div style={{ display: "flex", gap: 4 }}>
                      {["Male","Female"].map(s => <button key={s} onClick={() => setEmf({ ...emf, sex: s })} style={{ flex: 1, padding: "7px 0", borderRadius: 8, border: emf.sex === s ? "2px solid #c62828" : "1.5px solid #e2e8f0", background: emf.sex === s ? "#fef2f2" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 600, fontSize: "0.82rem", color: emf.sex === s ? "#c62828" : "#94a3b8" }}>{s[0]}</button>)}
                    </div>
                  </div>
                  <div><label style={S.label}>MRD No.</label><input style={S.input} value={emf.mrd} onChange={e => setEmf({ ...emf, mrd: e.target.value })} placeholder="MRD" /></div>
                </div>
              </div>

              <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 18, paddingTop: 14, borderTop: "1px solid #fecaca" }}>
                <button style={S.btnS} onClick={() => { setEmf({ name: "", age: "", sex: "Male", mrd: "" }); setView("dashboard"); }}>Cancel</button>
                <button style={{ ...S.btnP, background: "linear-gradient(135deg,#c62828,#e53935)" }} onClick={() => {
                  if (!emf.name.trim()) { show("Patient name is required.", "error"); return; }
                  const newPt = {
                    id: "p" + Date.now() + Math.random().toString(36).slice(2, 5),
                    name: emf.name.trim(),
                    age: emf.age ? +emf.age : null,
                    sex: emf.sex,
                    phone: "",
                    type: "benign",
                    diagnosis: "",
                    plannedProcedure: "",
                    surgeryDate: todayS,
                    notes: "",
                    benignCategory: "",
                    malignancySite: "",
                    malignancyPlan: "",
                    status: "Admitted",
                    isEmergency: true,
                    admittedAt: new Date().toISOString(),
                    createdAt: new Date().toISOString(),
                    createdBy: me.id,
                    createdByName: me.name,
                    clinical: { mrd: emf.mrd.trim(), clinicalDone: false, theater: "EOT", surgeryListDate: todayS },
                  };
                  updatePatients(prev => [...prev, newPt]);
                  show(`🚨 ${emf.name.trim()} admitted as emergency case.`);
                  notify('🚨 Emergency Admission', `${emf.name.trim()} admitted as emergency.`, 'new-patient', '/', getSurgeonUserIds({ createdBy: me?.id }, users, config));
                  setEmf({ name: "", age: "", sex: "Male", mrd: "" });
                  setPage("admissions");
                }}>{"🚨"} Admit Emergency</button>
              </div>
            </div>

            {/* Recent emergency cases */}
            {(() => {
              const emergPts = patients.filter(p => p.isEmergency).sort((a, b) => (b.admittedAt || "").localeCompare(a.admittedAt || "")).slice(0, 10);
              if (emergPts.length === 0) return null;
              return <div style={{ marginTop: 8 }}>
                <div style={{ fontSize: "0.74rem", fontWeight: 700, color: "#64748b", marginBottom: 8, textTransform: "uppercase", letterSpacing: "0.04em" }}>Recent Emergency Cases</div>
                <div style={{ background: "#fff", borderRadius: 10, border: "1px solid #e2e8f0", overflow: "hidden" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.76rem" }}>
                    <thead><tr>
                      <th style={S.th}>Patient</th>
                      <th style={S.th}>MRD</th>
                      <th style={S.th}>Date</th>
                      <th style={S.th}>Status</th>
                    </tr></thead>
                    <tbody>{emergPts.map(p => (
                      <tr key={p.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                        <td style={S.td}><span style={{ fontWeight: 600 }}>{p.name}</span> <span style={{ color: "#94a3b8", fontSize: "0.68rem" }}>{p.age ? p.age + "y/" + (p.sex?.[0] || "") : ""}</span></td>
                        <td style={{ ...S.td, fontSize: "0.72rem" }}>{p.clinical?.mrd || "—"}</td>
                        <td style={{ ...S.td, fontSize: "0.72rem" }}>{p.admittedAt ? fmtDT(p.admittedAt) : "—"}</td>
                        <td style={S.td}>
                          <Bdg bg={p.status === "Discharged" ? "#f3e5f5" : p.status === "Operated" ? "#e8f5e9" : "#fff3e0"} color={p.status === "Discharged" ? "#6a1b9a" : p.status === "Operated" ? "#2e7d32" : "#e65100"} border={p.status === "Discharged" ? "#ce93d8" : p.status === "Operated" ? "#a5d6a7" : "#ffcc80"}>{p.status}</Bdg>
                          <span style={{ fontSize: "0.58rem", padding: "1px 5px", borderRadius: 4, background: "#fef2f2", color: "#c62828", fontWeight: 600, marginLeft: 4 }}>EMG</span>
                        </td>
                      </tr>
                    ))}</tbody>
                  </table>
                </div>
              </div>;
            })()}
          </div>
        </>}

          </div>
        </>}

        {page === "dutyRoster" && <div className="st-content" style={S.content}>
          <CalendarGrid ym={dutyMonth} setYm={setDutyMonth} data={dutyData} saveData={saveDuty} color="#1565c0" title="Duty Roster" placeholder="On-call, Emergency..." readOnly={true} />
          <div style={{ textAlign: "center", padding: "8px 0", fontSize: "0.72rem", color: "#94a3b8" }}>{perms.manageUsers ? "Edit roster in Settings → Rosters tab" : "View only — contact admin to modify"}</div>
        </div>}
        {page === "acadRoster" && <div className="st-content" style={S.content}>
          <CalendarGrid ym={acadMonth} setYm={setAcadMonth} data={acadData} saveData={saveAcad} color="#6a1b9a" title="Academic Roster" placeholder="Seminar, Journal Club..." readOnly={true} />
          <div style={{ textAlign: "center", padding: "8px 0", fontSize: "0.72rem", color: "#94a3b8" }}>{perms.manageUsers ? "Edit roster in Settings → Rosters tab" : "View only — contact admin to modify"}</div>
        </div>}

        {/* ═══ RESEARCH PAGE ═══ */}
        {page === "research" && <div className="st-content" style={S.content}>
          <div style={S.formC}>
            <h2 style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.25rem", color: "#0b1420", margin: "0 0 14px" }}>{"🔬"} Research Protocols</h2>

            {(config.researchProtocols || []).length === 0 ? (
              <div style={{ textAlign: "center", padding: 40, color: "#94a3b8" }}>
                <div style={{ fontSize: "2rem", marginBottom: 8 }}>{"🔬"}</div>
                <div style={{ fontSize: "0.9rem", fontWeight: 600, marginBottom: 4 }}>No Research Protocols</div>
                <div style={{ fontSize: "0.82rem" }}>Admin can create protocols in Settings → Research Protocols tab.</div>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                {(config.researchProtocols || []).map(rp => {
                  const enrolled = patients.filter(p => (p.researchProtocols || []).includes(rp.id));
                  const operated = enrolled.filter(p => p.status === "Operated" || p.status === "Discharged");
                  const discharged = enrolled.filter(p => p.status === "Discharged");
                  return <div key={rp.id} style={{ borderRadius: 12, border: rp.active !== false ? "2px solid #d8b4fe" : "1px solid #e2e8f0", overflow: "hidden", opacity: rp.active !== false ? 1 : 0.7 }}>
                    {/* Protocol header */}
                    <div style={{ padding: "14px 16px", background: "linear-gradient(135deg,#f3e8ff,#faf5ff)", borderBottom: "1px solid #e9d5ff" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <div>
                          <div style={{ fontWeight: 700, fontSize: "0.95rem", color: "#7c3aed" }}>{rp.name}</div>
                          <div style={{ fontSize: "0.72rem", color: "#64748b", marginTop: 2 }}>
                            {rp.linkedSurgeon && <span>PI: <b>{rp.linkedSurgeon}</b> · </span>}
                            {rp.active === false && <span style={{ color: "#e65100" }}>Paused · </span>}
                            Created {rp.createdAt ? fmtDT(rp.createdAt) : "—"}
                          </div>
                        </div>
                        <div style={{ display: "flex", gap: 8 }}>
                          {[{ l: "Enrolled", v: enrolled.length, c: "#7c3aed", bg: "#f3e8ff" }, { l: "Operated", v: operated.length, c: "#2e7d32", bg: "#e8f5e9" }, { l: "Discharged", v: discharged.length, c: "#6a1b9a", bg: "#f3e5f5" }].map(s => (
                            <div key={s.l} style={{ padding: "6px 10px", borderRadius: 8, background: s.bg, textAlign: "center", minWidth: 50 }}>
                              <div style={{ fontSize: "1.1rem", fontWeight: 800, color: s.c }}>{s.v}</div>
                              <div style={{ fontSize: "0.56rem", fontWeight: 600, color: s.c, textTransform: "uppercase" }}>{s.l}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                    {/* Patient list */}
                    {enrolled.length === 0 ? (
                      <div style={{ padding: "20px 16px", textAlign: "center", color: "#94a3b8", fontSize: "0.82rem" }}>No patients enrolled yet. Assign patients via Admissions → 🔬 button.</div>
                    ) : (
                      <div style={{ overflow: "auto" }}>
                        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.76rem" }}>
                          <thead><tr>
                            <th style={{ ...S.th, width: 28 }}>#</th>
                            <th style={S.th}>Patient</th>
                            <th style={S.th}>Diagnosis</th>
                            <th style={S.th}>Procedure</th>
                            <th style={S.th}>Op Date</th>
                            <th style={S.th}>Status</th>
                          </tr></thead>
                          <tbody>{enrolled.map((p, i) => {
                            const od = p.opDetails || {};
                            return <tr key={p.id} onClick={() => { if (p.status === "Operated") { setViewPatient(p); setPage("operated"); } else if (p.status === "Discharged") { setViewPatient(p); setPage("discharged"); } else if (p.status === "Admitted") { setClinicalPt(patients.find(x => x.id === p.id)); setPage("admissions"); } }} style={{ borderBottom: "1px solid #f1f5f9", cursor: "pointer" }} onMouseEnter={e => e.currentTarget.style.background = "#faf5ff"} onMouseLeave={e => e.currentTarget.style.background = ""}>
                              <td style={{ ...S.td, textAlign: "center", color: "#94a3b8", fontWeight: 600 }}>{i + 1}</td>
                              <td style={S.td}>
                                <div style={{ fontWeight: 600, fontSize: "0.82rem" }}>{p.name}{p.isEmergency && <span style={{ fontSize: "0.54rem", padding: "1px 4px", borderRadius: 3, background: "#fef2f2", color: "#c62828", fontWeight: 700, marginLeft: 4 }}>EMG</span>}</div>
                                <div style={{ color: "#94a3b8", fontSize: "0.68rem" }}>{p.age ? p.age + "y/" : ""}{p.sex?.[0] || ""} · MRD: {p.clinical?.mrd || "—"}</div>
                              </td>
                              <td style={{ ...S.td, maxWidth: 120 }}>{p.type === "malignancy" ? (p.malignancySite || "Malignancy") : (p.diagnosis || "—")}</td>
                              <td style={{ ...S.td, maxWidth: 150 }}>{od.primaryProcedure || p.plannedProcedure || "—"}</td>
                              <td style={{ ...S.td, fontSize: "0.72rem" }}>{od.surgeryDateActual ? fmtD(od.surgeryDateActual) : "—"}</td>
                              <td style={S.td}><Bdg bg={p.status === "Discharged" ? "#f3e5f5" : p.status === "Operated" ? "#e8f5e9" : "#fff3e0"} color={p.status === "Discharged" ? "#6a1b9a" : p.status === "Operated" ? "#2e7d32" : "#e65100"} border={p.status === "Discharged" ? "#ce93d8" : p.status === "Operated" ? "#a5d6a7" : "#ffcc80"}>{p.status}</Bdg></td>
                            </tr>;
                          })}</tbody>
                        </table>
                      </div>
                    )}
                  </div>;
                })}
              </div>
            )}
          </div>
        </div>}

        {page === "settings" && perms.manageUsers && <div className="st-content" style={S.content}>
          <div style={S.formC}>
            <h2 style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.25rem", color: "#0b1420", margin: "0 0 14px" }}>Settings</h2>

            {/* Settings Tabs */}
            <div style={{ display: "flex", gap: 4, marginBottom: 18, flexWrap: "wrap" }}>
              {[["general","⚙️ General"],["surgeons","🩺 Surgeons"],["holidays","🎉 Holidays"],["backup","💾 Backup"],["duty","📋 Duty Roster"],["academic","🎓 Academic Roster"],["followup","📅 Follow-Up Templates"],["repository","📚 Dx & Proc Repository"],["research","🔬 Research Protocols"]].map(([id, l]) =>
                <button key={id} onClick={() => setSettingsTab(id)} style={{ padding: "7px 14px", borderRadius: 8, border: settingsTab === id ? "2px solid #1565c0" : "1.5px solid #e2e8f0", background: settingsTab === id ? "#eff6ff" : "#fff", color: settingsTab === id ? "#1565c0" : "#64748b", fontWeight: 600, fontSize: "0.76rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>{l}</button>
              )}
            </div>

            {/* ─── GENERAL TAB ─── */}
            {settingsTab === "general" && <>
            <div style={{ marginBottom: 24, padding: 16, borderRadius: 12, background: "#eff6ff", border: "1px solid #bfdbfe" }}>
              <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#1565c0", margin: "0 0 8px" }}>📅 Weekly Admission Day</h3>
              <select style={{ ...S.input, maxWidth: 200 }} value={config.admissionDay} onChange={e => updateConfig({ ...config, admissionDay: parseInt(e.target.value) })}>{DAY_NAMES.map((d, i) => <option key={i} value={i}>{d}</option>)}</select>
            </div>

            <div style={{ marginBottom: 24, padding: 16, borderRadius: 12, background: "#f0fdf4", border: "1px solid #bbf7d0" }}>
              <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#2e7d32", margin: "0 0 4px" }}>📊 Priority-Based Slot Limits</h3>
              <p style={{ fontSize: "0.72rem", color: "#64748b", margin: "0 0 12px" }}>Set how many patients per category can be scheduled each week at each priority level.</p>
              <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 420, fontSize: "0.76rem" }}>
                  <thead>
                    <tr>
                      <th style={{ padding: "6px 8px", textAlign: "left", borderBottom: "2px solid #e2e8f0", fontSize: "0.68rem", color: "#64748b" }}>Priority</th>
                      {Object.entries(mergedBenignCats).map(([k, v]) => (
                        <th key={k} style={{ padding: "6px 8px", textAlign: "center", borderBottom: "2px solid #e2e8f0", fontSize: "0.68rem", color: v.color }}>{v.icon} {v.label}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {["1","2","3","4"].map(pk => {
                      const p = pSlots[pk];
                      return <tr key={pk}>
                        <td style={{ padding: "6px 8px", fontWeight: 700, color: p.color, borderBottom: "1px solid #f1f5f9" }}>
                          {pk}. {p.label}
                        </td>
                        {Object.keys(mergedBenignCats).map(cat => (
                          <td key={cat} style={{ padding: "4px 6px", textAlign: "center", borderBottom: "1px solid #f1f5f9" }}>
                            <input type="number" min="0" max="50" value={p.slots[cat] ?? 0}
                              onChange={e => {
                                const val = parseInt(e.target.value) || 0;
                                updateConfig(prev => ({
                                  ...prev,
                                  prioritySlots: {
                                    ...(prev.prioritySlots || DEFAULT_PRIORITY_SLOTS),
                                    [pk]: {
                                      ...((prev.prioritySlots || DEFAULT_PRIORITY_SLOTS)[pk]),
                                      slots: {
                                        ...((prev.prioritySlots || DEFAULT_PRIORITY_SLOTS)[pk]?.slots || DEFAULT_PRIORITY_SLOTS[pk].slots),
                                        [cat]: val
                                      }
                                    }
                                  }
                                }));
                              }}
                              style={{ width: 50, padding: "5px 4px", textAlign: "center", border: "1.5px solid #e2e8f0", borderRadius: 6, fontSize: "0.82rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif" }}
                            />
                          </td>
                        ))}
                      </tr>;
                    })}
                  </tbody>
                </table>
              </div>
              <button onClick={() => updateConfig(prev => ({ ...prev, prioritySlots: DEFAULT_PRIORITY_SLOTS }))} style={{ marginTop: 10, padding: "5px 14px", border: "1px solid #e2e8f0", borderRadius: 6, background: "#f8fafc", fontSize: "0.7rem", fontWeight: 600, color: "#64748b", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>↺ Reset to Defaults</button>
            </div>

            <div style={{ marginBottom: 18 }}>
              <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#1e293b", margin: "0 0 10px" }}>👥 Users</h3>
              <div style={{ fontSize: "0.73rem", color: "#64748b", marginBottom: 10, padding: "7px 10px", background: "#f8fafc", borderRadius: 8, border: "1px solid #e2e8f0", lineHeight: 1.8 }}>
                <b>Admin</b>: Full access + delete (PIN verified) + settings | <b>Resident</b>: Clinical details, list, operate, HPE, follow-ups | <b>Faculty</b>: View + HPE + follow-ups | <b>Guest</b>: View only
              </div>
              {users.map(u => <div key={u.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", marginBottom: 5, background: "#fff" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                  <b style={{ fontSize: "0.86rem" }}>{u.name}</b>
                  <span style={{ color: "#94a3b8", fontSize: "0.76rem" }}>@{u.username}</span>
                  <Bdg bg={ROLE_COLORS[u.role].bg} color={ROLE_COLORS[u.role].color} border={ROLE_COLORS[u.role].b}>{ROLE_LABELS[u.role]}</Bdg>
                  {u.id === me.id && <Bdg bg="#eff6ff" color="#1565c0" border="#93c5fd">YOU</Bdg>}
                </div>
                {u.id !== me.id && <button style={{ ...S.btnSm, color: "#c62828" }} onClick={async () => { const up = users.filter(x => x.id !== u.id); up.push({ _deletedIds: [u.id] }); setUsers(up.filter(x => !x._deletedIds)); await save(SK.USERS, up); show("Removed."); }}>Remove</button>}
              </div>)}
            </div>

            <div style={{ padding: 16, borderRadius: 12, background: "#fafafe", border: "1px solid #e2e8f0" }}>
              <h4 style={{ fontSize: "0.86rem", fontWeight: 600, margin: "0 0 10px" }}>Add User</h4>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(130px,1fr))", gap: 8, alignItems: "end" }}>
                <div><label style={S.label}>Name</label><input style={S.input} placeholder="Dr. Name" value={nuf.name} onChange={e => setNuf({ ...nuf, name: e.target.value })} /></div>
                <div><label style={S.label}>Username</label><input style={S.input} placeholder="username" value={nuf.username} onChange={e => setNuf({ ...nuf, username: e.target.value })} /></div>
                <div><label style={S.label}>PIN</label><input style={S.input} type="password" placeholder="4+ digits" value={nuf.pin} onChange={e => setNuf({ ...nuf, pin: e.target.value })} maxLength={6} /></div>
                <div><label style={S.label}>Role</label><select style={S.input} value={nuf.role} onChange={e => setNuf({ ...nuf, role: e.target.value })}><option value="admin">Admin</option><option value="resident">Resident</option><option value="faculty">Faculty</option><option value="guest">Guest</option></select></div>
                <button style={{ ...S.btnP, padding: "10px 18px" }} onClick={async () => {
                  if (!nuf.name || !nuf.username || !nuf.pin || nuf.pin.length < 4) { show("Fill all. PIN≥4.", "error"); return; }
                  if (users.find(u => u.username === nuf.username.trim().toLowerCase())) { show("Username taken.", "error"); return; }
                  const up = [...users, { id: "u" + Date.now(), name: nuf.name.trim(), username: nuf.username.trim().toLowerCase(), pin: nuf.pin.trim(), role: nuf.role }];
                  setUsers(up); await save(SK.USERS, up); setNuf({ name: "", username: "", pin: "", role: "resident" }); show("Added!");
                }}>Add</button>
              </div>
            </div>

            {/* 🔔 Push Notifications */}
            <div style={{ marginBottom: 24, padding: 16, borderRadius: 12, background: "#fefce8", border: "1px solid #fde68a" }}>
              <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#92400e", margin: "0 0 8px" }}>🔔 Push Notifications</h3>
              <p style={{ fontSize: "0.75rem", color: "#78350f", margin: "0 0 14px" }}>Enable notifications on this device. Alerts are sent automatically to relevant team members based on their involvement in each case.</p>
              <NotificationToggle show={show} />
              <div style={{ marginTop: 14, padding: 12, borderRadius: 8, background: "#fff7ed", border: "1px solid #fed7aa", fontSize: "0.72rem", color: "#92400e", lineHeight: 1.6 }}>
                <div style={{ fontWeight: 700, marginBottom: 6 }}>How automatic notifications work:</div>
                <div>🔪 <b>Surgery Completed</b> — notifies the operating surgeon, all assistants, anaesthetist, and the user who scheduled the patient</div>
                <div style={{ marginTop: 4 }}>✅ <b>Patient Discharged</b> — notifies the same surgical team from the operative note</div>
                <div style={{ marginTop: 4 }}>🚨 <b>Emergency Admission</b> — notifies the user who admitted the patient</div>
                <div style={{ marginTop: 4 }}>📅 <b>Academic Reminders</b> — sent to all subscribers on same day, 1 day before, and 3 days before each academic event</div>
                <div style={{ marginTop: 6, color: "#b45309" }}>Surgeons are matched to SurgTrack accounts via their linked profile or by name. Make sure team members have linked their profiles in Settings → Surgeons.</div>
              </div>
            </div>
            </>}

            {/* ─── SURGEONS TAB ─── */}
            {settingsTab === "surgeons" && <>
            <div style={{ marginBottom: 24, padding: 16, borderRadius: 12, background: "#eff6ff", border: "1px solid #bfdbfe" }}>
              <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#1565c0", margin: "0 0 4px" }}>🩺 Surgeon Registry</h3>
              <p style={{ fontSize: "0.72rem", color: "#64748b", margin: "0 0 12px" }}>These names appear in the operative note dropdowns. Users can link their profiles to a surgeon entry.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {(config.surgeons || []).map(s => {
                  const linkedUser = users.find(u => u.linkedSurgeon === s.id && u.linkStatus === "approved");
                  return (
                  <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", background: "#fff", borderRadius: 8, border: "1px solid #e2e8f0", flexWrap: "wrap" }}>
                    <span style={{ flex: 1, fontWeight: 600, fontSize: "0.84rem", color: "#1e293b", minWidth: 140 }}>{s.name}</span>
                    <span style={{ fontSize: "0.7rem", color: "#64748b", minWidth: 100 }}>{s.designation || ""}</span>
                    {linkedUser && <Bdg bg="#e8f5e9" color="#2e7d32" border="#a5d6a7">🔗 {linkedUser.name}</Bdg>}
                    <button onClick={() => {
                      const newName = prompt("Edit surgeon name:", s.name);
                      if (newName && newName.trim()) {
                        const newDesig = prompt("Designation:", s.designation || "");
                        updateConfig(prev => ({ ...prev, surgeons: (prev.surgeons || []).map(x => x.id === s.id ? { ...x, name: newName.trim(), designation: (newDesig || "").trim() } : x) }));
                      }
                    }} style={{ ...S.btnSm, color: "#1565c0" }}>✏️</button>
                    <button onClick={() => updateConfig(prev => ({ ...prev, surgeons: (prev.surgeons || []).filter(x => x.id !== s.id) }))} style={{ ...S.btnSm, color: "#c62828" }}>✕</button>
                  </div>
                  );
                })}
              </div>
              <div style={{ display: "flex", gap: 8, marginTop: 12, alignItems: "end", flexWrap: "wrap" }}>
                <div style={{ flex: 1, minWidth: 140 }}><label style={S.label}>Name</label><input id="newSurgName" style={S.input} placeholder="Dr. Full Name" /></div>
                <div style={{ flex: 1, minWidth: 120 }}><label style={S.label}>Designation</label><input id="newSurgDesig" style={S.input} placeholder="e.g. Professor" /></div>
                <button style={{ ...S.btnP, padding: "10px 16px", whiteSpace: "nowrap" }} onClick={() => {
                  const nameEl = document.getElementById("newSurgName"), desigEl = document.getElementById("newSurgDesig");
                  const n = nameEl?.value?.trim(); if (!n) { show("Enter surgeon name.", "error"); return; }
                  updateConfig(prev => ({ ...prev, surgeons: [...(prev.surgeons || []), { id: "s" + Date.now(), name: n, designation: (desigEl?.value || "").trim(), canOperate: true }] }));
                  if (nameEl) nameEl.value = ""; if (desigEl) desigEl.value = "";
                  show("Surgeon added.");
                }}>+ Add</button>
              </div>
            </div>

            {/* Link Requests */}
            {(() => {
              const pendingLinks = users.filter(u => u.linkStatus === "pending" && u.requestedSurgeon);
              if (pendingLinks.length === 0) return <div style={{ padding: 16, borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0", fontSize: "0.82rem", color: "#94a3b8", textAlign: "center" }}>No pending link requests.</div>;
              return <div style={{ padding: 16, borderRadius: 12, background: "#fff8e1", border: "1px solid #ffe082" }}>
                <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#e65100", margin: "0 0 10px" }}>🔗 Pending Link Requests</h3>
                {pendingLinks.map(u => {
                  const surgeonEntry = (config.surgeons || []).find(s => s.id === u.requestedSurgeon);
                  return <div key={u.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", background: "#fff", borderRadius: 8, border: "1px solid #e2e8f0", marginBottom: 6, flexWrap: "wrap" }}>
                    <div style={{ flex: 1, minWidth: 120 }}>
                      <b style={{ fontSize: "0.84rem" }}>{u.name}</b> <span style={{ color: "#94a3b8", fontSize: "0.72rem" }}>@{u.username}</span>
                      <div style={{ fontSize: "0.72rem", color: "#64748b" }}>wants to link as → <b style={{ color: "#1565c0" }}>{surgeonEntry?.name || "Unknown"}</b></div>
                    </div>
                    <button onClick={async () => {
                      const up = users.map(x => x.id === u.id ? { ...x, linkedSurgeon: u.requestedSurgeon, linkStatus: "approved", requestedSurgeon: null } : x);
                      setUsers(up); await save(SK.USERS, up); show(`${u.name} linked to ${surgeonEntry?.name}.`);
                    }} style={{ ...S.btnP, padding: "6px 14px", fontSize: "0.76rem" }}>✅ Approve</button>
                    <button onClick={async () => {
                      const up = users.map(x => x.id === u.id ? { ...x, linkStatus: "rejected", requestedSurgeon: null } : x);
                      setUsers(up); await save(SK.USERS, up); show(`${u.name} request rejected.`);
                    }} style={{ ...S.btnSm, color: "#c62828", padding: "6px 12px" }}>✕ Reject</button>
                  </div>;
                })}
              </div>;
            })()}
            </>}

            {/* ─── HOLIDAYS TAB ─── */}
            {settingsTab === "holidays" && <>
              <div style={{ padding: 16, borderRadius: 12, background: "#fff8e1", border: "1px solid #ffe082", marginBottom: 16 }}>
                <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#e65100", margin: "0 0 10px" }}>🎉 Holiday List</h3>
                <p style={{ fontSize: "0.74rem", color: "#64748b", margin: "0 0 12px" }}>Holidays will be highlighted in rosters and you'll be notified when scheduling patients in a week that contains a holiday.</p>

                {/* Add holiday form */}
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "end", marginBottom: 14 }}>
                  <div><label style={{ ...S.label, fontSize: "0.66rem" }}>Date</label><input style={{ ...S.input, width: 150 }} type="date" value={newHol.date} onChange={e => setNewHol({ ...newHol, date: e.target.value })} /></div>
                  <div style={{ flex: 1, minWidth: 160 }}><label style={{ ...S.label, fontSize: "0.66rem" }}>Holiday Name</label><input style={S.input} value={newHol.name} onChange={e => setNewHol({ ...newHol, name: e.target.value })} placeholder="e.g. Republic Day, Eid..." /></div>
                  <button onClick={() => {
                    if (!newHol.date || !newHol.name.trim()) { show("Enter date and name.", "error"); return; }
                    if ((config.holidays || []).find(h => h.date === newHol.date)) { show("Holiday already exists on this date.", "error"); return; }
                    updateConfig({ ...config, holidays: [...(config.holidays || []), { date: newHol.date, name: newHol.name.trim() }].sort((a, b) => a.date.localeCompare(b.date)) });
                    setNewHol({ date: "", name: "" });
                    show("Holiday added.");
                  }} style={{ ...S.btnP, padding: "10px 18px", whiteSpace: "nowrap" }}>+ Add</button>
                </div>

                {/* Holiday list */}
                {(config.holidays || []).length === 0 && <div style={{ padding: "12px", textAlign: "center", color: "#94a3b8", fontSize: "0.82rem" }}>No holidays added yet.</div>}
                {(config.holidays || []).map((h, i) => (
                  <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 12px", borderRadius: 8, border: "1px solid #ffe082", marginBottom: 4, background: "#fffde7" }}>
                    <div>
                      <span style={{ fontSize: "0.8rem", fontWeight: 600, color: "#e65100" }}>{fmtD(h.date)}</span>
                      <span style={{ fontSize: "0.8rem", color: "#475569", marginLeft: 10 }}>{h.name}</span>
                    </div>
                    <button onClick={() => { updateConfig({ ...config, holidays: (config.holidays || []).filter((_, j) => j !== i) }); show("Removed."); }} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.72rem", fontWeight: 700 }}>✕</button>
                  </div>
                ))}
              </div>
            </>}

            {/* ─── BACKUP TAB ─── */}
            {settingsTab === "backup" && <>
              {/* FULL SYSTEM BACKUP */}
              <div style={{ padding: 16, borderRadius: 12, background: "#eff6ff", border: "1px solid #bfdbfe", marginBottom: 16 }}>
                <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#1565c0", margin: "0 0 8px" }}>{"💾"} Full System Backup</h3>
                <p style={{ fontSize: "0.76rem", color: "#64748b", margin: "0 0 14px", lineHeight: 1.6 }}>
                  Downloads a complete backup of <b>all data</b> — patients, users, config, surgeons, holidays, rosters, research protocols, and custom repository. We recommend downloading a backup <b>weekly</b>.
                </p>
                <button onClick={async () => {
                  const backup = {
                    _version: "surgtrack-backup-v2",
                    _date: new Date().toISOString(),
                    _app: "SurgTrack",
                    patients: patients,
                    users: users,
                    config: config,
                    dutyRoster: dutyData,
                    acadRoster: acadData,
                  };
                  const data = JSON.stringify(backup, null, 2);
                  const blob = new Blob([data], { type: "application/json" });
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement("a"); a.href = url;
                  a.download = `SurgTrack_FullBackup_${fmt(new Date())}.json`;
                  a.click(); URL.revokeObjectURL(url);
                  show(`Full backup downloaded — ${patients.length} patients, ${users.length} users, ${(config.surgeons || []).length} surgeons.`);
                }} style={{ padding: "10px 24px", background: "linear-gradient(135deg,#1565c0,#1976d2)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.86rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>
                  {"📥"} Download Full Backup
                </button>
                <div style={{ marginTop: 10, display: "flex", gap: 12, flexWrap: "wrap", fontSize: "0.72rem", color: "#64748b" }}>
                  <span>{"👥"} {patients.length} patients</span>
                  <span>{"🔑"} {users.length} users</span>
                  <span>{"🩺"} {(config.surgeons || []).length} surgeons</span>
                  <span>{"🎉"} {(config.holidays || []).length} holidays</span>
                  <span>{"🔬"} {(config.researchProtocols || []).length} protocols</span>
                </div>
              </div>

              {/* EXCEL EXPORT */}
              <div style={{ padding: 16, borderRadius: 12, background: "#f0fdf4", border: "1px solid #bbf7d0", marginBottom: 16 }}>
                <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#2e7d32", margin: "0 0 8px" }}>{"📊"} Excel Export (Scheduled Patients)</h3>
                <p style={{ fontSize: "0.76rem", color: "#64748b", margin: "0 0 14px" }}>Download scheduled patients (Date Given / Admitted / Listed) as Excel file.</p>
                <button onClick={async () => {
                  if (!window.XLSX) {
                    await new Promise((resolve, reject) => { const s = document.createElement("script"); s.src = "https://cdn.sheetjs.com/xlsx-0.20.1/package/dist/xlsx.full.min.js"; s.onload = resolve; s.onerror = () => reject(new Error("Failed to load SheetJS")); document.head.appendChild(s); });
                  }
                  const XLSX = window.XLSX;
                  const scheduled = patients.filter(p => ["Date Given", "Admitted", "Listed"].includes(p.status));
                  if (scheduled.length === 0) { show("No scheduled patients to backup.", "error"); return; }
                  const rows = []; scheduled.forEach(p => {
                    rows.push({ "Name": p.name, "Age": p.age, "Sex": p.sex, "Phone": p.phone, "Type": p.type === "malignancy" ? "Malignancy" : "Benign", "Diagnosis": p.diagnosis || p.malignancySite || "", "Procedure": p.plannedProcedure || "", "Date": p.surgeryDate ? fmtD(p.surgeryDate) : "", "Status": p.status, "Notes": p.notes || "" });
                  });
                  const ws = XLSX.utils.json_to_sheet(rows); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "Scheduled"); XLSX.writeFile(wb, `SurgTrack_Scheduled_${fmt(new Date())}.xlsx`);
                  show(`Excel downloaded — ${scheduled.length} patients.`);
                }} style={{ padding: "10px 24px", background: "linear-gradient(135deg,#2e7d32,#43a047)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.86rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>
                  {"📊"} Download Excel
                </button>
              </div>

              {/* RESTORE FROM BACKUP */}
              <div style={{ padding: 16, borderRadius: 12, background: "#fff3e0", border: "1px solid #ffcc80" }}>
                <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#e65100", margin: "0 0 8px" }}>{"🔄"} Restore from Backup</h3>
                <p style={{ fontSize: "0.76rem", color: "#64748b", margin: "0 0 14px", lineHeight: 1.6 }}>
                  Upload a previously downloaded JSON backup file to restore all data. <b style={{ color: "#c62828" }}>This will overwrite all current data.</b>
                </p>
                <input type="file" accept=".json" onChange={async (e) => {
                  const file = e.target.files?.[0]; if (!file) return;
                  try {
                    const text = await file.text();
                    const backup = JSON.parse(text);
                    if (!backup._version || !backup._version.startsWith("surgtrack-backup")) {
                      show("Invalid backup file — not a SurgTrack backup.", "error"); return;
                    }
                    // Confirm with user
                    const msg = `Restore from backup dated ${backup._date ? new Date(backup._date).toLocaleDateString() : "unknown"}?\n\n` +
                      `${(backup.patients || []).length} patients, ${(backup.users || []).length} users, ${(backup.config?.surgeons || []).length} surgeons\n\n` +
                      `THIS WILL OVERWRITE ALL CURRENT DATA.`;
                    if (!window.confirm(msg)) { e.target.value = ""; return; }
                    // Restore
                    if (backup.patients) { setPatients(backup.patients); await save(SK.PATIENTS, backup.patients); }
                    if (backup.users) { setUsers(backup.users); await save(SK.USERS, backup.users); }
                    if (backup.config) { setConfig(backup.config); await save(SK.CONFIG, backup.config); }
                    if (backup.dutyRoster) { setDutyData(backup.dutyRoster); await save("st:duty_roster", backup.dutyRoster); }
                    if (backup.acadRoster) { setAcadData(backup.acadRoster); await save("st:acad_roster", backup.acadRoster); }
                    show(`Restored! ${(backup.patients || []).length} patients, ${(backup.users || []).length} users.`);
                    e.target.value = "";
                  } catch (err) { show("Failed to parse backup file: " + err.message, "error"); }
                }} style={{ display: "block", marginBottom: 10, fontSize: "0.82rem" }} />
                <div style={{ fontSize: "0.72rem", color: "#94a3b8", lineHeight: 1.5 }}>
                  Accepts: <b>SurgTrack_FullBackup_*.json</b> files only. The file must have been created by the Full System Backup button above.
                </div>
              </div>
            </>}

            {/* ─── DUTY ROSTER TAB ─── */}
            {settingsTab === "duty" && <>
              <div style={{ marginBottom: 10, fontSize: "0.76rem", color: "#64748b", padding: "8px 12px", background: "#eff6ff", borderRadius: 8, border: "1px solid #bfdbfe" }}>
                Tap any day cell to add or edit duty assignments. Changes are saved automatically.
              </div>
              <CalendarGrid ym={dutyMonth} setYm={setDutyMonth} data={dutyData} saveData={saveDuty} color="#1565c0" title="Duty Roster" placeholder="On-call, Emergency..." />
            </>}

            {/* ─── ACADEMIC ROSTER TAB ─── */}
            {settingsTab === "academic" && <>
              <div style={{ marginBottom: 10, fontSize: "0.76rem", color: "#64748b", padding: "8px 12px", background: "#f3e5f5", borderRadius: 8, border: "1px solid #ce93d8" }}>
                Tap any day cell to add or edit academic activities. Changes are saved automatically.
              </div>
              <CalendarGrid ym={acadMonth} setYm={setAcadMonth} data={acadData} saveData={saveAcad} color="#6a1b9a" title="Academic Roster" placeholder="Seminar, Journal Club..." />
            </>}

            {/* ─── FOLLOW-UP TEMPLATES TAB ─── */}
            {settingsTab === "followup" && <>
              <div style={{ fontSize: "0.76rem", color: "#64748b", marginBottom: 12, padding: "8px 12px", background: "#fff8e1", borderRadius: 8, border: "1px solid #ffe082" }}>
                Create custom follow-up templates for specific diagnoses/procedures. These will appear alongside the built-in templates when recording follow-ups.
              </div>

              {!editingTemplate && <>
                <button onClick={() => setEditingTemplate({ name: "", matchProcedure: "", matchDiagnosis: "", visits: [{ label: "1 Week", days: 7, fields: [{ key: "wound", label: "Wound Status", type: "select", opts: ["Healthy","Erythema","Discharge","Dehiscence","Other"] }, { key: "notes", label: "Notes", type: "text" }] }] })} style={{ padding: "8px 16px", background: "linear-gradient(135deg,#1565c0,#1976d2)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.8rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif", marginBottom: 12 }}>+ Create New Template</button>

                {customFupTemplates.length === 0 && <div style={{ color: "#94a3b8", fontSize: "0.82rem", textAlign: "center", padding: 20 }}>No custom templates yet. Built-in templates cover 20+ common procedures. Create a custom template for research or specific protocols.</div>}

                {customFupTemplates.map((tpl, ti) => (
                  <div key={ti} style={{ padding: 12, background: "#f8fafc", borderRadius: 8, border: "1px solid #e2e8f0", marginBottom: 8 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <div>
                        <span style={{ fontWeight: 700, fontSize: "0.84rem", color: "#1e293b" }}>{tpl.name}</span>
                        {tpl.matchProcedure && <span style={{ fontSize: "0.68rem", color: "#64748b", marginLeft: 8 }}>Procedure: {tpl.matchProcedure}</span>}
                        {tpl.matchDiagnosis && <span style={{ fontSize: "0.68rem", color: "#64748b", marginLeft: 8 }}>Diagnosis: {tpl.matchDiagnosis}</span>}
                      </div>
                      <div style={{ display: "flex", gap: 6 }}>
                        <span style={{ fontSize: "0.68rem", color: "#1565c0", fontWeight: 600 }}>{tpl.visits.length} visit(s)</span>
                        <button onClick={() => setEditingTemplate({ ...tpl, _editIdx: ti })} style={{ border: "1px solid #90caf9", background: "#e3f2fd", borderRadius: 6, padding: "3px 10px", fontSize: "0.68rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Edit</button>
                        <button onClick={() => { if (confirm("Delete this template?")) setCustomFupTemplates(prev => prev.filter((_, j) => j !== ti)); }} style={{ border: "1px solid #ef9a9a", background: "#ffebee", borderRadius: 6, padding: "3px 10px", fontSize: "0.68rem", fontWeight: 600, color: "#c62828", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Delete</button>
                      </div>
                    </div>
                    <div style={{ marginTop: 6, display: "flex", gap: 6, flexWrap: "wrap" }}>
                      {tpl.visits.map((v, vi) => <span key={vi} style={{ fontSize: "0.68rem", padding: "2px 8px", borderRadius: 6, background: "#e8f5e9", color: "#2e7d32", fontWeight: 600 }}>{v.label} ({v.fields.length} fields)</span>)}
                    </div>
                  </div>
                ))}
              </>}

              {/* Template Editor */}
              {editingTemplate && (() => {
                const tpl = editingTemplate;
                const setTpl = (fn) => setEditingTemplate(prev => typeof fn === "function" ? fn(prev) : fn);
                const FIELD_TYPES = ["select", "text", "number", "date"];

                return <div style={{ background: "#fff", borderRadius: 10, border: "2px solid #1565c0", padding: 16 }}>
                  <h3 style={{ fontSize: "0.92rem", color: "#1565c0", margin: "0 0 12px", fontFamily: "'Outfit',sans-serif" }}>{tpl._editIdx !== undefined ? "Edit" : "New"} Follow-Up Template</h3>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 8, marginBottom: 12 }}>
                    <div><label style={{ display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#475569", marginBottom: 2 }}>TEMPLATE NAME *</label><input style={{ width: "100%", padding: "7px 10px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" }} value={tpl.name} onChange={e => setTpl({ ...tpl, name: e.target.value })} placeholder="e.g. Thyroid Research Protocol" /></div>
                    <div><label style={{ display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#475569", marginBottom: 2 }}>MATCH PROCEDURE</label><SearchSelect clearable options={mergedOpProcs} value={tpl.matchProcedure || ""} onChange={v => setTpl({ ...tpl, matchProcedure: v || "" })} placeholder="Search procedure..." /></div>
                    <div><label style={{ display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#475569", marginBottom: 2 }}>MATCH DIAGNOSIS</label><SearchSelect clearable options={[...Object.keys(mergedMaligSites), ...mergedAllBenignDx.map(d => d.dx)]} value={tpl.matchDiagnosis || ""} onChange={v => setTpl({ ...tpl, matchDiagnosis: v || "" })} placeholder="Search diagnosis..." /></div>
                    <div><label style={{ display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#7c3aed", marginBottom: 2 }}>MATCH RESEARCH PROTOCOL</label><SearchSelect clearable options={(config.researchProtocols || []).map(r => r.name)} value={tpl.matchProtocol || ""} onChange={v => setTpl({ ...tpl, matchProtocol: v || "" })} placeholder="Select protocol..." /></div>
                  </div>

                  {tpl.visits.map((vis, vi) => (
                    <div key={vi} style={{ marginBottom: 10, padding: 10, background: "#f0f9ff", borderRadius: 8, border: "1px solid #b3e5fc" }}>
                      <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8 }}>
                        <input style={{ width: 100, padding: "5px 8px", border: "1.5px solid #e2e8f0", borderRadius: 6, fontSize: "0.78rem", fontFamily: "'Outfit',sans-serif" }} value={vis.label} onChange={e => setTpl(prev => { const v = [...prev.visits]; v[vi] = { ...v[vi], label: e.target.value }; return { ...prev, visits: v }; })} placeholder="Visit label" />
                        <span style={{ fontSize: "0.68rem", color: "#64748b" }}>after</span>
                        <input type="number" style={{ width: 60, padding: "5px 8px", border: "1.5px solid #e2e8f0", borderRadius: 6, fontSize: "0.78rem", fontFamily: "'Outfit',sans-serif" }} value={vis.days} onChange={e => setTpl(prev => { const v = [...prev.visits]; v[vi] = { ...v[vi], days: parseInt(e.target.value) || 0 }; return { ...prev, visits: v }; })} />
                        <span style={{ fontSize: "0.68rem", color: "#64748b" }}>days</span>
                        <span style={{ fontSize: "0.68rem", color: "#1565c0", fontWeight: 600, marginLeft: "auto" }}>{vis.fields.length} fields</span>
                        {tpl.visits.length > 1 && <button onClick={() => setTpl(prev => ({ ...prev, visits: prev.visits.filter((_, j) => j !== vi) }))} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.72rem", fontWeight: 600 }}>✕</button>}
                      </div>

                      {vis.fields.map((fd, fi) => (
                        <div key={fi} style={{ display: "flex", gap: 6, alignItems: "center", marginBottom: 4, padding: "3px 0" }}>
                          <input style={{ flex: 1, padding: "4px 8px", border: "1px solid #e2e8f0", borderRadius: 6, fontSize: "0.74rem", fontFamily: "'Outfit',sans-serif" }} value={fd.label} onChange={e => setTpl(prev => { const v = [...prev.visits]; const f = [...v[vi].fields]; f[fi] = { ...f[fi], label: e.target.value, key: e.target.value.toLowerCase().replace(/[^a-z0-9]/g, "_") }; v[vi] = { ...v[vi], fields: f }; return { ...prev, visits: v }; })} placeholder="Field label" />
                          <select style={{ width: 90, padding: "4px 6px", border: "1px solid #e2e8f0", borderRadius: 6, fontSize: "0.72rem", fontFamily: "'Outfit',sans-serif" }} value={fd.type} onChange={e => setTpl(prev => { const v = [...prev.visits]; const f = [...v[vi].fields]; f[fi] = { ...f[fi], type: e.target.value }; v[vi] = { ...v[vi], fields: f }; return { ...prev, visits: v }; })}>
                            {FIELD_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                          </select>
                          {fd.type === "select" && <input style={{ flex: 1, padding: "4px 8px", border: "1px solid #e2e8f0", borderRadius: 6, fontSize: "0.72rem", fontFamily: "'Outfit',sans-serif" }} value={(fd.opts || []).join(", ")} onChange={e => setTpl(prev => { const v = [...prev.visits]; const f = [...v[vi].fields]; f[fi] = { ...f[fi], opts: e.target.value.split(",").map(s => s.trim()).filter(Boolean) }; v[vi] = { ...v[vi], fields: f }; return { ...prev, visits: v }; })} placeholder="Options (comma-separated)" />}
                          <button onClick={() => setTpl(prev => { const v = [...prev.visits]; const f = v[vi].fields.filter((_, j) => j !== fi); v[vi] = { ...v[vi], fields: f }; return { ...prev, visits: v }; })} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.72rem" }}>✕</button>
                        </div>
                      ))}
                      <button onClick={() => setTpl(prev => { const v = [...prev.visits]; v[vi] = { ...v[vi], fields: [...v[vi].fields, { key: "field_" + Date.now(), label: "", type: "text", opts: [] }] }; return { ...prev, visits: v }; })} style={{ padding: "3px 10px", border: "1px dashed #90caf9", background: "#fff", borderRadius: 6, fontSize: "0.68rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif", marginTop: 4 }}>+ Add Field</button>
                    </div>
                  ))}

                  <button onClick={() => setTpl(prev => ({ ...prev, visits: [...prev.visits, { label: "Visit " + (prev.visits.length + 1), days: 30, fields: [{ key: "notes", label: "Notes", type: "text", opts: [] }] }] }))} style={{ padding: "5px 12px", border: "1px dashed #1565c0", background: "#e3f2fd", borderRadius: 6, fontSize: "0.72rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif", marginBottom: 12 }}>+ Add Visit</button>

                  <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 12 }}>
                    <button onClick={() => setEditingTemplate(null)} style={{ padding: "7px 16px", border: "1.5px solid #e2e8f0", borderRadius: 8, background: "#fff", fontSize: "0.78rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Cancel</button>
                    <button onClick={() => {
                      if (!tpl.name.trim()) { show("Template name is required.", "error"); return; }
                      if (tpl.visits.some(v => v.fields.length === 0)) { show("Each visit needs at least one field.", "error"); return; }
                      const clean = { ...tpl }; delete clean._editIdx;
                      if (tpl._editIdx !== undefined) {
                        setCustomFupTemplates(prev => prev.map((t, j) => j === tpl._editIdx ? clean : t));
                      } else {
                        setCustomFupTemplates(prev => [...prev, clean]);
                      }
                      setEditingTemplate(null);
                      show(`Template "${clean.name}" saved.`);
                    }} style={{ padding: "7px 16px", background: "linear-gradient(135deg,#1565c0,#1976d2)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.78rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"💾"} Save Template</button>
                  </div>
                </div>;
              })()}
            </>}

            {/* ─── DIAGNOSIS & PROCEDURE REPOSITORY TAB ─── */}
            {settingsTab === "repository" && (() => {
              const inp5 = { width: "100%", padding: "7px 10px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" };
              const lbl5 = { display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#475569", marginBottom: 2, textTransform: "uppercase", letterSpacing: "0.04em" };

              const addBenignDx = () => {
                if (!newBenignDx.trim()) { show("Enter a diagnosis name.", "error"); return; }
                const procs = newBenignProcs.split(",").map(s => s.trim()).filter(Boolean);
                if (procs.length === 0) { show("Enter at least one procedure.", "error"); return; }
                setCustomRepo(prev => {
                  const bd = { ...prev.benignDx };
                  if (!bd[newBenignCat]) bd[newBenignCat] = {};
                  bd[newBenignCat][newBenignDx.trim()] = procs;
                  // Also add procedures to opProcs
                  const op = [...new Set([...(prev.opProcs || []), ...procs])];
                  return { ...prev, benignDx: bd, opProcs: op };
                });
                show(`Added "${newBenignDx.trim()}" to ${mergedBenignCats[newBenignCat]?.label || newBenignCat}.`);
                setNewBenignDx(""); setNewBenignProcs("");
              };

              const addMaligSite = () => {
                if (!newMaligSite.trim()) { show("Enter a malignancy site.", "error"); return; }
                const procs = newMaligProcs.split(",").map(s => s.trim()).filter(Boolean);
                if (procs.length === 0) { show("Enter at least one procedure.", "error"); return; }
                setCustomRepo(prev => {
                  const ms = { ...prev.maligSites };
                  if (ms[newMaligSite.trim()]) { ms[newMaligSite.trim()] = { procedures: [...new Set([...ms[newMaligSite.trim()].procedures, ...procs])] }; }
                  else { ms[newMaligSite.trim()] = { procedures: procs }; }
                  const op = [...new Set([...(prev.opProcs || []), ...procs])];
                  return { ...prev, maligSites: ms, opProcs: op };
                });
                show(`Added "${newMaligSite.trim()}" to malignancy sites.`);
                setNewMaligSite(""); setNewMaligProcs("");
              };

              const addProc = () => {
                if (!newProc.trim()) return;
                setCustomRepo(prev => ({
                  ...prev,
                  opProcs: [...new Set([...(prev.opProcs || []), newProc.trim()])],
                  procCategories: { ...(prev.procCategories || {}), [newProc.trim()]: newProcCat }
                }));
                show(`Added procedure: "${newProc.trim()}" → ${newProcCat}`);
                setNewProc(""); setNewProcCat("others");
              };

              const removeBenignDx = (cat, dx) => {
                setCustomRepo(prev => {
                  const bd = { ...prev.benignDx };
                  if (bd[cat]) { const c = { ...bd[cat] }; delete c[dx]; bd[cat] = c; }
                  return { ...prev, benignDx: bd };
                });
                show(`Removed custom diagnosis: "${dx}"`);
              };

              const removeMaligSite = (site) => {
                setCustomRepo(prev => {
                  const ms = { ...prev.maligSites }; delete ms[site];
                  return { ...prev, maligSites: ms };
                });
                show(`Removed custom site: "${site}"`);
              };

              const removeProc = (p) => {
                setCustomRepo(prev => ({ ...prev, opProcs: (prev.opProcs || []).filter(x => x !== p) }));
                show(`Removed custom procedure: "${p}"`);
              };

              const customBenignCount = Object.values(customRepo.benignDx || {}).reduce((a, o) => a + Object.keys(o).length, 0);
              const customMaligCount = Object.keys(customRepo.maligSites || {}).length;
              const customProcCount = (customRepo.opProcs || []).length;

              return <>
                <div style={{ fontSize: "0.76rem", color: "#64748b", marginBottom: 12, padding: "8px 12px", background: "#e3f2fd", borderRadius: 8, border: "1px solid #90caf9" }}>
                  Central repository of diagnoses and procedures. Additions here appear everywhere — appointments, clinical forms, operative forms, follow-up templates, and export. <b>Built-in entries cannot be removed.</b>
                </div>

                <div style={{ display: "flex", gap: 12, marginBottom: 14 }}>
                  <div style={{ flex: 1, padding: 10, borderRadius: 8, border: "1px solid #e2e8f0", textAlign: "center" }}>
                    <div style={{ fontSize: "1.1rem", fontWeight: 700, color: "#2e7d32" }}>{mergedAllBenignDx.length}</div>
                    <div style={{ fontSize: "0.66rem", color: "#64748b" }}>Benign Diagnoses</div>
                    {customBenignCount > 0 && <div style={{ fontSize: "0.6rem", color: "#1565c0", fontWeight: 600 }}>+{customBenignCount} custom</div>}
                  </div>
                  <div style={{ flex: 1, padding: 10, borderRadius: 8, border: "1px solid #e2e8f0", textAlign: "center" }}>
                    <div style={{ fontSize: "1.1rem", fontWeight: 700, color: "#c62828" }}>{Object.keys(mergedMaligSites).length}</div>
                    <div style={{ fontSize: "0.66rem", color: "#64748b" }}>Malignancy Sites</div>
                    {customMaligCount > 0 && <div style={{ fontSize: "0.6rem", color: "#1565c0", fontWeight: 600 }}>+{customMaligCount} custom</div>}
                  </div>
                  <div style={{ flex: 1, padding: 10, borderRadius: 8, border: "1px solid #e2e8f0", textAlign: "center" }}>
                    <div style={{ fontSize: "1.1rem", fontWeight: 700, color: "#6a1b9a" }}>{mergedOpProcs.length}</div>
                    <div style={{ fontSize: "0.66rem", color: "#64748b" }}>Procedures</div>
                    {customProcCount > 0 && <div style={{ fontSize: "0.6rem", color: "#1565c0", fontWeight: 600 }}>+{customProcCount} custom</div>}
                  </div>
                </div>

                <div style={{ display: "flex", gap: 4, marginBottom: 14 }}>
                  {[["benign","Benign Diagnoses"],["malignancy","Malignancy Sites"],["procedures","Standalone Procedures"]].map(([id, l]) =>
                    <button key={id} onClick={() => setRepoTab(id)} style={{ padding: "6px 12px", borderRadius: 7, border: repoTab === id ? "2px solid #1565c0" : "1.5px solid #e2e8f0", background: repoTab === id ? "#eff6ff" : "#fff", color: repoTab === id ? "#1565c0" : "#64748b", fontWeight: 600, fontSize: "0.72rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>{l}</button>
                  )}
                </div>

                {/* ── ADD BENIGN DIAGNOSIS ── */}
                {repoTab === "benign" && <>
                  <div style={{ padding: 12, background: "#f0fdf4", borderRadius: 8, border: "1px solid #a5d6a7", marginBottom: 12 }}>
                    <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#2e7d32", marginBottom: 8 }}>Add New Benign Diagnosis</div>
                    <div style={{ display: "grid", gridTemplateColumns: "150px 1fr", gap: 8, marginBottom: 8 }}>
                      <div><label style={lbl5}>Category</label>
                        <select style={inp5} value={newBenignCat} onChange={e => setNewBenignCat(e.target.value)}>
                          {Object.entries(mergedBenignCats).map(([k, v]) => <option key={k} value={k}>{v.icon} {v.label}</option>)}
                        </select>
                      </div>
                      <div><label style={lbl5}>Diagnosis Name *</label><input style={inp5} value={newBenignDx} onChange={e => setNewBenignDx(e.target.value)} placeholder="e.g. Meckel's Diverticulum" /></div>
                    </div>
                    <div><label style={lbl5}>Procedures (comma-separated) *</label><input style={inp5} value={newBenignProcs} onChange={e => setNewBenignProcs(e.target.value)} placeholder="e.g. Diverticulectomy, Segmental Resection" /></div>
                    <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 8 }}>
                      <button onClick={addBenignDx} style={{ padding: "6px 14px", background: "#2e7d32", color: "#fff", border: "none", borderRadius: 7, fontSize: "0.76rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>+ Add Diagnosis</button>
                    </div>
                  </div>

                  {/* List custom benign entries */}
                  {customBenignCount > 0 && <div style={{ marginBottom: 12 }}>
                    <div style={{ fontSize: "0.7rem", fontWeight: 700, color: "#1565c0", marginBottom: 6 }}>Custom Additions ({customBenignCount})</div>
                    {Object.entries(customRepo.benignDx || {}).map(([cat, dxObj]) =>
                      Object.entries(dxObj).map(([dx, procs]) => (
                        <div key={dx} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "5px 8px", background: "#f8fafc", borderRadius: 6, border: "1px solid #e2e8f0", marginBottom: 3 }}>
                          <div>
                            <span style={{ fontWeight: 600, fontSize: "0.78rem", color: "#1e293b" }}>{dx}</span>
                            <span style={{ fontSize: "0.66rem", color: "#64748b", marginLeft: 6 }}>[{mergedBenignCats[cat]?.label || cat}]</span>
                            <span style={{ fontSize: "0.66rem", color: "#94a3b8", marginLeft: 6 }}>{procs.join(", ")}</span>
                          </div>
                          <button onClick={() => removeBenignDx(cat, dx)} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.7rem", fontWeight: 600 }}>✕</button>
                        </div>
                      ))
                    )}
                  </div>}

                  {/* Browse existing */}
                  <details style={{ marginTop: 8 }}>
                    <summary style={{ fontSize: "0.72rem", fontWeight: 600, color: "#64748b", cursor: "pointer" }}>Browse All Benign Diagnoses ({mergedAllBenignDx.length})</summary>
                    <div style={{ maxHeight: 300, overflow: "auto", marginTop: 6, border: "1px solid #e2e8f0", borderRadius: 8, padding: 6 }}>
                      {Object.entries(mergedBenignCats).map(([k, v]) => (
                        <div key={k} style={{ marginBottom: 8 }}>
                          <div style={{ fontWeight: 700, fontSize: "0.72rem", color: v.color, padding: "3px 0" }}>{v.icon} {v.label} ({Object.keys(v.diagnoses).length})</div>
                          {Object.entries(v.diagnoses).map(([dx, procs]) => (
                            <div key={dx} style={{ fontSize: "0.7rem", color: "#475569", padding: "1px 0 1px 12px" }}>• {dx} → <span style={{ color: "#94a3b8" }}>{procs.join(", ")}</span></div>
                          ))}
                        </div>
                      ))}
                    </div>
                  </details>
                </>}

                {/* ── ADD MALIGNANCY SITE ── */}
                {repoTab === "malignancy" && <>
                  <div style={{ padding: 12, background: "#fef2f2", borderRadius: 8, border: "1px solid #ef9a9a", marginBottom: 12 }}>
                    <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#c62828", marginBottom: 8 }}>Add New Malignancy Site</div>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 8 }}>
                      <div><label style={lbl5}>Site Name *</label><input style={inp5} value={newMaligSite} onChange={e => setNewMaligSite(e.target.value)} placeholder="e.g. Mesothelioma" /></div>
                      <div><label style={lbl5}>Procedures (comma-separated) *</label><input style={inp5} value={newMaligProcs} onChange={e => setNewMaligProcs(e.target.value)} placeholder="e.g. Pleurectomy, Debulking" /></div>
                    </div>
                    <div style={{ display: "flex", justifyContent: "flex-end" }}>
                      <button onClick={addMaligSite} style={{ padding: "6px 14px", background: "#c62828", color: "#fff", border: "none", borderRadius: 7, fontSize: "0.76rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>+ Add Site</button>
                    </div>
                  </div>

                  {customMaligCount > 0 && <div style={{ marginBottom: 12 }}>
                    <div style={{ fontSize: "0.7rem", fontWeight: 700, color: "#1565c0", marginBottom: 6 }}>Custom Additions ({customMaligCount})</div>
                    {Object.entries(customRepo.maligSites || {}).map(([site, obj]) => (
                      <div key={site} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "5px 8px", background: "#f8fafc", borderRadius: 6, border: "1px solid #e2e8f0", marginBottom: 3 }}>
                        <div>
                          <span style={{ fontWeight: 600, fontSize: "0.78rem", color: "#c62828" }}>{site}</span>
                          <span style={{ fontSize: "0.66rem", color: "#94a3b8", marginLeft: 6 }}>{obj.procedures.join(", ")}</span>
                        </div>
                        <button onClick={() => removeMaligSite(site)} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.7rem", fontWeight: 600 }}>✕</button>
                      </div>
                    ))}
                  </div>}

                  <details style={{ marginTop: 8 }}>
                    <summary style={{ fontSize: "0.72rem", fontWeight: 600, color: "#64748b", cursor: "pointer" }}>Browse All Malignancy Sites ({Object.keys(mergedMaligSites).length})</summary>
                    <div style={{ maxHeight: 300, overflow: "auto", marginTop: 6, border: "1px solid #e2e8f0", borderRadius: 8, padding: 6 }}>
                      {Object.entries(mergedMaligSites).map(([site, obj]) => (
                        <div key={site} style={{ fontSize: "0.7rem", color: "#475569", padding: "2px 0" }}>• <b>{site}</b> → <span style={{ color: "#94a3b8" }}>{obj.procedures.join(", ")}</span></div>
                      ))}
                    </div>
                  </details>
                </>}

                {/* ── ADD STANDALONE PROCEDURE ── */}
                {repoTab === "procedures" && <>
                  <div style={{ padding: 12, background: "#faf4ff", borderRadius: 8, border: "1px solid #ce93d8", marginBottom: 12 }}>
                    <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#6a1b9a", marginBottom: 8 }}>Add New Procedure</div>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr auto auto", gap: 8, alignItems: "end" }}>
                      <div>
                        <label style={lbl5}>Procedure Name *</label>
                        <input style={inp5} value={newProc} onChange={e => setNewProc(e.target.value)} placeholder="e.g. Robotic Cholecystectomy" onKeyDown={e => e.key === "Enter" && addProc()} />
                      </div>
                      <div>
                        <label style={lbl5}>Category *</label>
                        <select style={inp5} value={newProcCat} onChange={e => setNewProcCat(e.target.value)}>
                          {Object.entries(EXPANDED_BENIGN).map(([k, v]) => <option key={k} value={k}>{v.icon} {v.label}</option>)}
                        </select>
                      </div>
                      <button onClick={addProc} style={{ padding: "6px 14px", background: "#6a1b9a", color: "#fff", border: "none", borderRadius: 7, fontSize: "0.76rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif", whiteSpace: "nowrap", height: 34 }}>+ Add</button>
                    </div>
                  </div>

                  {customProcCount > 0 && <div style={{ marginBottom: 12 }}>
                    <div style={{ fontSize: "0.7rem", fontWeight: 700, color: "#1565c0", marginBottom: 6 }}>Custom Procedures ({customProcCount})</div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
                      {(customRepo.opProcs || []).map(proc => {
                        const cat = (customRepo.procCategories || {})[proc];
                        const catInfo = cat ? EXPANDED_BENIGN[cat] : null;
                        return <span key={proc} style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 8px", background: "#f3e5f5", borderRadius: 6, border: "1px solid #ce93d8", fontSize: "0.72rem", color: "#6a1b9a", fontWeight: 500 }}>
                          {proc}
                          {catInfo && <span style={{ fontSize: "0.58rem", padding: "1px 4px", borderRadius: 3, background: catInfo.color + "15", color: catInfo.color, fontWeight: 600 }}>{catInfo.icon} {catInfo.label}</span>}
                          <button onClick={() => removeProc(proc)} style={{ border: "none", background: "none", color: "#c62828", cursor: "pointer", fontSize: "0.68rem", fontWeight: 700, padding: 0 }}>✕</button>
                        </span>;
                      })}
                    </div>
                  </div>}

                  <details style={{ marginTop: 8 }}>
                    <summary style={{ fontSize: "0.72rem", fontWeight: 600, color: "#64748b", cursor: "pointer" }}>Browse All Procedures ({mergedOpProcs.length})</summary>
                    <div style={{ maxHeight: 300, overflow: "auto", marginTop: 6, border: "1px solid #e2e8f0", borderRadius: 8, padding: 6, display: "flex", flexWrap: "wrap", gap: 3 }}>
                      {mergedOpProcs.map(p => <span key={p} style={{ fontSize: "0.66rem", padding: "2px 6px", borderRadius: 4, background: (customRepo.opProcs || []).includes(p) ? "#e3f2fd" : "#f8fafc", border: "1px solid #e2e8f0", color: "#475569" }}>{p}</span>)}
                    </div>
                  </details>
                </>}
              </>;
            })()}

            {/* ─── RESEARCH PROTOCOLS TAB ─── */}
            {settingsTab === "research" && <>
              <div style={{ padding: 16, borderRadius: 12, background: "#f3e8ff", border: "1px solid #d8b4fe", marginBottom: 16 }}>
                <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#7c3aed", margin: "0 0 12px" }}>🔬 Create Research / Thesis Protocol</h3>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
                  <div><label style={{ display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#475569", marginBottom: 2, textTransform: "uppercase" }}>Protocol / Thesis Name *</label>
                    <input style={{ width: "100%", padding: "8px 12px", border: "1.5px solid #d8b4fe", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" }} value={newProtocol.name} onChange={e => setNewProtocol({ ...newProtocol, name: e.target.value })} placeholder="e.g. Laparoscopic vs Open Appendectomy RCT" />
                  </div>
                  <div><label style={{ display: "block", fontSize: "0.66rem", fontWeight: 600, color: "#475569", marginBottom: 2, textTransform: "uppercase" }}>Linked Investigator / Surgeon</label>
                    <SearchSelect clearable options={(config.surgeons || []).map(s => s.name)} value={newProtocol.linkedSurgeon} onChange={v => setNewProtocol({ ...newProtocol, linkedSurgeon: v || "" })} placeholder="Select surgeon..." />
                  </div>
                </div>
                <div style={{ display: "flex", justifyContent: "flex-end" }}>
                  <button onClick={() => {
                    if (!newProtocol.name.trim()) { show("Protocol name is required.", "error"); return; }
                    const protocols = [...(config.researchProtocols || []), { id: "rp" + Date.now(), name: newProtocol.name.trim(), linkedSurgeon: newProtocol.linkedSurgeon || "", createdAt: new Date().toISOString(), active: true }];
                    updateConfig(prev => ({ ...prev, researchProtocols: protocols }));
                    setNewProtocol({ name: "", linkedSurgeon: "" });
                    show("Protocol created!");
                  }} style={{ padding: "8px 18px", background: "linear-gradient(135deg,#7c3aed,#8b5cf6)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.8rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>+ Create Protocol</button>
                </div>
              </div>

              {/* Existing protocols */}
              {(config.researchProtocols || []).length === 0 ? (
                <div style={{ textAlign: "center", padding: 30, color: "#94a3b8", fontSize: "0.88rem" }}>No research protocols created yet.</div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {(config.researchProtocols || []).map((rp, i) => {
                    const enrolledCount = patients.filter(p => (p.researchProtocols || []).includes(rp.id)).length;
                    return <div key={rp.id} style={{ padding: "12px 16px", background: "#fff", borderRadius: 10, border: rp.active !== false ? "1.5px solid #d8b4fe" : "1px solid #e2e8f0", opacity: rp.active !== false ? 1 : 0.6 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <div>
                          <div style={{ fontWeight: 700, fontSize: "0.88rem", color: "#1e293b" }}>{"🔬"} {rp.name}</div>
                          <div style={{ fontSize: "0.72rem", color: "#64748b", marginTop: 2 }}>
                            {rp.linkedSurgeon && <span>PI: {rp.linkedSurgeon} · </span>}
                            <span style={{ color: "#7c3aed", fontWeight: 600 }}>{enrolledCount} patient{enrolledCount !== 1 ? "s" : ""} enrolled</span>
                            {rp.createdAt && <span> · Created {fmtDT(rp.createdAt)}</span>}
                          </div>
                        </div>
                        <div style={{ display: "flex", gap: 6 }}>
                          <button onClick={() => {
                            const protocols = (config.researchProtocols || []).map(x => x.id === rp.id ? { ...x, active: !x.active } : x);
                            updateConfig(prev => ({ ...prev, researchProtocols: protocols }));
                          }} style={{ padding: "4px 10px", borderRadius: 6, border: "1px solid #e2e8f0", background: rp.active !== false ? "#f0fdf4" : "#fff", fontSize: "0.68rem", fontWeight: 600, color: rp.active !== false ? "#2e7d32" : "#94a3b8", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{rp.active !== false ? "Active" : "Paused"}</button>
                          <button onClick={() => {
                            if (enrolledCount > 0) { setConfirm({ msg: `This protocol has ${enrolledCount} enrolled patients. Remove anyway?`, fn: () => { const protocols2 = (config.researchProtocols || []).filter(x => x.id !== rp.id); updateConfig(prev => ({ ...prev, researchProtocols: protocols2 })); show("Protocol removed."); setConfirm(null); } }); return; }
                            const protocols = (config.researchProtocols || []).filter(x => x.id !== rp.id);
                            updateConfig(prev => ({ ...prev, researchProtocols: protocols }));
                            show("Protocol removed.");
                          }} style={{ padding: "4px 8px", borderRadius: 6, border: "1px solid #fecaca", background: "#fff", fontSize: "0.68rem", color: "#c62828", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>✕</button>
                        </div>
                      </div>
                    </div>;
                  })}
                </div>
              )}
            </>}

            {/* ─── SYSTEM DIAGNOSTICS TAB ─── */}
            {settingsTab === "system" && <SystemDiagPanel show={show} />}

          </div>
        </div>}

        {/* ═══ MY PROFILE PAGE ═══ */}
        {page === "profile" && me && ["admin","resident","faculty"].includes(me.role) && <div className="st-content" style={S.content}>
          <div style={S.formC}>
            <h2 style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.25rem", color: "#0b1420", margin: "0 0 6px" }}>👤 My Profile</h2>
            <p style={{ fontSize: "0.76rem", color: "#94a3b8", margin: "0 0 20px" }}>{me.name} · {ROLE_LABELS[me.role]}{me.linkedSurgeon && me.linkStatus === "approved" ? ` · 🔗 ${(config.surgeons || []).find(s => s.id === me.linkedSurgeon)?.name || ""}` : ""}</p>

            {/* Photo */}
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 20, padding: 16, borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0" }}>
              <div style={{ width: 72, height: 72, borderRadius: "50%", background: me.photo ? "none" : "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "1.8rem", fontWeight: 700, color: "#94a3b8", overflow: "hidden", border: `3px solid ${ROLE_COLORS[me.role]?.b || "#e2e8f0"}`, flexShrink: 0 }}>
                {me.photo ? <img src={me.photo} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : me.name.charAt(0)}
              </div>
              <div>
                <label style={{ display: "inline-block", padding: "8px 16px", borderRadius: 8, border: "1.5px solid #90caf9", background: "#e3f2fd", color: "#1565c0", fontWeight: 600, fontSize: "0.78rem", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>
                  📷 {me.photo ? "Change Photo" : "Upload Photo"}
                  <input type="file" accept="image/*" style={{ display: "none" }} onChange={async (e) => {
                    const file = e.target.files?.[0]; if (!file) return;
                    if (file.size > 500000) { show("Image too large. Max 500KB.", "error"); return; }
                    const reader = new FileReader();
                    reader.onload = async (ev) => {
                      const photo = ev.target.result;
                      const up = users.map(u => u.id === me.id ? { ...u, photo } : u);
                      setUsers(up); await save(SK.USERS, up); setMe(prev => ({ ...prev, photo })); show("Photo updated.");
                    };
                    reader.readAsDataURL(file);
                  }} />
                </label>
                {me.photo && <button onClick={async () => {
                  const up = users.map(u => u.id === me.id ? { ...u, photo: null } : u);
                  setUsers(up); await save(SK.USERS, up); setMe(prev => ({ ...prev, photo: null })); show("Photo removed.");
                }} style={{ marginLeft: 8, border: "none", background: "none", color: "#c62828", fontSize: "0.76rem", cursor: "pointer", fontWeight: 600, fontFamily: "'Outfit',sans-serif" }}>Remove</button>}
              </div>
            </div>

            {/* Name */}
            <div style={{ marginBottom: 18 }}>
              <label style={S.label}>Display Name</label>
              <div style={{ display: "flex", gap: 8 }}>
                <input id="profName" style={{ ...S.input, flex: 1 }} defaultValue={me.name} />
                <button onClick={async () => {
                  const n = document.getElementById("profName")?.value?.trim();
                  if (!n) { show("Name required.", "error"); return; }
                  const up = users.map(u => u.id === me.id ? { ...u, name: n } : u);
                  setUsers(up); await save(SK.USERS, up); setMe(prev => ({ ...prev, name: n })); show("Name updated.");
                }} style={{ ...S.btnP, padding: "10px 18px" }}>Save</button>
              </div>
            </div>

            {/* Change PIN */}
            <div style={{ marginBottom: 18 }}>
              <label style={S.label}>Change PIN</label>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                <input id="profOldPin" type="password" style={{ ...S.input, flex: 1, minWidth: 120 }} placeholder="Current PIN" />
                <input id="profNewPin" type="password" style={{ ...S.input, flex: 1, minWidth: 120 }} placeholder="New PIN (4+)" />
                <button onClick={async () => {
                  const oldP = document.getElementById("profOldPin")?.value;
                  const newP = document.getElementById("profNewPin")?.value;
                  const current = users.find(u => u.id === me.id);
                  if (!oldP || oldP !== current?.pin) { show("Current PIN incorrect.", "error"); return; }
                  if (!newP || newP.length < 4) { show("New PIN must be 4+ digits.", "error"); return; }
                  const up = users.map(u => u.id === me.id ? { ...u, pin: newP } : u);
                  setUsers(up); await save(SK.USERS, up); setMe(prev => ({ ...prev, pin: newP })); show("PIN changed.");
                  document.getElementById("profOldPin").value = ""; document.getElementById("profNewPin").value = "";
                }} style={{ ...S.btnP, padding: "10px 16px" }}>Update PIN</button>
              </div>
            </div>

            {/* Surgeon Link */}
            <div style={{ padding: 16, borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0" }}>
              <h3 style={{ fontSize: "0.9rem", fontWeight: 700, color: "#1e293b", margin: "0 0 8px" }}>🔗 Surgeon Link</h3>
              {me.linkStatus === "approved" && me.linkedSurgeon ? (
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <Bdg bg="#e8f5e9" color="#2e7d32" border="#a5d6a7">✅ Linked</Bdg>
                  <span style={{ fontWeight: 600, fontSize: "0.9rem", color: "#1e293b" }}>{(config.surgeons || []).find(s => s.id === me.linkedSurgeon)?.name || "Unknown"}</span>
                </div>
              ) : me.linkStatus === "pending" ? (
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <Bdg bg="#fff3e0" color="#e65100" border="#ffcc80">⏳ Pending Approval</Bdg>
                  <span style={{ fontSize: "0.82rem", color: "#64748b" }}>Waiting for admin to approve your link request.</span>
                </div>
              ) : (
                <div>
                  <p style={{ fontSize: "0.78rem", color: "#64748b", margin: "0 0 10px" }}>Link your account to a surgeon in the registry to track your patients and view your statistics.</p>
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                    <select id="profLinkSurgeon" style={{ ...S.input, flex: 1, minWidth: 180 }}>
                      <option value="">Select surgeon...</option>
                      {(config.surgeons || []).filter(s => !users.find(u => u.linkedSurgeon === s.id && u.linkStatus === "approved")).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                    </select>
                    <button onClick={async () => {
                      const sid = document.getElementById("profLinkSurgeon")?.value;
                      if (!sid) { show("Select a surgeon.", "error"); return; }
                      const up = users.map(u => u.id === me.id ? { ...u, requestedSurgeon: sid, linkStatus: "pending" } : u);
                      setUsers(up); await save(SK.USERS, up); setMe(prev => ({ ...prev, requestedSurgeon: sid, linkStatus: "pending" }));
                      show("Link request sent. Awaiting admin approval.");
                    }} style={{ ...S.btnP, padding: "10px 18px" }}>Request Link</button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>}

        {/* ═══ MY PATIENTS PAGE ═══ */}
        {page === "mypatients" && me && ["admin","resident","faculty"].includes(me.role) && <div className="st-content" style={S.content}>
          <div style={S.formC}>
            <h2 style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.25rem", color: "#0b1420", margin: "0 0 14px" }}>📋 My Patients</h2>
            {(!me.linkedSurgeon || me.linkStatus !== "approved") ? (
              <div style={{ textAlign: "center", padding: "50px 10px", color: "#94a3b8" }}>
                <div style={{ fontSize: "2.5rem", marginBottom: 10 }}>🔗</div>
                <div style={{ fontSize: "1rem", fontWeight: 600, marginBottom: 6 }}>Link your profile first</div>
                <div style={{ fontSize: "0.82rem" }}>Go to <b>My Profile</b> to request a link to your surgeon entry in the registry.</div>
              </div>
            ) : (() => {
              const surgeonName = (config.surgeons || []).find(s => s.id === me.linkedSurgeon)?.name || "";
              const myPts = patients.filter(p => {
                const od = p.opDetails; if (!od) return false;
                const surg = od.operatingSurgeon === "__other" ? od.surgeonOther : od.operatingSurgeon;
                const asst = od.firstAssistant === "__other" ? od.assistantOther : od.firstAssistant;
                const asst2 = od.secondAssistant === "__other" ? od.secondAssistantOther : (od.secondAssistant || "");
                const asst3 = od.thirdAssistant === "__other" ? od.thirdAssistantOther : (od.thirdAssistant || "");
                const asst4 = od.fourthAssistant === "__other" ? od.fourthAssistantOther : (od.fourthAssistant || "");
                const asst5 = od.fifthAssistant === "__other" ? od.fifthAssistantOther : (od.fifthAssistant || "");
                return [surg, asst, asst2, asst3, asst4, asst5].some(f => f && f.toLowerCase().includes(surgeonName.toLowerCase()));
              }).sort((a, b) => (b.opDetails?.surgeryDateActual || "").localeCompare(a.opDetails?.surgeryDateActual || ""));

              const filtMyPts = myPts.filter(p => {
                if (myPtFilter !== "all" && p.status !== myPtFilter) return false;
                if (myPtSearch) {
                  const q = myPtSearch.toLowerCase();
                  return (p.name || "").toLowerCase().includes(q) || (p.opDetails?.primaryProcedure || "").toLowerCase().includes(q) || (p.diagnosis || "").toLowerCase().includes(q) || (p.malignancySite || "").toLowerCase().includes(q) || (p.clinical?.mrd || "").toLowerCase().includes(q);
                }
                return true;
              });

              const handleMyPtClick = (p) => {
                setViewPatient(p);
                if (p.status === "Discharged") { setPage("discharged"); }
                else { setPage("operated"); }
              };

              const opCount = myPts.filter(p => p.status === "Operated").length;
              const dcCount = myPts.filter(p => p.status === "Discharged").length;

              return <>
                <div style={{ marginBottom: 14, fontSize: "0.82rem", color: "#64748b", padding: "8px 12px", background: "#f8fafc", borderRadius: 8, border: "1px solid #e2e8f0", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
                  <span>Showing <b>{filtMyPts.length}</b> of <b>{myPts.length}</b> patients involving <b>{surgeonName}</b></span>
                  <div style={{ display: "flex", gap: 6 }}>
                    {[["all", `All (${myPts.length})`], ["Operated", `Operated (${opCount})`], ["Discharged", `Discharged (${dcCount})`]].map(([k, l]) => (
                      <button key={k} onClick={() => setMyPtFilter(k)} style={{ padding: "3px 10px", borderRadius: 6, border: myPtFilter === k ? "1.5px solid #1565c0" : "1px solid #e2e8f0", background: myPtFilter === k ? "#e3f2fd" : "#fff", fontSize: "0.68rem", fontWeight: 600, color: myPtFilter === k ? "#1565c0" : "#64748b", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{l}</button>
                    ))}
                  </div>
                </div>

                {/* Search */}
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, background: "#fff", borderRadius: 10, border: "1.5px solid #e2e8f0", padding: "6px 14px" }}>
                  <span style={{ color: "#94a3b8" }}>{"🔍"}</span>
                  <input style={{ border: "none", outline: "none", fontSize: "0.84rem", width: "100%", fontFamily: "'Outfit',sans-serif", background: "transparent" }} placeholder="Search by name, MRD, procedure, diagnosis..." value={myPtSearch} onChange={e => setMyPtSearch(e.target.value)} />
                  {myPtSearch && <button onClick={() => setMyPtSearch("")} style={{ border: "none", background: "none", color: "#94a3b8", cursor: "pointer", fontSize: "0.9rem" }}>✕</button>}
                </div>

                {filtMyPts.length === 0 ? <div style={{ textAlign: "center", padding: 40, color: "#94a3b8", fontSize: "0.88rem" }}>{myPtSearch ? "No patients match your search." : "No patients found."}</div> : (
                  <div style={{ background: "#fff", borderRadius: 12, border: "1px solid #e2e8f0", overflow: "auto" }}>
                    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.78rem" }}>
                      <thead><tr>
                        <th style={{ ...S.th, width: 28 }}>#</th>
                        <th style={S.th}>Patient</th>
                        <th style={S.th}>Diagnosis</th>
                        <th style={S.th}>Procedure</th>
                        <th style={S.th}>Role</th>
                        <th style={S.th}>Date</th>
                        <th style={S.th}>Access</th>
                        <th style={S.th}>Status</th>
                      </tr></thead>
                      <tbody>{filtMyPts.map((p, i) => {
                        const od = p.opDetails || {};
                        const surg = od.operatingSurgeon === "__other" ? od.surgeonOther : od.operatingSurgeon;
                        const myRole = surg && surg.toLowerCase().includes(surgeonName.toLowerCase()) ? "Surgeon" : "Assistant";
                        return (
                          <tr key={p.id} onClick={() => handleMyPtClick(p)} style={{ borderBottom: "1px solid #f1f5f9", cursor: "pointer", transition: "background 0.1s" }} onMouseEnter={e => e.currentTarget.style.background = "#f0fdf4"} onMouseLeave={e => e.currentTarget.style.background = ""}>
                            <td style={{ ...S.td, textAlign: "center", color: "#94a3b8", fontWeight: 600 }}>{i + 1}</td>
                            <td style={S.td}>
                              <div style={{ fontWeight: 600, fontSize: "0.82rem" }}>{p.name}</div>
                              <div style={{ color: "#94a3b8", fontSize: "0.7rem" }}>{p.age}y/{p.sex?.[0]} · {p.clinical?.mrd || "—"}</div>
                            </td>
                            <td style={{ ...S.td, maxWidth: 130 }}>{p.type === "malignancy" ? (p.malignancySite || "Malignancy") : (p.diagnosis || "—")}</td>
                            <td style={S.td}>
                              <div style={{ fontWeight: 600 }}>{od.primaryProcedure || p.plannedProcedure || "—"}</div>
                              {od.adjunctProcedure && <div style={{ fontSize: "0.7rem", color: "#64748b" }}>+ {od.adjunctProcedure}</div>}
                            </td>
                            <td style={S.td}><Bdg bg={myRole === "Surgeon" ? "#e8f5e9" : "#e3f2fd"} color={myRole === "Surgeon" ? "#2e7d32" : "#1565c0"} border={myRole === "Surgeon" ? "#a5d6a7" : "#90caf9"}>{myRole}</Bdg></td>
                            <td style={{ ...S.td, fontSize: "0.72rem" }}>{od.surgeryDateActual ? fmtD(od.surgeryDateActual) : "—"}</td>
                            <td style={S.td}><Bdg bg={od.opAccessMode?.includes("Lap") || od.opAccessMode?.includes("Minimal") ? "#e3f2fd" : "#fff3e0"} color={od.opAccessMode?.includes("Lap") || od.opAccessMode?.includes("Minimal") ? "#1565c0" : "#e65100"} border={od.opAccessMode?.includes("Lap") || od.opAccessMode?.includes("Minimal") ? "#90caf9" : "#ffcc80"}>{od.opAccessMode || "—"}</Bdg></td>
                            <td style={S.td}><Bdg bg={p.status === "Discharged" ? "#f3e5f5" : "#e8f5e9"} color={p.status === "Discharged" ? "#6a1b9a" : "#2e7d32"} border={p.status === "Discharged" ? "#ce93d8" : "#a5d6a7"}>{p.status}</Bdg></td>
                          </tr>
                        );
                      })}</tbody>
                    </table>
                  </div>
                )}
              </>;
            })()}
          </div>
        </div>}

        {/* ═══ MY STATS PAGE ═══ */}
        {page === "mystats" && me && ["admin","resident","faculty"].includes(me.role) && <div className="st-content" style={S.content}>
          <div style={S.formC}>
            <h2 style={{ fontFamily: "'Playfair Display',serif", fontSize: "1.25rem", color: "#0b1420", margin: "0 0 14px" }}>📊 My Stats</h2>
            {(!me.linkedSurgeon || me.linkStatus !== "approved") ? (
              <div style={{ textAlign: "center", padding: "50px 10px", color: "#94a3b8" }}>
                <div style={{ fontSize: "2.5rem", marginBottom: 10 }}>📊</div>
                <div style={{ fontSize: "1rem", fontWeight: 600, marginBottom: 6 }}>Link your profile to view stats</div>
                <div style={{ fontSize: "0.82rem" }}>Go to <b>My Profile</b> to request a link to your surgeon entry in the registry.</div>
              </div>
            ) : (() => {
              const surgeonName = (config.surgeons || []).find(s => s.id === me.linkedSurgeon)?.name || "";
              const myPts = patients.filter(p => {
                const od = p.opDetails; if (!od) return false;
                const surg = od.operatingSurgeon === "__other" ? od.surgeonOther : od.operatingSurgeon;
                const asst = od.firstAssistant === "__other" ? od.assistantOther : od.firstAssistant;
                const asst2 = od.secondAssistant === "__other" ? od.secondAssistantOther : (od.secondAssistant || "");
                const asst3 = od.thirdAssistant === "__other" ? od.thirdAssistantOther : (od.thirdAssistant || "");
                const asst4 = od.fourthAssistant === "__other" ? od.fourthAssistantOther : (od.fourthAssistant || "");
                const asst5 = od.fifthAssistant === "__other" ? od.fifthAssistantOther : (od.fifthAssistant || "");
                return [surg, asst, asst2, asst3, asst4, asst5].some(f => f && f.toLowerCase().includes(surgeonName.toLowerCase()));
              });
              const asSurgeon = myPts.filter(p => { const s = p.opDetails?.operatingSurgeon === "__other" ? p.opDetails.surgeonOther : p.opDetails?.operatingSurgeon; return s && s.toLowerCase().includes(surgeonName.toLowerCase()); });
              const asAssistant = myPts.filter(p => !asSurgeon.includes(p));
              const lapPts = myPts.filter(p => { const m = p.opDetails?.opAccessMode || ""; return m.includes("Lap") || m.includes("Minimal") || m.includes("VATS") || m.includes("Thoracoscop"); });
              const openPts = myPts.filter(p => { const m = p.opDetails?.opAccessMode || ""; return m.includes("Open") || m.includes("Conventional"); });
              const otherAccess = myPts.filter(p => !lapPts.includes(p) && !openPts.includes(p));
              const monthly = {}; myPts.forEach(p => { const d = p.opDetails?.surgeryDateActual; if (d) { const m = d.slice(0, 7); monthly[m] = (monthly[m] || 0) + 1; } });
              const monthKeys = Object.keys(monthly).sort();
              const procCount = {}; myPts.forEach(p => { const proc = p.opDetails?.primaryProcedure || "Other"; procCount[proc] = (procCount[proc] || 0) + 1; });
              const topProcs = Object.entries(procCount).sort((a, b) => b[1] - a[1]).slice(0, 10);
              const maxProc = topProcs.length > 0 ? topProcs[0][1] : 1;

              return <>
                {/* Summary Cards */}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(120px, 1fr))", gap: 12, marginBottom: 22 }}>
                  {[
                    { l: "Total", v: myPts.length, c: "#1565c0", bg: "#e3f2fd" },
                    { l: "As Surgeon", v: asSurgeon.length, c: "#2e7d32", bg: "#e8f5e9" },
                    { l: "As Assistant", v: asAssistant.length, c: "#e65100", bg: "#fff3e0" },
                    { l: "Laparoscopic", v: lapPts.length, c: "#6a1b9a", bg: "#f3e5f5" },
                  ].map((s, i) => <div key={i} style={{ padding: "16px 12px", borderRadius: 12, background: s.bg, textAlign: "center" }}>
                    <div style={{ fontSize: "1.8rem", fontWeight: 800, color: s.c }}>{s.v}</div>
                    <div style={{ fontSize: "0.7rem", fontWeight: 600, color: s.c, opacity: 0.8, textTransform: "uppercase" }}>{s.l}</div>
                  </div>)}
                </div>

                {/* Access Mode Breakdown */}
                <div style={{ marginBottom: 22, padding: 16, borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0" }}>
                  <h4 style={{ fontSize: "0.88rem", fontWeight: 700, color: "#1e293b", margin: "0 0 12px" }}>Access Mode Breakdown</h4>
                  {[
                    { l: "Laparoscopic / MIS", v: lapPts.length, c: "#1565c0" },
                    { l: "Open / Conventional", v: openPts.length, c: "#e65100" },
                    { l: "Other / Endoscopic", v: otherAccess.length, c: "#6a1b9a" },
                  ].map((s, i) => <div key={i} style={{ marginBottom: 8 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.78rem", color: "#475569", marginBottom: 3 }}>
                      <span>{s.l}</span><span style={{ fontWeight: 700 }}>{s.v} ({myPts.length > 0 ? Math.round(s.v / myPts.length * 100) : 0}%)</span>
                    </div>
                    <div style={{ height: 10, borderRadius: 5, background: "#e2e8f0", overflow: "hidden" }}>
                      <div style={{ width: `${myPts.length > 0 ? (s.v / myPts.length * 100) : 0}%`, height: "100%", borderRadius: 5, background: s.c, transition: "width 0.5s" }} />
                    </div>
                  </div>)}
                </div>

                {/* Monthly Trend */}
                {monthKeys.length > 0 && <div style={{ marginBottom: 22, padding: 16, borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0" }}>
                  <h4 style={{ fontSize: "0.88rem", fontWeight: 700, color: "#1e293b", margin: "0 0 12px" }}>📈 Monthly Trend</h4>
                  <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 120, padding: "0 4px" }}>
                    {monthKeys.slice(-12).map(m => {
                      const v = monthly[m]; const maxM = Math.max(...monthKeys.slice(-12).map(k => monthly[k]));
                      return <div key={m} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}>
                        <span style={{ fontSize: "0.65rem", fontWeight: 700, color: "#1565c0" }}>{v}</span>
                        <div style={{ width: "100%", maxWidth: 32, height: `${maxM > 0 ? (v / maxM * 80) : 0}px`, background: "linear-gradient(180deg,#1565c0,#42a5f5)", borderRadius: "5px 5px 0 0", minHeight: 4 }} />
                        <span style={{ fontSize: "0.55rem", color: "#94a3b8", writingMode: "vertical-rl", transform: "rotate(180deg)", height: 30 }}>{m.slice(2)}</span>
                      </div>;
                    })}
                  </div>
                </div>}

                {/* Top Procedures */}
                {topProcs.length > 0 && <div style={{ padding: 16, borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0" }}>
                  <h4 style={{ fontSize: "0.88rem", fontWeight: 700, color: "#1e293b", margin: "0 0 12px" }}>🔪 Top Procedures</h4>
                  {topProcs.map(([proc, count], i) => <div key={i} style={{ marginBottom: 8 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.76rem", color: "#475569", marginBottom: 3 }}>
                      <span style={{ maxWidth: "70%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{proc}</span><span style={{ fontWeight: 700 }}>{count}</span>
                    </div>
                    <div style={{ height: 8, borderRadius: 4, background: "#e2e8f0", overflow: "hidden" }}>
                      <div style={{ width: `${(count / maxProc) * 100}%`, height: "100%", borderRadius: 4, background: `hsl(${220 + i * 15}, 70%, 50%)`, transition: "width 0.5s" }} />
                    </div>
                  </div>)}
                </div>}
              </>;
            })()}
          </div>
        </div>}

        {/* ═══ ADMISSIONS PAGE ═══ */}
        {page === "admissions" && <div className="st-content" style={S.content}>
          {/* Assign Research Protocol Modal */}
          {assignProtocolModal && <div style={S.modOv}><div style={{ ...S.mod, maxWidth: 420 }}>
            <h3 style={{ margin: "0 0 4px", fontSize: "1rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif", color: "#7c3aed" }}>🔬 Assign Research Protocol</h3>
            <p style={{ margin: "0 0 14px", fontSize: "0.84rem", color: "#64748b" }}>Assign <strong>{assignProtocolModal.patient.name}</strong> to a research protocol</p>
            {(config.researchProtocols || []).filter(r => r.active !== false).length === 0 ? (
              <div style={{ padding: 16, textAlign: "center", color: "#94a3b8", fontSize: "0.84rem" }}>No active protocols. Create one in Settings → Research Protocols.</div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 300, overflowY: "auto" }}>
                {(config.researchProtocols || []).filter(r => r.active !== false).map(rp => {
                  const ptProts = assignProtocolModal.patient.researchProtocols || [];
                  const isAssigned = ptProts.includes(rp.id);
                  return <div key={rp.id} onClick={() => {
                    const p = assignProtocolModal.patient;
                    const current = p.researchProtocols || [];
                    const updated = isAssigned ? current.filter(x => x !== rp.id) : [...current, rp.id];
                    updatePatients(prev => prev.map(x => x.id === p.id ? { ...x, researchProtocols: updated } : x));
                    setAssignProtocolModal({ ...assignProtocolModal, patient: { ...p, researchProtocols: updated } });
                    show(isAssigned ? `Removed from ${rp.name}` : `Assigned to ${rp.name}`);
                  }} style={{ padding: "10px 14px", borderRadius: 8, border: isAssigned ? "2px solid #7c3aed" : "1.5px solid #e2e8f0", background: isAssigned ? "#f3e8ff" : "#fff", cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: "0.84rem", color: isAssigned ? "#7c3aed" : "#1e293b" }}>{rp.name}</div>
                      {rp.linkedSurgeon && <div style={{ fontSize: "0.68rem", color: "#64748b" }}>PI: {rp.linkedSurgeon}</div>}
                    </div>
                    <span style={{ fontSize: "0.82rem", color: isAssigned ? "#7c3aed" : "#cbd5e1" }}>{isAssigned ? "✓" : "○"}</span>
                  </div>;
                })}
              </div>
            )}
            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 14 }}>
              <button onClick={() => setAssignProtocolModal(null)} style={{ padding: "8px 18px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Done</button>
            </div>
          </div></div>}
          {/* Listing modal */}
          {listModal && <div style={S.modOv}><div style={S.mod}>
            <h3 style={{ margin: "0 0 4px", fontSize: "1rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif" }}>🔪 List for Surgery</h3>
            <p style={{ margin: "0 0 14px", fontSize: "0.84rem", color: "#64748b" }}>{listModal.batchIds ? `List ${listModal.batchIds.length} selected patients` : <>List <strong>{listModal.patient.name}</strong> for surgery</>}</p>
            {listModal.batchIds && <div style={{ marginBottom: 10, padding: "6px 10px", background: "#f3e5f5", borderRadius: 8, maxHeight: 100, overflowY: "auto" }}>
              {listModal.batchIds.map(id => { const pt = patients.find(p => p.id === id); return pt ? <div key={id} style={{ fontSize: "0.72rem", color: "#6a1b9a", padding: "2px 0" }}>{pt.name} — {pt.diagnosis || pt.malignancySite || ""}</div> : null; })}
            </div>}
            <label style={{ display: "block", fontSize: "0.72rem", fontWeight: 600, color: "#475569", marginBottom: 5, textTransform: "uppercase" }}>Surgery Date</label>
            <input style={{ display: "block", width: "100%", padding: "10px 13px", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.87rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box", WebkitAppearance: "none", MozAppearance: "none", appearance: "none", background: "#fff", minHeight: 44, lineHeight: "1.4" }} type="date" value={listModal.date || ""} onChange={e => setListModal({ ...listModal, date: e.target.value })} />
            {listModal.date && (() => {
              const d = new Date(listModal.date + "T00:00:00"); const dayOfWeek = d.getDay();
              const weekStart = new Date(d); weekStart.setDate(d.getDate() - dayOfWeek);
              const weekHols = (config.holidays || []).filter(h => { const hd = new Date(h.date + "T00:00:00"); return hd >= weekStart && hd < new Date(weekStart.getTime() + 7 * 86400000); });
              if (weekHols.length === 0) return null;
              return <div style={{ marginTop: 6, padding: "6px 10px", background: "#fff3e0", borderRadius: 6, border: "1px solid #ffe082" }}>
                <div style={{ fontSize: "0.72rem", fontWeight: 700, color: "#e65100" }}>⚠️ Holiday(s) this week:</div>
                {weekHols.map((h, i) => <div key={i} style={{ fontSize: "0.7rem", color: "#bf360c" }}>🎉 {fmtD(h.date)} — {h.name}</div>)}
              </div>;
            })()}
            <label style={{ display: "block", fontSize: "0.72rem", fontWeight: 600, color: "#475569", marginBottom: 3, marginTop: 10, textTransform: "uppercase" }}>Theater</label>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {(config.theaters || DEFAULT_CONFIG.theaters).map(t => (
                <button key={t} onClick={() => setListModal({ ...listModal, theater: t })}
                  style={{ flex: "1 1 auto", minWidth: 80, padding: "10px 14px", borderRadius: 8, border: listModal.theater === t ? "2px solid #6a1b9a" : "1.5px solid #e2e8f0", background: listModal.theater === t ? "#f3e5f5" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 600, fontSize: "0.84rem", color: listModal.theater === t ? "#6a1b9a" : "#94a3b8" }}>{t}</button>
              ))}
            </div>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
              <button onClick={() => setListModal(null)} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Cancel</button>
              <button onClick={doListForSurgery} style={{ padding: "10px 24px", background: "linear-gradient(135deg,#6a1b9a,#8e24aa)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.88rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>List for Surgery</button>
            </div>
          </div></div>}

          {/* Postpone modal */}
          {postponeModal && <div style={S.modOv}><div style={S.mod}>
            <h3 style={{ margin: "0 0 4px", fontSize: "1rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif" }}>⏳ Move to Pending</h3>
            <p style={{ margin: "0 0 14px", fontSize: "0.84rem", color: "#64748b" }}>Postpone <strong>{postponeModal.patient.name}</strong></p>
            <label style={{ display: "block", fontSize: "0.72rem", fontWeight: 600, color: "#475569", marginBottom: 3, textTransform: "uppercase" }}>Reason for Postponing *</label>
            <textarea style={{ width: "100%", padding: "10px 13px", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.87rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box", minHeight: 60, resize: "vertical" }} value={postponeModal.reason} onChange={e => setPostponeModal({ ...postponeModal, reason: e.target.value })} placeholder="Enter reason..." />
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
              <button onClick={() => setPostponeModal(null)} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Cancel</button>
              <button onClick={doPostpone} style={{ padding: "10px 24px", background: "linear-gradient(135deg,#e65100,#ff6d00)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.88rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Confirm Postpone</button>
            </div>
          </div></div>}

          {clinicalPt ? (
            <>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                <button onClick={() => setClinicalPt(null)} style={{ border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", padding: "5px 12px", cursor: "pointer", fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif" }}>← Back</button>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.1rem" }}>Clinical Details — {clinicalPt.name}</h2>
              </div>
              <ClinicalForm patient={clinicalPt} onSave={(cd, bu) => saveClinical(clinicalPt, cd, bu)} onCancel={() => setClinicalPt(null)} repo={{ allBenignDx: mergedAllBenignDx, maligSites: mergedMaligSites, benignCats: mergedBenignCats, customRepo }} />
            </>
          ) : (() => {
            const admitted = patients.filter(p => p.status === "Admitted").sort((a, b) => new Date(b.admittedAt || b.updatedAt) - new Date(a.admittedAt || a.updatedAt));
            const filteredAdm = admDateFilter ? admitted.filter(p => p.surgeryDate === admDateFilter) : admitted;
            const searchAdm = filteredAdm.filter(p => { const s = search.toLowerCase(); return !s || p.name.toLowerCase().includes(s) || p.phone.includes(s) || (p.diagnosis || "").toLowerCase().includes(s) || (p.malignancySite || "").toLowerCase().includes(s); });
            // Separate benign and malignant
            const benign = searchAdm.filter(p => p.type === "benign");
            const malignant = searchAdm.filter(p => p.type === "malignancy");

            const renderSection = (title, pts, color, icon) => {
              if (pts.length === 0) return null;
              const listablePts = pts.filter(p => p.clinical?.clinicalDone && p.clinical?.listStatus !== "Listed");
              const allSel = listablePts.length > 0 && listablePts.every(p => batchSelect.includes(p.id));
              const toggleAll = () => { if (allSel) setBatchSelect(prev => prev.filter(id => !listablePts.find(p => p.id === id))); else setBatchSelect(prev => [...new Set([...prev, ...listablePts.map(p => p.id)])]); };
              const toggleOne = (id) => setBatchSelect(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
              return (
                <div key={title} style={{ marginBottom: 18 }}>
                  <div style={{ padding: "8px 14px", background: color + "0a", borderRadius: "10px 10px 0 0", borderBottom: `2px solid ${color}22`, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <span style={{ fontWeight: 700, fontSize: "0.82rem", color }}>{icon} {title} ({pts.length})</span>
                    {perms.editAfterAdmit && listablePts.length > 0 && <label style={{ display: "flex", alignItems: "center", gap: 4, cursor: "pointer", fontSize: "0.68rem", color: "#6a1b9a", fontWeight: 600 }}><input type="checkbox" checked={allSel} onChange={toggleAll} style={{ accentColor: "#6a1b9a" }} /> Select All</label>}
                  </div>
                  <div style={{ background: "#fff", borderRadius: "0 0 10px 10px", border: "1px solid #e2e8f0", borderTop: "none", overflowX: "auto", WebkitOverflowScrolling: "touch" }}>
                    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.8rem", minWidth: 620 }}>
                      <thead><tr>
                        <th style={{ ...S.th, width: 28 }}>#</th>
                        {perms.editAfterAdmit && <th style={{ ...S.th, width: 28 }}></th>}
                        <th style={S.th}>Patient</th>
                        <th style={{ ...S.th, width: 80 }}>Admitted</th>
                        <th style={S.th}>Diagnosis</th>
                        <th style={S.th}>Procedure</th>
                        <th style={{ ...S.th, width: 60 }}>Details</th>
                        <th style={{ ...S.th, width: 160, textAlign: "right" }}>Actions</th>
                      </tr></thead>
                      <tbody>{pts.map((p, i) => {
                        const hasClinical = p.clinical?.clinicalDone;
                        const isListed = p.clinical?.listStatus === "Listed";
                        return (
                          <tr key={p.id} style={{ borderBottom: "1px solid #f1f5f9", background: isListed ? "#f3e5f508" : (batchSelect.includes(p.id) ? "#f3e5f510" : "#fff") }}>
                            <td style={{ ...S.td, textAlign: "center", color: "#94a3b8", fontWeight: 600 }}>{i + 1}</td>
                            {perms.editAfterAdmit && <td style={{ ...S.td, textAlign: "center", padding: "4px" }}>
                              {hasClinical && !isListed && <input type="checkbox" checked={batchSelect.includes(p.id)} onChange={() => toggleOne(p.id)} style={{ accentColor: "#6a1b9a", cursor: "pointer" }} />}
                            </td>}
                            <td style={S.td}>
                              <div style={{ fontWeight: 600, color: "#1e293b", fontSize: "0.84rem" }}>{p.name}{p.isEmergency && <span style={{ fontSize: "0.56rem", padding: "1px 5px", borderRadius: 4, background: "#fef2f2", color: "#c62828", fontWeight: 700, marginLeft: 5, verticalAlign: "middle" }}>🚨 EMG</span>}</div>
                              <div style={{ color: "#94a3b8", fontSize: "0.72rem" }}>{p.age ? p.age + "y/" : ""}{p.sex?.[0] || ""}{p.phone ? " · " + p.phone : ""}</div>
                              {(p.admissionHistory || []).length > 0 && <div style={{ display: "flex", gap: 3, flexWrap: "wrap", marginTop: 3 }}>
                                {p.admissionHistory.map((ah, ahi) => <span key={ahi} style={{ fontSize: "0.54rem", padding: "1px 5px", borderRadius: 3, background: "#e3f2fd", color: "#1565c0", fontWeight: 600 }}>Prev: {fmtDT(ah.admittedAt)}</span>)}
                              </div>}
                            </td>
                            <td style={{ ...S.td, fontSize: "0.72rem", color: "#64748b" }}>{p.admittedAt ? fmtDT(p.admittedAt) : "—"}</td>
                            <td style={{ ...S.td, maxWidth: 150 }}>{p.type === "malignancy" ? p.malignancySite : (p.diagnosis || "—")}</td>
                            <td style={{ ...S.td, maxWidth: 180 }}>
                              {p.type === "malignancy" && <span style={{ color: p.malignancyPlan === "Palliative" ? "#e65100" : "#2e7d32", fontWeight: 600, fontSize: "0.72rem" }}>{p.malignancyPlan} → </span>}
                              <span style={{ color: "#64748b" }}>{p.plannedProcedure || "—"}</span>
                            </td>
                            <td style={S.td}>
                              {hasClinical ? <Bdg bg="#e8f5e9" color="#2e7d32" border="#a5d6a7">Done</Bdg> : <Bdg bg="#fff3e0" color="#e65100" border="#ffcc80">Pending</Bdg>}
                              {isListed && <Bdg bg="#f3e5f5" color="#6a1b9a" border="#ce93d8">Listed</Bdg>}
                            </td>
                            <td style={{ ...S.td, textAlign: "right", whiteSpace: "nowrap" }}>
                              {perms.editAfterAdmit && <button onClick={() => setClinicalPt(patients.find(x => x.id === p.id))} title="Clinical Details" style={{ ...S.actBtn, color: "#1565c0", borderColor: "#90caf9" }}>📝</button>}
                              {p.isEmergency && perms.operate && <button onClick={() => { setOperativePt(patients.find(x => x.id === p.id)); setPage("listed"); }} title="Operate in EOT" style={{ ...S.actBtn, background: "#fef2f2", color: "#c62828", borderColor: "#ef9a9a", fontWeight: 700 }}>🚨</button>}
                              {(config.researchProtocols || []).filter(r => r.active !== false).length > 0 && <button onClick={() => setAssignProtocolModal({ patient: p })} title="Assign Research Protocol" style={{ ...S.actBtn, background: "#f3e8ff", color: "#7c3aed", borderColor: "#d8b4fe" }}>🔬</button>}
                              {perms.editAfterAdmit && hasClinical && !isListed && !p.isEmergency && <button onClick={() => setListModal({ patient: p, date: "", theater: "" })} title="List for Surgery" style={{ ...S.actBtn, background: "#f3e5f5", color: "#6a1b9a", borderColor: "#ce93d8" }}>🔪</button>}
                              {perms.admit && <button onClick={() => setPostponeModal({ patient: p, reason: "", from: "admission" })} title="Postpone" style={{ ...S.actBtn, color: "#e65100", borderColor: "#ffcc80" }}>⏳</button>}
                              {perms.admit && <button onClick={() => setDischargeModal({ patient: p, reason: "" })} title="Discharge" style={{ ...S.actBtn, color: "#2e7d32", borderColor: "#a5d6a7" }}>🏠</button>}
                              {perms.deletePatient && <button onClick={() => doCancelAdmission(p)} title="Cancel Admission (Admin PIN)" style={{ ...S.actBtn, color: "#c62828", borderColor: "#ef9a9a" }}>✕</button>}
                            </td>
                          </tr>
                        );
                      })}</tbody>
                    </table>
                  </div>
                </div>
              );
            };

            return <>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14, flexWrap: "wrap", gap: 8 }}>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.15rem" }}>🏥 Admissions</h2>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ fontSize: "0.82rem", color: "#64748b" }}>{searchAdm.length} patients</span>
                  {(() => {
                    const todayStr = fmt(new Date());
                    const todayAdmitted = patients.filter(p => p.admittedAt && fmt(new Date(p.admittedAt)) === todayStr);
                    const sendAdmissions = async () => {
                      if (todayAdmitted.length === 0) { show("No admissions recorded today.", "error"); return; }
                      const names = todayAdmitted.map((p, i) => `${i + 1}. ${p.name} (${p.diagnosis || p.malignancySite || ""})`).join(", ");
                      const body = `${todayAdmitted.length} admission${todayAdmitted.length > 1 ? "s" : ""} today — ${names}`;
                      await notify(`🏥 Admissions — ${fmtD(todayStr)}`, body.length > 200 ? body.slice(0, 197) + "…" : body, "admissions");
                      show("Admissions notification sent.");
                    };
                    return <button onClick={sendAdmissions} style={{ display: "flex", alignItems: "center", gap: 5, padding: "6px 12px", borderRadius: 8, border: "1.5px solid #1565c0", background: "#eff6ff", color: "#1565c0", fontWeight: 600, fontSize: "0.74rem", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>
                      🏥 Notify Admissions <span style={{ background: "#1565c0", color: "#fff", borderRadius: 10, fontSize: "0.65rem", padding: "1px 6px", fontWeight: 700 }}>{todayAdmitted.length}</span>
                    </button>;
                  })()}
                </div>
              </div>
              <div style={{ display: "flex", gap: 8, marginBottom: 16, flexWrap: "wrap" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "7px 12px", flex: 1, minWidth: 180 }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2"><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>
                  <input style={{ border: "none", outline: "none", fontSize: "0.84rem", width: "100%", fontFamily: "'Outfit',sans-serif", color: "#1e293b", background: "transparent" }} placeholder="Search..." value={search} onChange={e => setSearch(e.target.value)} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <input type="date" value={admDateFilter} onChange={e => setAdmDateFilter(e.target.value)} style={{ padding: "7px 12px", border: "1px solid #e2e8f0", borderRadius: 10, fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif", background: "#fff", cursor: "pointer" }} />
                  {admDateFilter && <button onClick={() => setAdmDateFilter("")} style={{ border: "1px solid #e2e8f0", borderRadius: 6, background: "#fff", padding: "5px 8px", cursor: "pointer", fontSize: "0.72rem", color: "#c62828", fontFamily: "'Outfit',sans-serif" }} title="Clear date filter">✕</button>}
                </div>
              </div>
              {searchAdm.length === 0 ? <div style={S.empty}>No admitted patients{search || admDateFilter ? " matching filters" : ""}.</div> : <>
                {batchSelect.length > 0 && <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "8px 14px", background: "linear-gradient(135deg,#f3e5f5,#ede7f6)", borderRadius: 10, border: "1.5px solid #ce93d8", marginBottom: 12 }}>
                  <span style={{ fontSize: "0.82rem", fontWeight: 700, color: "#6a1b9a" }}>{"🔪"} {batchSelect.length} patient{batchSelect.length > 1 ? "s" : ""} selected</span>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button onClick={() => setBatchSelect([])} style={{ padding: "6px 14px", background: "#fff", color: "#6a1b9a", border: "1.5px solid #ce93d8", borderRadius: 8, fontSize: "0.76rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Clear</button>
                    <button onClick={() => setListModal({ batchIds: batchSelect, date: "", theater: "" })} style={{ padding: "6px 16px", background: "linear-gradient(135deg,#6a1b9a,#8e24aa)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.76rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>List Selected</button>
                  </div>
                </div>}
                {renderSection("Malignancy", malignant, "#c62828", "🔴")}
                {renderSection("Benign", benign, "#2e7d32", "🟢")}
              </>}
            </>;
          })()}
        </div>}

        {/* ═══ LISTED PATIENTS PAGE ═══ */}
        {page === "listed" && <div className="st-content" style={S.content}>
          {/* Listing modal for re-list */}
          {listModal && <div style={S.modOv}><div style={S.mod}>
            <h3 style={{ margin: "0 0 4px", fontSize: "1rem", fontWeight: 700, fontFamily: "'Outfit',sans-serif" }}>📅 Re-list for Surgery</h3>
            <p style={{ margin: "0 0 14px", fontSize: "0.84rem", color: "#64748b" }}>Change date/theater for <strong>{listModal.patient.name}</strong></p>
            <label style={{ display: "block", fontSize: "0.72rem", fontWeight: 600, color: "#475569", marginBottom: 3, textTransform: "uppercase" }}>Surgery Date</label>
            <input style={{ width: "100%", padding: "10px 13px", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.87rem", fontFamily: "'Outfit',sans-serif", boxSizing: "border-box" }} type="date" value={listModal.date || ""} onChange={e => setListModal({ ...listModal, date: e.target.value })} />
            <label style={{ display: "block", fontSize: "0.72rem", fontWeight: 600, color: "#475569", marginBottom: 3, marginTop: 10, textTransform: "uppercase" }}>Theater</label>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {(config.theaters || DEFAULT_CONFIG.theaters).map(t => (
                <button key={t} onClick={() => setListModal({ ...listModal, theater: t })}
                  style={{ flex: "1 1 auto", minWidth: 80, padding: "10px 14px", borderRadius: 8, border: listModal.theater === t ? "2px solid #6a1b9a" : "1.5px solid #e2e8f0", background: listModal.theater === t ? "#f3e5f5" : "#fff", cursor: "pointer", fontFamily: "'Outfit',sans-serif", fontWeight: 600, fontSize: "0.84rem", color: listModal.theater === t ? "#6a1b9a" : "#94a3b8" }}>{t}</button>
              ))}
            </div>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 16 }}>
              <button onClick={() => setListModal(null)} style={{ padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Cancel</button>
              <button onClick={doListForSurgery} style={{ padding: "10px 24px", background: "linear-gradient(135deg,#6a1b9a,#8e24aa)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.88rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>Re-list</button>
            </div>
          </div></div>}

          {operativePt ? (
            <>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
                <button onClick={() => setOperativePt(null)} style={{ border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", padding: "5px 12px", cursor: "pointer", fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif" }}>← Back</button>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.1rem", flex: 1 }}>Operative Details — {operativePt.name}</h2>
                <button onClick={() => { setClinicalPt(patients.find(x => x.id === operativePt.id)); setOperativePt(null); setPage("admissions"); }} style={{ padding: "4px 10px", borderRadius: 6, border: "1px solid #90caf9", background: "#e3f2fd", fontSize: "0.7rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>📝 Modify Diagnosis</button>
              </div>
              <OperativeForm patient={operativePt} config={config} onSave={od => doConfirmOperation(operativePt, od)} onCancel={() => setOperativePt(null)} repo={{ opProcs: mergedOpProcs }} />
            </>
          ) : (() => {
            const rawListed = patients.filter(p => {
              // Show if currently listed
              if ((p.clinical?.listStatus === "Listed" || p.clinical?.listOutcome) && p.clinical?.surgeryListDate) return true;
              // Also show if has listing history (postponed/cancelled/relisted entries)
              if ((p.clinical?.listHistory || []).length > 0) return true;
              return false;
            });
            // Flatten: include current listing + history entries
            const allListed = [];
            rawListed.forEach(p => {
              // Current listing entry (only if it has a date)
              if (p.clinical?.surgeryListDate) {
                allListed.push(p);
              }
              // History entries
              const hist = p.clinical?.listHistory || [];
              hist.forEach((h, idx) => {
                allListed.push({ ...p, _historyEntry: true, _histIdx: idx, clinical: { ...p.clinical, surgeryListDate: h.surgeryListDate, theater: h.theater, listOutcome: h.listOutcome, listHistory: null } });
              });
            });
            allListed.sort((a, b) => (a.clinical?.surgeryListDate || "").localeCompare(b.clinical?.surgeryListDate || ""));
            // Get unique dates and find today or nearest next date
            const uniqueDates = [...new Set(allListed.filter(p => !p._historyEntry && !p.clinical?.listOutcome).map(p => p.clinical?.surgeryListDate).filter(Boolean))].sort();
            const todayStr = fmt(new Date());
            const defaultDate = listDateFilter || uniqueDates.find(d => d >= todayStr) || uniqueDates[uniqueDates.length - 1] || "";
            const effectiveFilter = defaultDate;
            const dateFiltered = effectiveFilter ? allListed.filter(p => p.clinical?.surgeryListDate === effectiveFilter) : allListed;
            const listed = dateFiltered.filter(p => { const s = search.toLowerCase(); return !s || p.name.toLowerCase().includes(s) || (p.diagnosis || "").toLowerCase().includes(s) || (p.malignancySite || "").toLowerCase().includes(s) || (p.plannedProcedure || "").toLowerCase().includes(s); });
            const byDate = {};
            listed.forEach(p => { const d = p.clinical?.surgeryListDate; if (!byDate[d]) byDate[d] = []; byDate[d].push(p); });
            const activeCount = listed.filter(p => !p.clinical?.listOutcome && !p._historyEntry).length;

            return <>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.15rem" }}>🔪 Listed for Surgery</h2>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ fontSize: "0.82rem", color: "#64748b" }}>{activeCount} active · {listed.length} total</span>
                  {(() => {
                    const listedForDate = effectiveFilter ? allListed.filter(p => p.clinical?.surgeryListDate === effectiveFilter && !p._historyEntry && !p.clinical?.listOutcome) : [];
                    const sendOTList = async () => {
                      if (listedForDate.length === 0) { show("No active patients for selected date.", "error"); return; }
                      const theaters = (config.theaters || ["GOT1", "GOT2"]);
                      const parts = theaters.map(t => {
                        const tPts = listedForDate.filter(p => p.clinical?.theater === t);
                        if (tPts.length === 0) return null;
                        return `${t}: ${tPts.map((p, i) => `${i + 1}. ${p.name} (${p.diagnosis || p.malignancySite || p.plannedProcedure || ""})`).join(", ")}`;
                      }).filter(Boolean);
                      const body = parts.join(" | ");
                      await notify(`📋 OT List — ${fmtD(effectiveFilter)}`, body.length > 200 ? body.slice(0, 197) + "…" : body, "ot-list");
                      show("OT list notification sent.");
                    };
                    return <button onClick={sendOTList} style={{ display: "flex", alignItems: "center", gap: 5, padding: "6px 12px", borderRadius: 8, border: "1.5px solid #c62828", background: "#fef2f2", color: "#c62828", fontWeight: 600, fontSize: "0.74rem", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>
                      📋 Notify OT List <span style={{ background: "#c62828", color: "#fff", borderRadius: 10, fontSize: "0.65rem", padding: "1px 6px", fontWeight: 700 }}>{listedForDate.length}</span>
                    </button>;
                  })()}
                </div>
              </div>
              <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "7px 12px", flex: 1, minWidth: 180 }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2"><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>
                  <input style={{ border: "none", outline: "none", fontSize: "0.84rem", width: "100%", fontFamily: "'Outfit',sans-serif", background: "transparent" }} placeholder="Search by name..." value={search} onChange={e => setSearch(e.target.value)} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <input type="date" value={listDateFilter || effectiveFilter} onChange={e => setListDateFilter(e.target.value)} style={{ padding: "7px 12px", border: "1.5px solid #6a1b9a", borderRadius: 10, fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif", background: "#faf4ff", cursor: "pointer", color: "#6a1b9a", fontWeight: 600 }} />
                  {listDateFilter && <button onClick={() => setListDateFilter("")} style={{ border: "1px solid #e2e8f0", borderRadius: 6, background: "#fff", padding: "5px 8px", cursor: "pointer", fontSize: "0.72rem", color: "#c62828", fontFamily: "'Outfit',sans-serif" }} title="Reset to nearest date">✕</button>}
                </div>
              </div>
              {effectiveFilter && <div style={{ marginBottom: 10, fontSize: "0.76rem", color: "#64748b" }}>Showing list for <b style={{ color: "#6a1b9a" }}>{fmtD(effectiveFilter)}</b>{effectiveFilter === todayStr && <span style={{ color: "#2e7d32", fontWeight: 600 }}> (Today)</span>}. Use date picker to view other dates.</div>}
              {listed.length === 0 ? <div style={S.empty}>No patients listed for surgery yet. List patients from the Admissions page after completing clinical details.</div> : (
                Object.entries(byDate).sort(([a], [b]) => a.localeCompare(b)).map(([date, pts]) => (
                  <div key={date} style={{ marginBottom: 20 }}>
                    <div style={{ padding: "10px 14px", background: "#f3e5f508", borderRadius: "10px 10px 0 0", borderBottom: "2px solid #6a1b9a22", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <span style={{ fontWeight: 700, fontSize: "0.92rem", color: "#6a1b9a" }}>📅 {fmtD(date)}</span>
                      <span style={{ fontSize: "0.76rem", color: "#94a3b8" }}>{pts.length} case{pts.length > 1 ? "s" : ""}</span>
                    </div>
                    {(config.theaters || DEFAULT_CONFIG.theaters).map(theater => {
                      const tPts = pts.filter(p => p.clinical?.theater === theater);
                      if (tPts.length === 0) return null;
                      const activePts = tPts.filter(p => !p.clinical?.listOutcome);
                      return (
                        <div key={theater}>
                          <div style={{ padding: "5px 14px", background: "#f8fafc", borderLeft: "3px solid #6a1b9a", fontSize: "0.76rem", fontWeight: 700, color: "#475569", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                            <span>{theater} ({tPts.length})</span>
                            <button onClick={() => generatePrintList(date, theater, activePts.length > 0 ? activePts : tPts)} style={{ border: "1px solid #ce93d8", borderRadius: 6, background: "#f3e5f5", padding: "3px 10px", cursor: "pointer", fontSize: "0.68rem", fontFamily: "'Outfit',sans-serif", color: "#6a1b9a", fontWeight: 600 }}>🖨️ Print List</button>
                          </div>
                          <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderTop: "none", overflow: "auto" }}>
                            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.8rem" }}>
                              <thead><tr>
                                <th style={{ ...S.th, width: 28 }}>#</th>
                                <th style={S.th}>Patient</th>
                                <th style={S.th}>Diagnosis</th>
                                <th style={S.th}>Procedure</th>
                                <th style={{ ...S.th, width: 56 }}>PAC</th>
                                <th style={{ ...S.th, width: 75 }}>Status</th>
                                <th style={{ ...S.th, width: 140, textAlign: "right" }}>Actions</th>
                              </tr></thead>
                              <tbody>{tPts.map((p, i) => {
                                const pac = p.clinical?.pacStatus || "";
                                const outcome = p.clinical?.listOutcome || "";
                                const isActive = !outcome && !p._historyEntry;
                                const isHist = p._historyEntry;
                                return (
                                  <tr key={isHist ? p.id + '-h' + p._histIdx : p.id} style={{ borderBottom: "1px solid #f1f5f9", opacity: isActive ? 1 : 0.6, background: isActive ? "#fff" : "#fafafa" }}>
                                    <td style={{ ...S.td, textAlign: "center", color: "#94a3b8", fontWeight: 600 }}>{i + 1}</td>
                                    <td style={S.td}>
                                      <div style={{ fontWeight: 600, color: "#1e293b", fontSize: "0.84rem" }}>{p.name}</div>
                                      <div style={{ color: "#94a3b8", fontSize: "0.72rem" }}>{p.age}y/{p.sex?.[0]}</div>
                                    </td>
                                    <td style={{ ...S.td, maxWidth: 140 }}>{p.type === "malignancy" ? (p.malignancySite || "Malignancy") : (p.diagnosis || "—")}</td>
                                    <td style={{ ...S.td, maxWidth: 140, color: "#64748b" }}>{p.plannedProcedure || "—"}</td>
                                    <td style={{ ...S.td, textAlign: "center" }}>
                                      {isActive && !isHist ? <select value={pac} onChange={e => doUpdatePAC(p, e.target.value)} style={{ border: `1.5px solid ${pac === "OK" ? "#4caf50" : pac === "Review" ? "#ff9800" : "#e2e8f0"}`, borderRadius: 6, padding: "2px 4px", fontSize: "0.68rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", background: pac === "OK" ? "#e8f5e9" : pac === "Review" ? "#fff3e0" : "#fff", color: pac === "OK" ? "#2e7d32" : pac === "Review" ? "#e65100" : "#94a3b8", cursor: "pointer" }}>
                                        <option value="">—</option><option value="OK">OK</option><option value="Review">Review</option>
                                      </select> : <span style={{ fontSize: "0.68rem", color: pac === "OK" ? "#2e7d32" : "#e65100" }}>{pac || "—"}</span>}
                                    </td>
                                    <td style={{ ...S.td, textAlign: "center" }}>
                                      {outcome === "Operated" && <Bdg bg="#e8f5e9" color="#2e7d32" border="#a5d6a7">Operated</Bdg>}
                                      {outcome === "Relisted" && <Bdg bg="#ede7f6" color="#6a1b9a" border="#ce93d8">Relisted</Bdg>}
                                      {outcome === "Cancelled" && <Bdg bg="#fce4ec" color="#c62828" border="#ef9a9a">Cancelled</Bdg>}
                                      {outcome === "Deleted" && <Bdg bg="#f5f5f5" color="#757575" border="#bdbdbd">Deleted</Bdg>}
                                      {outcome === "Postponed" && <Bdg bg="#fff3e0" color="#e65100" border="#ffcc80">Postponed</Bdg>}
                                      {outcome === "Delisted" && <Bdg bg="#f5f5f5" color="#757575" border="#bdbdbd">Delisted</Bdg>}
                                      {isActive && <Bdg bg="#e3f2fd" color="#1565c0" border="#90caf9">Active</Bdg>}
                                    </td>
                                    <td style={{ ...S.td, textAlign: "right", whiteSpace: "nowrap" }}>
                                      {isActive && !isHist && perms.operate && <>
                                        <button onClick={() => setOperativePt(patients.find(x => x.id === p.id))} title="Operate" style={{ ...S.actBtn, background: "#e8f5e9", color: "#2e7d32", borderColor: "#a5d6a7", fontWeight: 700 }}>🔪</button>
                                        <button onClick={() => setListModal({ patient: p, date: p.clinical?.surgeryListDate || "", theater: p.clinical?.theater || "" })} title="Relist" style={{ ...S.actBtn, color: "#6a1b9a", borderColor: "#ce93d8" }}>📅</button>
                                        <button onClick={() => setConfirm({ msg: `Cancel surgery listing for ${p.name}?`, fn: () => { updatePatients(prev => prev.map(x => { if (x.id !== p.id) return x; const cl = x.clinical || {}; return { ...x, clinical: { ...cl, listOutcome: "Cancelled", listStatus: null } }; })); show(`${p.name} listing cancelled.`); setConfirm(null); } })} title="Cancel Listing" style={{ ...S.actBtn, color: "#c62828", borderColor: "#ef9a9a" }}>✕</button>
                                      </>}
                                      {perms.deletePatient && !isHist && !outcome && <button onClick={() => doRemoveFromList(p)} title="Remove from List (Admin)" style={{ ...S.actBtn, color: "#c62828", borderColor: "#ef9a9a" }}>🗑</button>}
                                    </td>
                                  </tr>
                                );
                              })}</tbody>
                            </table>
                          </div>
                        </div>
                      );
                    })}
                    {(() => {
                      const theaters = config.theaters || DEFAULT_CONFIG.theaters;
                      const unassigned = pts.filter(p => !theaters.includes(p.clinical?.theater));
                      if (unassigned.length === 0) return null;
                      return <div>
                        <div style={{ padding: "5px 14px", background: "#fef2f2", borderLeft: "3px solid #ef9a9a", fontSize: "0.76rem", fontWeight: 700, color: "#c62828" }}>Unassigned ({unassigned.length})</div>
                        <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderTop: "none", overflow: "auto" }}>
                          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.8rem" }}>
                            <tbody>{unassigned.map((p, i) => {
                              const outcome = p.clinical?.listOutcome || "";
                              const isActive = !outcome;
                              return (
                                <tr key={p.id} style={{ borderBottom: "1px solid #f1f5f9", opacity: isActive ? 1 : 0.6 }}>
                                  <td style={{ ...S.td, width: 28, textAlign: "center", color: "#94a3b8", fontWeight: 600 }}>{i + 1}</td>
                                  <td style={S.td}><div style={{ fontWeight: 600, fontSize: "0.84rem" }}>{p.name}</div><div style={{ color: "#94a3b8", fontSize: "0.72rem" }}>{p.age}y/{p.sex?.[0]}</div></td>
                                  <td style={{ ...S.td, maxWidth: 140 }}>{p.type === "malignancy" ? (p.malignancySite || "Malignancy") : (p.diagnosis || "—")}</td>
                                  <td style={S.td}>{outcome ? <Bdg bg={outcome === "Operated" ? "#e8f5e9" : "#fff3e0"} color={outcome === "Operated" ? "#2e7d32" : "#e65100"} border={outcome === "Operated" ? "#a5d6a7" : "#ffcc80"}>{outcome}</Bdg> : <Bdg bg="#e3f2fd" color="#1565c0" border="#90caf9">Active</Bdg>}</td>
                                  <td style={{ ...S.td, textAlign: "right" }}>{perms.deletePatient && !outcome && <button onClick={() => doRemoveFromList(p)} title="Remove from List" style={{ ...S.actBtn, color: "#c62828", borderColor: "#ef9a9a" }}>🗑</button>}</td>
                                </tr>
                              );
                            })}</tbody>
                          </table>
                        </div>
                      </div>;
                    })()}
                  </div>
                ))
              )}
            </>;
          })()}
        </div>}

        {/* ═══ OPERATED PATIENTS PAGE ═══ */}
        {page === "operated" && <div className="st-content" style={S.content}>
          {viewPatient ? (() => {
            const p = viewPatient; const cl = p.clinical || {}; const po = cl.preOp || {}; const od = p.opDetails || {};
            const lbl2 = { fontSize: "0.64rem", fontWeight: 600, color: "#94a3b8", textTransform: "uppercase", letterSpacing: "0.04em" };
            const val2 = { fontSize: "0.84rem", color: "#1e293b", fontWeight: 500 };
            const row = (l, v) => v ? <div style={{ marginBottom: 6 }}><div style={lbl2}>{l}</div><div style={val2}>{v}</div></div> : null;
            const sec2 = (title, icon, color, children) => <div style={{ marginBottom: 12, border: "1px solid #e2e8f0", borderRadius: 10, overflow: "hidden" }}><div style={{ padding: "8px 14px", background: color + "08", fontWeight: 700, fontSize: "0.82rem", color, borderBottom: "1px solid #e2e8f0" }}>{icon} {title}</div><div style={{ padding: "12px 14px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 16px" }}>{children}</div></div>;
            return <>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
                <button onClick={() => setViewPatient(null)} style={{ border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", padding: "5px 12px", cursor: "pointer", fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif" }}>← Back</button>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.1rem", flex: 1 }}>Patient Record — {p.name}</h2>
                {me.role === "admin" && <div style={{ display: "flex", gap: 4 }}>
                  <button onClick={() => { setClinicalPt(patients.find(x => x.id === p.id)); setViewPatient(null); setPage("admissions"); }} style={{ padding: "4px 10px", borderRadius: 6, border: "1px solid #90caf9", background: "#e3f2fd", fontSize: "0.68rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"📝"} Edit Clinical</button>
                  <button onClick={() => { setOperativePt(patients.find(x => x.id === p.id)); setViewPatient(null); setPage("listed"); }} style={{ padding: "4px 10px", borderRadius: 6, border: "1px solid #a5d6a7", background: "#e8f5e9", fontSize: "0.68rem", fontWeight: 600, color: "#2e7d32", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"🔪"} Edit Operative</button>
                </div>}
              </div>
              <div style={{ maxWidth: 740, margin: "0 auto" }}>
                {sec2("Patient Particulars", "👤", "#2e7d32", <>
                  {row("Name", p.name)} {row("Age / Sex", `${p.age}y / ${p.sex}`)} {row("Phone", p.phone)} {row("MRD", cl.mrd)}
                  {row("Blood Group", cl.bloodGroup)} {row("State / District", [cl.state, cl.district].filter(Boolean).join(", "))}
                  {row("Occupation", cl.occupation === "Other" ? cl.occupationOther || "Other" : cl.occupation)} {row("Height / Weight / BMI", [cl.height && cl.height + "cm", cl.weight && cl.weight + "kg", cl.height && cl.weight && (parseFloat(cl.weight) / ((parseFloat(cl.height) / 100) ** 2)).toFixed(1)].filter(Boolean).join(" / "))}
                  {row("Comorbidities", [...(cl.comorbidities || []), cl.comorbidOther].filter(Boolean).join(", "))}
                  {row("PAC Cleared", cl.pacClearedDate ? fmtD(cl.pacClearedDate) : (cl.pacStatus === "Cleared" ? "Yes" : ""))}
                  {row("Date of Admission", p.admittedAt ? fmtDT(p.admittedAt) : "")}
                  {(p.admissionHistory || []).length > 0 && row("Previous Admissions", p.admissionHistory.map(ah => fmtDT(ah.admittedAt)).join(", "))}
                </>)}
                {sec2("Clinical Details", "📝", "#c62828", <>
                  {row("Chief Complaints", (cl.chiefComplaints || []).filter(Boolean).join(", "))}
                  {row("Past History", (cl.pastHistory || []).filter(Boolean).join(", "))}
                  {row("Previous Surgeries", (cl.prevSurgeries || []).filter(Boolean).join(", "))}
                  {row("Vitals", [cl.pulse && `P: ${cl.pulse}`, cl.bp && `BP: ${cl.bp}`, cl.spo2 && `SpO2: ${cl.spo2}`].filter(Boolean).join(" · "))}
                  {row("Pallor / Icterus", `${cl.pallor || "—"} / ${cl.icterus || "—"}`)}
                  {row("Abdominal Findings", cl.abdominalFindings)} {row("DRE", cl.dre)}
                  {row("Other Examinations", Array.isArray(cl.otherExam) ? cl.otherExam.filter(Boolean).join("; ") : cl.otherExam)}
                </>)}
                {/* Imaging, Endoscopy, Pathology summary */}
                {[...IMAGING_KEYS, ...ENDO_KEYS, ...PATHO_KEYS].some(k => { const img = cl[k]; return typeof img === "object" ? img?.done : !!img; }) && sec2("Imaging + Endoscopy", "📷", "#00695c", <>
                  {IMAGING_KEYS.map(k => {
                    const img = cl[k]; if (!img) return null;
                    const obj = typeof img === "object" ? img : { done: true, findings: img, date: "", region: "" };
                    if (!obj.done && !obj.findings) return null;
                    return <div key={k}>{row(IMAGING_LABELS[k], [obj.region && `[${obj.region}]`, obj.date && fmtD(obj.date), obj.findings].filter(Boolean).join(" — ") || "Done")}</div>;
                  })}
                  {ENDO_KEYS.map(k => {
                    const img = cl[k]; if (!img) return null;
                    const obj = typeof img === "object" ? img : { done: true, findings: img, date: "" };
                    if (!obj.done && !obj.findings) return null;
                    return <div key={k}>{row(ENDO_LABELS[k], [obj.date && fmtD(obj.date), obj.findings].filter(Boolean).join(" — ") || "Done")}</div>;
                  })}
                  {PATHO_KEYS.map(k => {
                    const img = cl[k]; if (!img) return null;
                    const obj = typeof img === "object" ? img : { done: true, findings: img, date: "", site: "" };
                    if (!obj.done && !obj.findings) return null;
                    return <div key={k}>{row(PATHO_LABELS[k], [obj.site && `[${obj.site}]`, obj.date && fmtD(obj.date), obj.findings].filter(Boolean).join(" — ") || "Done")}</div>;
                  })}
                </>)}
                {sec2("Pre-Op Diagnosis", "🩺", "#0d47a1", <>
                  {row("Type", po.lesionType === "malignancy" ? "Malignant" : "Benign")}
                  {po.lesionType === "malignancy" ? <>
                    {row("Site", po.malSite)} {row("Histology", po.preOpHistology)} {row("IHC", po.ihc)}
                    {row("TNM", [po.clinicalT, po.clinicalN, po.clinicalM].filter(Boolean).join(" "))}
                    {row("Plan", po.plan)}
                  </> : <>
                    {row("Primary Dx", [po.primaryDx, po.primaryLaterality && `(${po.primaryLaterality})`, po.primarySite].filter(Boolean).join(" "))}
                    {row("Subtype / ASH", [po.primarySubtype, po.ashClass].filter(Boolean).join(" · "))}
                  </>}
                  {row("Secondary Dx", [po.secondaryDx, po.secondaryLaterality && `(${po.secondaryLaterality})`].filter(Boolean).join(" "))}
                  {row("Planned Procedure", po.procedure)} {row("Access", po.accessMode === "Others" ? po.accessOther : po.accessMode)}
                </>)}
                {od.primaryProcedure && sec2("Operative Details", "🔪", "#6a1b9a", <>
                  {row("Surgery Date", od.surgeryDateActual ? fmtD(od.surgeryDateActual) : "")}
                  {row("Duration", od.startTime && od.endTime ? (() => { const [sh,sm]=od.startTime.split(":").map(Number); const [eh,em]=od.endTime.split(":").map(Number); let m=(eh*60+em)-(sh*60+sm); if(m<0)m+=1440; const h=Math.floor(m/60); return h>0?`${h}h ${m%60}m`:`${m}m`; })() : "")}
                  {row("Anaesthesia", od.anaesthesia === "Other" ? od.anaesthesiaOther : od.anaesthesia)}
                  {row("Anaesthetist", od.anaesthetist)}
                  {row("Position", od.patientPosition === "Other" ? od.patientPositionOther : od.patientPosition)}
                  {row("Surgeon", od.operatingSurgeon === "__other" ? od.surgeonOther : od.operatingSurgeon)}
                  {row("1st Assistant", od.firstAssistant === "__other" ? od.assistantOther : od.firstAssistant)}
                  {row("2nd Assistant", od.secondAssistant === "__other" ? od.secondAssistantOther : od.secondAssistant)}
                  {row("3rd Assistant", od.thirdAssistant === "__other" ? od.thirdAssistantOther : od.thirdAssistant)}
                  {row("4th Assistant", od.fourthAssistant === "__other" ? od.fourthAssistantOther : od.fourthAssistant)}
                  {row("5th Assistant", od.fifthAssistant === "__other" ? od.fifthAssistantOther : od.fifthAssistant)}
                  {row("Access", od.opAccessMode === "Other" ? od.opAccessOther : od.opAccessMode)}
                  {row("Primary Procedure", od.primaryProcedure)} {row("Adjunct", od.adjunctProcedure)} {row("Secondary", od.secondaryProcedure)}
                  {row("Intra-Op Findings", (od.intraFindings || []).filter(Boolean).join("; "))}
                  {row("Specimen", od.specimenSent !== "No" && od.specimenSent ? [od.specimenSent, od.specimenDetails].filter(Boolean).join(" — ") : "")}
                  {row("Blood Loss", od.bloodLoss && `${od.bloodLoss} ml`)} {row("PRBC", od.prbcTransfusion !== "0" && od.prbcTransfusion)} {row("FFP", od.ffpUnits !== "0" && od.ffpUnits)}
                  {row("Complications", [od.complication1 === "Other" ? od.complication1Other : od.complication1, od.complication2 === "Other" ? od.complication2Other : od.complication2].filter(v => v && v !== "None").join(", ") || "None")}
                  {row("Drains", od.drains === "Yes" && od.drainList?.length ? od.drainList.map((d, i) => `${i+1}. ${[d.type, d.site].filter(Boolean).join(" — ")}`).join("; ") : (od.drains !== "No" && od.drains !== "0" && od.drains ? [od.drains, od.drainType, od.drainSite].filter(Boolean).join(" — ") : ""))} {row("Stoma", od.stoma && [od.stoma, od.stomaSite].filter(Boolean).join(" — "))}
                  {row("Ryles Tube", od.rylesTube)} {row("Foley's", od.foleysCatheter)}
                  {row("Thoracostomy", od.thoracostomy !== "None" && od.thoracostomy)} {row("Epidural", od.epidural)} {row("Extubation", od.extubation)}
                  {row("Closure", od.abdominalClosure)} {row("Shifted To", od.shiftedTo)}
                  {od.operativeNote && row("Operative Note", od.operativeNote)}
                  {row("Other Info", od.otherInfo)}
                </>)}

                {/* ─── DAILY PROGRESS NOTES ─── */}
                {p.status === "Operated" && (me.role === "admin" || me.role === "resident") && <DailyProgressSection patient={p} onSave={notes => saveDailyNotes(p, notes)} />}
                {p.status === "Operated" && me.role === "faculty" && p.dailyNotes && p.dailyNotes.length > 0 && sec2("Daily Progress Notes", "📝", "#1565c0", <>
                  {p.dailyNotes.map((n, i) => <div key={i} style={{ gridColumn: "1/-1" }}>{row(n.date ? fmtD(n.date) + (n.pod ? ` (POD ${n.pod})` : "") : `Note ${i+1}`, n.note)}</div>)}
                </>)}

                {/* ─── POST-OP COURSE (Admin & Resident only) ─── */}
                {p.status === "Operated" && (me.role === "admin" || me.role === "resident") && <PostOpForm patient={p} onSave={ppData => savePostOpProgress(p, ppData)} onDischarge={ppData => { savePostOpProgress(p, ppData); doDischarge(p); }} repo={{ allBenignDx: mergedAllBenignDx, maligSites: mergedMaligSites }} />}
                {p.status === "Operated" && me.role === "faculty" && p.postOp && sec2("Post-Operative Course (View Only)", "📋", "#e65100", <>
                  {row("Complications", (p.postOp.complications || []).filter(c => c && c !== "None").join(", ") || "None")}
                  {row("Wound Condition", p.postOp.woundCondition)}
                  {row("HPE Report", p.postOp.hpeReport)}
                  {row("Follow-Up Date", p.postOp.followUpDate)}
                  {row("Follow-Up Instructions", p.postOp.followUpInstructions)}
                </>)}

                {/* Show saved post-op data for discharged patients */}
                {p.status === "Discharged" && p.postOp && sec2("Post-Operative Course", "📋", "#e65100", <>
                  {row("Complications", (p.postOp.complications || []).filter(c => c && c !== "None").join(", ") || "None")}
                  {(p.postOp.drainRemoval || []).length > 0 && row("Drains", p.postOp.drainRemoval.map(r => { const dr = (p.opDetails?.drainList || [])[r.drainIdx]; return `${dr ? [dr.type, dr.site].filter(Boolean).join(" ") : `Drain ${r.drainIdx+1}`}: ${r.pod || "—"}`; }).join("; "))}
                  {!p.postOp.drainRemoval?.length && p.postOp.drainRemovalDay && row("Drain Removed", `POD ${p.postOp.drainRemovalDay}`)}
                  {row("RT Removal", p.postOp.rylesRemoval || (p.postOp.rylesRemovalDay && `POD ${p.postOp.rylesRemovalDay}`))}
                  {row("Catheter Removal", p.postOp.catheterRemoval || (p.postOp.catheterRemovalDay && `POD ${p.postOp.catheterRemovalDay}`))}
                  {row("Flatus / Bowels / Orals", [p.postOp.flatusDay && `Flatus ${p.postOp.flatusDay}`, p.postOp.bowelsDay && `Bowels ${p.postOp.bowelsDay}`, p.postOp.oralsDay && `Orals ${p.postOp.oralsDay}`].filter(Boolean).join(" · ") || "—")}
                  {row("Ambulation", p.postOp.ambulationDay)}
                  {row("Suture Removal", p.postOp.sutureRemovalDay)}
                  {row("Wound Condition", p.postOp.woundCondition)}
                  {row("Post-Op Imaging", p.postOp.postOpImaging)} {row("Investigations", p.postOp.postOpInvestigations)}
                  {row("HPE Report", p.postOp.hpeReport)} {row("HPE Stage", p.postOp.hpeStage)}
                  {(() => {
                    const fd = p.postOp?.finalDx || {};
                    if (!fd.type) return null;
                    let fdStr = "";
                    if (fd.type === "malignancy") {
                      const h = fd.histology === "Others" ? fd.histologyOther : fd.histology;
                      fdStr = [h, fd.malSite].filter(Boolean).join(" ") + (fd.pathStage ? " (" + fd.pathStage + ")" : "");
                    } else {
                      fdStr = fd.primaryDx || "";
                      if (fd.primaryLaterality) fdStr += " (" + fd.primaryLaterality + ")";
                      if (fd.secondaryDx) fdStr += " + " + fd.secondaryDx;
                    }
                    return <>
                      {row("Final Diagnosis", fdStr)}
                      {fd.notes && row("Final Dx Notes", fd.notes)}
                    </>;
                  })()}
                  {row("Hospital Stay", p.postOp.hospitalStayNotes)}
                  {row("Medications", p.postOp.dischargeMedications)} {row("Diet", p.postOp.dietInstructions)}
                  {row("Advice on Discharge", p.postOp.adviceOnDischarge)}
                  {row("Follow-Up", p.postOp.followUpDate ? fmtD(p.postOp.followUpDate) : "")}
                </>)}

                {/* Daily Progress Notes (read-only for discharged) */}
                {(p.dailyNotes || []).length > 0 && sec2("Daily Progress Notes", "🩺", "#0277bd", <>
                  {p.dailyNotes.map((e, i) => <div key={i} style={{ marginBottom: 6, padding: "6px 8px", background: i === 0 ? "#f0f9ff" : "#f8fafc", borderRadius: 6, border: `1px solid ${i === 0 ? "#b3e5fc" : "#e2e8f0"}`, fontSize: "0.72rem" }}>
                    <div style={{ fontWeight: 700, color: "#0277bd", marginBottom: 2 }}>{e.pod || ""} {e.date && `— ${new Date(e.date + "T00:00:00").toLocaleDateString("en-IN", { day: "numeric", month: "short" })}`} {e.time && `at ${e.time}`}</div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: "1px 10px", color: "#475569", lineHeight: 1.5 }}>
                      {e.pulse && <span><b>P:</b> {e.pulse}</span>} {e.bp && <span><b>BP:</b> {e.bp}</span>} {e.spo2 && <span><b>SpO2:</b> {e.spo2}%</span>} {e.temp && <span><b>T:</b> {e.temp}°F</span>}
                      {e.wound && <span><b>Wound:</b> {e.wound}</span>} {e.drainOutput && <span><b>Drain:</b> {e.drainOutput}{e.drainOutputVol && ` (${e.drainOutputVol}ml)`}</span>} {e.pain && <span><b>Pain:</b> {e.pain}/10</span>}
                      {e.diet && <span><b>Diet:</b> {e.diet}</span>} {e.flatus && <span style={{ color: "#2e7d32" }}>✓Flatus</span>} {e.bowels && <span style={{ color: "#2e7d32" }}>✓Bowels</span>} {e.mobility && <span><b>Mobility:</b> {e.mobility}</span>}
                      {e.ivFluids && <span><b>IV:</b> {e.ivFluids}</span>} {e.antibiotics && <span><b>Abx:</b> {e.antibiotics}</span>} {e.otherMeds && <span><b>Meds:</b> {e.otherMeds}</span>}
                      {e.cbcHb && <span><b>Hb:</b> {e.cbcHb}</span>} {e.tlc && <span><b>TLC:</b> {e.tlc}</span>} {e.creatinine && <span><b>Cr:</b> {e.creatinine}</span>}
                      {e.complication && <span style={{ color: "#c62828" }}><b>⚠</b> {e.complication}</span>} {e.plan && <span style={{ color: "#0277bd" }}><b>Plan:</b> {e.plan}</span>}
                      {e.notes && <span><b>Notes:</b> {e.notes}</span>}
                    </div>
                  </div>)}
                </>)}

                {p.status === "Discharged" && <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 10 }}>
                  <button onClick={() => generateDischarge(p)} style={{ padding: "10px 20px", background: "linear-gradient(135deg,#6a1b9a,#8e24aa)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.84rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>🖨️ Print Discharge Summary</button>
                </div>}

                {/* Entry Tracking */}
                {(cl.clinicalBy || cl.listedBy || od.operatedBy) && <div style={{ marginTop: 16, padding: "8px 12px", borderRadius: 8, background: "#f8fafc", border: "1px solid #e2e8f0", fontSize: "0.68rem", color: "#94a3b8", display: "flex", flexWrap: "wrap", gap: 4 }}>
                  <span style={{ marginRight: 2 }}>📝</span>
                  {cl.clinicalBy && <span>Clinical by <b style={{ color: "#475569" }}>{cl.clinicalBy}</b></span>}
                  {cl.clinicalBy && cl.listedBy && <span>·</span>}
                  {cl.listedBy && <span>Listed by <b style={{ color: "#475569" }}>{cl.listedBy}</b></span>}
                  {(cl.clinicalBy || cl.listedBy) && od.operatedBy && <span>·</span>}
                  {od.operatedBy && <span>Op entry by <b style={{ color: "#475569" }}>{od.operatedBy}</b></span>}
                </div>}
              </div>
            </>;
          })() : (() => {
            const operated = patients.filter(p => p.status === "Operated").sort((a, b) => new Date(b.operatedAt || 0) - new Date(a.operatedAt || 0));
            const filtered = operated.filter(p => { const s = search.toLowerCase(); return !s || p.name.toLowerCase().includes(s) || (p.diagnosis || "").toLowerCase().includes(s) || (p.malignancySite || "").toLowerCase().includes(s); });
            return <>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.15rem" }}>✅ Operated Patients</h2>
                <span style={{ fontSize: "0.82rem", color: "#64748b" }}>{filtered.length} patients</span>
              </div>
              <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "7px 12px", flex: 1 }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2"><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>
                  <input style={{ border: "none", outline: "none", fontSize: "0.84rem", width: "100%", fontFamily: "'Outfit',sans-serif", background: "transparent" }} placeholder="Search..." value={search} onChange={e => setSearch(e.target.value)} />
                </div>
              </div>
              {filtered.length === 0 ? <div style={S.empty}>No operated patients yet.</div> : (
                <div style={{ background: "#fff", borderRadius: 12, border: "1px solid #e2e8f0", overflow: "auto" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.78rem" }}>
                    <thead><tr>
                      <th style={{ ...S.th, width: 28 }}>#</th>
                      <th style={S.th}>Patient</th>
                      <th style={{ ...S.th, width: 70 }}>MRD</th>
                      <th style={S.th}>Diagnosis</th>
                      <th style={S.th}>Procedure Done</th>
                      <th style={S.th}>Surgeon</th>
                      <th style={S.th}>Date</th>
                      <th style={S.th}>Shifted</th>
                    </tr></thead>
                    <tbody>{filtered.map((p, i) => {
                      const od = p.opDetails || {};
                      return (
                        <tr key={p.id} onClick={() => setViewPatient(p)} style={{ borderBottom: "1px solid #f1f5f9", cursor: "pointer", transition: "background 0.1s" }} onMouseEnter={e => e.currentTarget.style.background = "#f0fdf4"} onMouseLeave={e => e.currentTarget.style.background = ""}>
                          <td style={{ ...S.td, textAlign: "center", color: "#94a3b8", fontWeight: 600 }}>{i + 1}</td>
                          <td style={S.td}>
                            <div style={{ fontWeight: 600, fontSize: "0.82rem" }}>{p.name}{p.isEmergency && <span style={{ fontSize: "0.54rem", padding: "1px 4px", borderRadius: 3, background: "#fef2f2", color: "#c62828", fontWeight: 700, marginLeft: 4, verticalAlign: "middle" }}>EMG</span>}</div>
                            <div style={{ color: "#94a3b8", fontSize: "0.7rem" }}>{p.age ? p.age + "y/" : ""}{p.sex?.[0] || ""}{p.phone ? " · " + p.phone : ""}</div>
                          </td>
                          <td style={{ ...S.td, fontSize: "0.72rem", color: "#475569" }}>{p.clinical?.mrd || "—"}</td>
                          <td style={{ ...S.td, maxWidth: 130 }}>{p.type === "malignancy" ? (p.malignancySite || "Malignancy") : (p.diagnosis || "—")}</td>
                          <td style={S.td}>
                            <div style={{ fontWeight: 600 }}>{od.primaryProcedure || p.plannedProcedure || "—"}</div>
                            {od.adjunctProcedure && <div style={{ fontSize: "0.7rem", color: "#64748b" }}>+ {od.adjunctProcedure}</div>}
                          </td>
                          <td style={{ ...S.td, fontSize: "0.72rem" }}>{od.operatingSurgeon === "__other" ? od.surgeonOther : (od.operatingSurgeon || "—")}</td>
                          <td style={{ ...S.td, fontSize: "0.72rem" }}>{od.surgeryDateActual ? fmtD(od.surgeryDateActual) : "—"}</td>
                          <td style={S.td}>{od.shiftedTo ? <Bdg bg={od.shiftedTo === "ICU" ? "#fce4ec" : "#e8f5e9"} color={od.shiftedTo === "ICU" ? "#c62828" : "#2e7d32"} border={od.shiftedTo === "ICU" ? "#ef9a9a" : "#a5d6a7"}>{od.shiftedTo}</Bdg> : "—"}</td>
                        </tr>
                      );
                    })}</tbody>
                  </table>
                </div>
              )}
            </>;
          })()}
        </div>}

        {/* ═══ DISCHARGED PATIENTS PAGE ═══ */}
        {page === "discharged" && <div className="st-content" style={S.content}>
          {viewPatient ? (() => {
            const p = viewPatient; const cl = p.clinical || {}; const po = cl.preOp || {}; const od = p.opDetails || {}; const pp = p.postOp || {};
            const lbl2 = { fontSize: "0.64rem", fontWeight: 600, color: "#94a3b8", textTransform: "uppercase", letterSpacing: "0.04em" };
            const val2 = { fontSize: "0.84rem", color: "#1e293b", fontWeight: 500 };
            const row = (l, v) => v ? <div style={{ marginBottom: 6 }}><div style={lbl2}>{l}</div><div style={val2}>{v}</div></div> : null;
            const sec2 = (title, icon, color, children) => <div style={{ marginBottom: 12, border: "1px solid #e2e8f0", borderRadius: 10, overflow: "hidden" }}><div style={{ padding: "8px 14px", background: color + "08", fontWeight: 700, fontSize: "0.82rem", color, borderBottom: "1px solid #e2e8f0" }}>{icon} {title}</div><div style={{ padding: "12px 14px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 16px" }}>{children}</div></div>;
            return <>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
                <button onClick={() => setViewPatient(null)} style={{ border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", padding: "5px 12px", cursor: "pointer", fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif" }}>← Back</button>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.1rem", flex: 1 }}>Discharged — {p.name}</h2>
                {me.role === "admin" && <div style={{ display: "flex", gap: 4 }}>
                  <button onClick={() => { setClinicalPt(patients.find(x => x.id === p.id)); setViewPatient(null); setPage("admissions"); }} style={{ padding: "4px 10px", borderRadius: 6, border: "1px solid #90caf9", background: "#e3f2fd", fontSize: "0.68rem", fontWeight: 600, color: "#1565c0", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"📝"} Edit Clinical</button>
                  <button onClick={() => { setOperativePt(patients.find(x => x.id === p.id)); setViewPatient(null); setPage("listed"); }} style={{ padding: "4px 10px", borderRadius: 6, border: "1px solid #a5d6a7", background: "#e8f5e9", fontSize: "0.68rem", fontWeight: 600, color: "#2e7d32", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"🔪"} Edit Operative</button>
                </div>}
                <button onClick={() => generateDischarge(p)} style={{ padding: "6px 14px", background: "#f3e5f5", color: "#6a1b9a", border: "1px solid #ce93d8", borderRadius: 8, fontSize: "0.76rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>{"🖨️"} Print Discharge</button>
              </div>
              <div style={{ maxWidth: 740, margin: "0 auto" }}>
                {sec2("Patient Particulars", "👤", "#2e7d32", <>
                  {row("Name", p.name)} {row("Age / Sex", `${p.age}y / ${p.sex}`)} {row("Phone", p.phone)} {row("MRD", cl.mrd)}
                  {row("Blood Group", cl.bloodGroup)} {row("Address", [cl.district, cl.state].filter(Boolean).join(", "))}
                  {row("Occupation", cl.occupation === "Other" ? cl.occupationOther || "Other" : cl.occupation)}
                  {row("Comorbidities", [...(cl.comorbidities || []), cl.comorbidOther].filter(Boolean).join(", "))}
                  {row("PAC Cleared", cl.pacClearedDate ? fmtD(cl.pacClearedDate) : (cl.pacStatus === "Cleared" ? "Yes" : ""))}
                  {row("Date of Admission", p.admittedAt ? fmtDT(p.admittedAt) : "")}
                  {(p.admissionHistory || []).length > 0 && row("Previous Admissions", p.admissionHistory.map(ah => fmtDT(ah.admittedAt)).join(", "))}
                </>)}
                {sec2("Pre-Op Diagnosis", "🩺", "#0d47a1", <>
                  {row("Type", po.lesionType === "malignancy" ? "Malignant" : "Benign")}
                  {po.lesionType === "malignancy" ? <>{row("Site", po.malSite)} {row("Staging", [po.clinicalT, po.clinicalN, po.clinicalM].filter(Boolean).join(" "))} {row("Plan", po.plan)}</> : <>{row("Primary Dx", [po.primaryDx, po.primaryLaterality && `(${po.primaryLaterality})`].filter(Boolean).join(" "))}</>}
                  {row("Planned Procedure", po.procedure)}
                </>)}
                {od.primaryProcedure && sec2("Operative Details", "🔪", "#6a1b9a", <>
                  {row("Surgery Date", od.surgeryDateActual ? fmtD(od.surgeryDateActual) : "")}
                  {row("Surgeon", od.operatingSurgeon === "__other" ? od.surgeonOther : od.operatingSurgeon)}
                  {row("Access", od.opAccessMode === "Other" ? od.opAccessOther : od.opAccessMode)}
                  {row("Procedure", od.primaryProcedure)} {row("Findings", (od.intraFindings || []).filter(Boolean).join("; "))}
                </>)}
                {sec2("Discharge Summary", "🏠", "#e65100", <>
                  {row("Discharge Date", p.dischargeDate ? fmtD(p.dischargeDate) : "—")}
                  {row("Condition at Discharge", pp.dischargeCondition)}
                  {row("Post-Op Complications", (pp.complications || []).filter(c => c && c !== "None").join(", ") || "None")}
                  {row("Drain Removal", (pp.drainRemoval || []).length > 0 ? pp.drainRemoval.map(r => { const dr = (p.opDetails?.drainList || [])[r.drainIdx]; return `${dr ? [dr.type, dr.site].filter(Boolean).join(" ") : "Drain "+(r.drainIdx+1)}: ${r.pod || ""}`; }).join("; ") : (pp.drainRemovalDay ? `POD ${pp.drainRemovalDay}` : ""))}
                  {row("RT Removal", pp.rylesRemoval || (pp.rylesRemovalDay ? `POD ${pp.rylesRemovalDay}` : ""))}
                  {row("Catheter Removal", pp.catheterRemoval || (pp.catheterRemovalDay ? `POD ${pp.catheterRemovalDay}` : ""))}
                  {row("Flatus / Bowels / Orals", [pp.flatusDay && `Flatus ${pp.flatusDay}`, pp.bowelsDay && `Bowels ${pp.bowelsDay}`, pp.oralsDay && `Orals ${pp.oralsDay}`].filter(Boolean).join(" · ") || "—")}
                  {row("Ambulation", pp.ambulationDay)}
                  {row("Suture Removal", pp.sutureRemovalDay)}
                  {row("Wound Condition", pp.woundCondition)}
                  {row("HPE Report", pp.hpeReport)} {row("HPE Stage", pp.hpeStage)}
                  {(() => {
                    const fd = pp.finalDx || {};
                    if (!fd.type) return null;
                    let fdStr = "";
                    if (fd.type === "malignancy") {
                      const h = fd.histology === "Others" ? fd.histologyOther : fd.histology;
                      fdStr = [h, fd.malSite].filter(Boolean).join(" ") + (fd.pathStage ? " (" + fd.pathStage + ")" : "");
                    } else {
                      fdStr = fd.primaryDx || "";
                      if (fd.primaryLaterality) fdStr += " (" + fd.primaryLaterality + ")";
                      if (fd.secondaryDx) fdStr += " + " + fd.secondaryDx;
                    }
                    return <>
                      {row("Final Diagnosis", fdStr)}
                      {fd.notes && row("Final Dx Notes", fd.notes)}
                    </>;
                  })()}
                  {row("Discharge Medications", pp.dischargeMedications)}
                  {row("Diet Instructions", pp.dietInstructions)}
                  {row("Advice", pp.adviceOnDischarge)}
                  {row("Follow-Up", pp.followUpDate ? `${fmtD(pp.followUpDate)}${pp.followUpInstructions ? " — " + pp.followUpInstructions : ""}` : pp.followUpInstructions)}
                </>)}

                <FollowUpSection patient={p} onSave={data => saveFollowUps(p, data)} customTemplates={customFupTemplates} researchProtocols={config.researchProtocols} />

                {/* Entry Tracking */}
                {(cl.clinicalBy || cl.listedBy || od.operatedBy) && <div style={{ marginTop: 16, padding: "8px 12px", borderRadius: 8, background: "#f8fafc", border: "1px solid #e2e8f0", fontSize: "0.68rem", color: "#94a3b8", display: "flex", flexWrap: "wrap", gap: 4 }}>
                  <span style={{ marginRight: 2 }}>📝</span>
                  {cl.clinicalBy && <span>Clinical by <b style={{ color: "#475569" }}>{cl.clinicalBy}</b></span>}
                  {cl.clinicalBy && cl.listedBy && <span>·</span>}
                  {cl.listedBy && <span>Listed by <b style={{ color: "#475569" }}>{cl.listedBy}</b></span>}
                  {(cl.clinicalBy || cl.listedBy) && od.operatedBy && <span>·</span>}
                  {od.operatedBy && <span>Op entry by <b style={{ color: "#475569" }}>{od.operatedBy}</b></span>}
                </div>}
              </div>
            </>;
          })() : (() => {
            const discharged = patients.filter(p => p.status === "Discharged").sort((a, b) => new Date(b.dischargedAt || 0) - new Date(a.dischargedAt || 0));
            const filtered = discharged.filter(p => {
              // Surgery date filter
              if (dischSurgDateFilter && (p.opDetails?.surgeryDateActual || "") !== dischSurgDateFilter) return false;
              const s = search.toLowerCase(); if (!s) return true;
              const od = p.opDetails || {};
              const proc = (od.primaryProcedure || p.plannedProcedure || "").toLowerCase();
              const surgeon = (od.operatingSurgeon === "__other" ? od.surgeonOther : od.operatingSurgeon || "").toLowerCase();
              const surgDate = od.surgeryDateActual || "";
              return p.name.toLowerCase().includes(s) || (p.clinical?.mrd || "").toLowerCase().includes(s) || (p.diagnosis || "").toLowerCase().includes(s) || (p.malignancySite || "").toLowerCase().includes(s) || proc.includes(s) || surgeon.includes(s) || surgDate.includes(s);
            });
            return <>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14, flexWrap: "wrap", gap: 8 }}>
                <h2 style={{ ...S.secT, margin: 0, fontSize: "1.15rem" }}>🏠 Discharged Patients</h2>
                <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <span style={{ fontSize: "0.82rem", color: "#64748b" }}>{filtered.length} patients</span>
                  {discharged.length > 0 && <button onClick={openExcelModal} style={{ padding: "6px 14px", background: "linear-gradient(135deg,#1b5e20,#2e7d32)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.76rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" }}>📊 Export Excel</button>}
                </div>
              </div>
              <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "7px 12px", flex: 1, minWidth: 180 }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2"><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>
                  <input style={{ border: "none", outline: "none", fontSize: "0.84rem", width: "100%", fontFamily: "'Outfit',sans-serif", background: "transparent" }} placeholder="Search name, MRD, diagnosis, procedure..." value={search} onChange={e => setSearch(e.target.value)} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{ fontSize: "0.72rem", color: "#64748b" }}>Op Date:</span>
                  <input type="date" value={dischSurgDateFilter} onChange={e => setDischSurgDateFilter(e.target.value)} style={{ padding: "7px 12px", border: "1.5px solid #6a1b9a", borderRadius: 10, fontSize: "0.82rem", fontFamily: "'Outfit',sans-serif", background: dischSurgDateFilter ? "#faf4ff" : "#fff", cursor: "pointer", color: dischSurgDateFilter ? "#6a1b9a" : "#475569", fontWeight: dischSurgDateFilter ? 600 : 400 }} />
                  {dischSurgDateFilter && <button onClick={() => setDischSurgDateFilter("")} style={{ border: "1px solid #e2e8f0", borderRadius: 6, background: "#fff", padding: "5px 8px", cursor: "pointer", fontSize: "0.72rem", color: "#c62828", fontFamily: "'Outfit',sans-serif" }} title="Clear">✕</button>}
                </div>
              </div>
              {dischSurgDateFilter && <div style={{ marginBottom: 10, fontSize: "0.76rem", color: "#64748b" }}>Showing patients operated on <b style={{ color: "#6a1b9a" }}>{fmtD(dischSurgDateFilter)}</b></div>}
              {filtered.length === 0 ? <div style={S.empty}>No discharged patients{search || dischSurgDateFilter ? " matching filter" : " yet"}.</div> : (
                <div style={{ background: "#fff", borderRadius: 12, border: "1px solid #e2e8f0", overflow: "auto" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.78rem" }}>
                    <thead><tr>
                      <th style={{ ...S.th, width: 28 }}>#</th>
                      <th style={S.th}>Patient</th>
                      <th style={S.th}>MRD</th>
                      <th style={S.th}>Diagnosis</th>
                      <th style={S.th}>Procedure</th>
                      <th style={S.th}>Surgeon</th>
                      <th style={S.th}>Op Date</th>
                      <th style={{ ...S.th, width: 40 }}></th>
                    </tr></thead>
                    <tbody>{filtered.map((p, i) => {
                      const od = p.opDetails || {};
                      return (
                        <tr key={p.id} onClick={() => setViewPatient(p)} style={{ borderBottom: "1px solid #f1f5f9", cursor: "pointer", transition: "background 0.1s" }} onMouseEnter={e => e.currentTarget.style.background = "#f0fdf4"} onMouseLeave={e => e.currentTarget.style.background = ""}>
                          <td style={{ ...S.td, textAlign: "center", color: "#94a3b8", fontWeight: 600 }}>{i + 1}</td>
                          <td style={S.td}>
                            <div style={{ fontWeight: 600, fontSize: "0.82rem" }}>{p.name}{p.isEmergency && <span style={{ fontSize: "0.54rem", padding: "1px 4px", borderRadius: 3, background: "#fef2f2", color: "#c62828", fontWeight: 700, marginLeft: 4 }}>EMG</span>}</div>
                            <div style={{ color: "#94a3b8", fontSize: "0.7rem" }}>{p.age ? p.age + "y/" : ""}{p.sex?.[0] || ""}</div>
                          </td>
                          <td style={{ ...S.td, fontSize: "0.76rem", color: "#475569" }}>{p.clinical?.mrd || "—"}</td>
                          <td style={{ ...S.td, maxWidth: 130 }}>{p.type === "malignancy" ? (p.malignancySite || "Malignancy") : (p.diagnosis || "—")}</td>
                          <td style={S.td}><div style={{ fontWeight: 600 }}>{od.primaryProcedure || p.plannedProcedure || "—"}</div></td>
                          <td style={{ ...S.td, fontSize: "0.72rem" }}>{od.operatingSurgeon === "__other" ? od.surgeonOther : (od.operatingSurgeon || "—")}</td>
                          <td style={{ ...S.td, fontSize: "0.72rem" }}>{od.surgeryDateActual ? fmtD(od.surgeryDateActual) : "—"}</td>
                          <td style={{ ...S.td, textAlign: "center" }}><button onClick={e => { e.stopPropagation(); generateDischarge(p); }} title="Print Discharge" style={{ ...S.actBtn, color: "#6a1b9a", borderColor: "#ce93d8" }}>🖨️</button></td>
                        </tr>
                      );
                    })}</tbody>
                  </table>
                </div>
              )}
            </>;
          })()}
        </div>}

        </main>

    {/* Excel Column Selection Modal */}
    {excelModal && <div style={S.modOv} onClick={() => setExcelModal(null)}>
      <div onClick={e => e.stopPropagation()} style={{ ...S.mod, maxWidth: 560, maxHeight: "85vh", overflow: "auto" }}>
        <h3 style={{ margin: "0 0 8px", fontSize: "0.96rem", fontFamily: "'Outfit',sans-serif", color: "#1b5e20" }}>{"📊"} Export Discharged Patients</h3>
        <p style={{ fontSize: "0.72rem", color: "#64748b", margin: "0 0 12px" }}>Select columns to include in the Excel export. Uncheck columns you don't need.</p>

        <div style={{ display: "flex", gap: 6, marginBottom: 10 }}>
          <button onClick={() => setExcelModal(prev => { const c = {}; ALL_EXCEL_COLS.forEach(k => c[k] = true); return { ...prev, columns: c }; })} style={{ padding: "4px 10px", border: "1px solid #a5d6a7", background: "#e8f5e9", borderRadius: 6, fontSize: "0.68rem", fontWeight: 600, color: "#2e7d32", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Select All</button>
          <button onClick={() => setExcelModal(prev => { const c = {}; ALL_EXCEL_COLS.forEach(k => c[k] = false); return { ...prev, columns: c }; })} style={{ padding: "4px 10px", border: "1px solid #e2e8f0", background: "#f8fafc", borderRadius: 6, fontSize: "0.68rem", fontWeight: 600, color: "#64748b", cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Deselect All</button>
          <span style={{ fontSize: "0.68rem", color: "#1565c0", fontWeight: 600, marginLeft: "auto", alignSelf: "center" }}>{Object.values(excelModal.columns).filter(Boolean).length}/{ALL_EXCEL_COLS.length} selected</span>
        </div>

        {EXCEL_COLUMNS.map(grp => {
          const allOn = grp.cols.every(c => excelModal.columns[c]);
          const someOn = grp.cols.some(c => excelModal.columns[c]);
          return <div key={grp.group} style={{ marginBottom: 8 }}>
            <div onClick={() => setExcelModal(prev => { const c = { ...prev.columns }; const turnOn = !allOn; grp.cols.forEach(k => c[k] = turnOn); return { ...prev, columns: c }; })} style={{ display: "flex", alignItems: "center", gap: 6, padding: "4px 0", cursor: "pointer" }}>
              <input type="checkbox" checked={allOn} readOnly style={{ accentColor: "#2e7d32" }} ref={el => { if (el) el.indeterminate = someOn && !allOn; }} />
              <span style={{ fontSize: "0.74rem", fontWeight: 700, color: "#1e293b" }}>{grp.group}</span>
              <span style={{ fontSize: "0.62rem", color: "#94a3b8" }}>({grp.cols.filter(c => excelModal.columns[c]).length}/{grp.cols.length})</span>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: "2px 0", paddingLeft: 22 }}>
              {grp.cols.map(col => (
                <label key={col} style={{ display: "flex", alignItems: "center", gap: 4, fontSize: "0.7rem", color: excelModal.columns[col] ? "#2e7d32" : "#94a3b8", cursor: "pointer", width: "50%", padding: "1px 0" }}>
                  <input type="checkbox" checked={!!excelModal.columns[col]} onChange={e => setExcelModal(prev => ({ ...prev, columns: { ...prev.columns, [col]: e.target.checked } }))} style={{ accentColor: "#2e7d32" }} />
                  {col}
                </label>
              ))}
            </div>
          </div>;
        })}

        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 14, borderTop: "1px solid #e2e8f0", paddingTop: 12 }}>
          <button onClick={() => setExcelModal(null)} style={{ padding: "8px 16px", border: "1.5px solid #e2e8f0", borderRadius: 8, background: "#fff", fontSize: "0.8rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Cancel</button>
          <button onClick={() => generateDischargeExcel(null)} style={{ padding: "8px 16px", background: "#1b5e20", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.8rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>Export All Columns</button>
          <button onClick={() => generateDischargeExcel(excelModal.columns)} style={{ padding: "8px 16px", background: "linear-gradient(135deg,#1b5e20,#2e7d32)", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.8rem", fontWeight: 600, cursor: "pointer", fontFamily: "'Outfit',sans-serif" }}>{"📊"} Export Selected ({Object.values(excelModal.columns).filter(Boolean).length})</button>
        </div>
      </div>
    </div>}

    {/* Discharge Certificate Overlay */}
    {dischPreview && <DischargeCertificate patient={dischPreview} onClose={() => setDischPreview(null)} />}

    </div>
    </>
  );
}

// ═════════════════════════════════════════════════════════════
const S = {
  loginBg: { display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100vh", background: "linear-gradient(155deg,#0b1420 0%,#162032 40%,#0f2818 100%)", fontFamily: "'Outfit',sans-serif", padding: 20 },
  loginCard: { width: "100%", maxWidth: 390, background: "#fff", borderRadius: 16, padding: "34px 28px", boxShadow: "0 24px 80px rgba(0,0,0,0.35)" },
  logo: { display: "inline-flex", alignItems: "center", justifyContent: "center", width: 48, height: 48, borderRadius: 13, background: "linear-gradient(135deg,#2e7d32,#43a047)", color: "#fff", fontFamily: "'Playfair Display',serif", fontSize: "1.3rem", fontWeight: 700, marginBottom: 14, boxShadow: "0 4px 16px rgba(46,125,50,0.3)" },
  label: { display: "block", fontSize: "0.72rem", fontWeight: 600, color: "#475569", marginBottom: 5, letterSpacing: "0.04em", fontFamily: "'Outfit',sans-serif", textTransform: "uppercase" },
  input: { width: "100%", padding: "10px 13px", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.87rem", fontFamily: "'Outfit',sans-serif", color: "#1e293b", outline: "none", boxSizing: "border-box", background: "#fff" },
  btnP: { padding: "11px 24px", background: "linear-gradient(135deg,#2e7d32,#388e3c)", color: "#fff", border: "none", borderRadius: 10, fontSize: "0.88rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer", boxShadow: "0 2px 10px rgba(46,125,50,0.25)" },
  btnS: { padding: "10px 20px", background: "#fff", color: "#475569", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: "0.84rem", fontWeight: 500, fontFamily: "'Outfit',sans-serif", cursor: "pointer" },
  btnSm: { padding: "4px 10px", background: "none", border: "1px solid #e2e8f0", borderRadius: 6, cursor: "pointer", fontSize: "0.76rem", fontFamily: "'Outfit',sans-serif", color: "#475569" },
  // Sidebar
  sidebar: { width: 210, minWidth: 210, background: "#0b1420", display: "flex", flexDirection: "column", justifyContent: "space-between", position: "sticky", top: 0, height: "100vh", overflowY: "auto", flexShrink: 0 },
  sideSection: { fontSize: "0.58rem", fontWeight: 700, color: "#475569", letterSpacing: "0.1em", textTransform: "uppercase", padding: "0 8px 6px", marginTop: 2 },
  sideItem: { display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "8px 12px", border: "none", borderRadius: 8, background: "transparent", color: "#94a3b8", fontSize: "0.8rem", fontWeight: 500, fontFamily: "'Outfit',sans-serif", cursor: "pointer", textAlign: "left", marginBottom: 2, transition: "all 0.15s" },
  sideItemOn: { display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "8px 12px", border: "none", borderRadius: 8, background: "#2e7d3218", color: "#4caf50", fontSize: "0.8rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer", textAlign: "left", marginBottom: 2 },
  sideBadge: { display: "inline-flex", alignItems: "center", justifyContent: "center", minWidth: 18, height: 18, borderRadius: 9, background: "#1565c0", color: "#fff", fontSize: "0.6rem", fontWeight: 700, padding: "0 4px", marginLeft: "auto" },
  navB: { background: "rgba(255,255,255,0.08)", border: "none", color: "#94a3b8", cursor: "pointer", padding: 6, borderRadius: 8, display: "flex" },
  // Tabs (inside Appointments page)
  tabs: { display: "flex", gap: 6, padding: "9px 20px", background: "#fff", borderBottom: "1px solid #e2e8f0", flexWrap: "wrap" },
  tab: { display: "inline-flex", alignItems: "center", gap: 4, padding: "6px 14px", border: "1.5px solid #e2e8f0", borderRadius: 8, background: "#fff", color: "#475569", fontSize: "0.8rem", fontWeight: 500, fontFamily: "'Outfit',sans-serif", cursor: "pointer" },
  tabOn: { display: "inline-flex", alignItems: "center", gap: 4, padding: "6px 14px", border: "1.5px solid #2e7d32", borderRadius: 8, background: "#e8f5e9", color: "#2e7d32", fontSize: "0.8rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer" },
  tabA: { display: "inline-flex", alignItems: "center", gap: 4, padding: "6px 14px", border: "none", borderRadius: 8, background: "linear-gradient(135deg,#2e7d32,#388e3c)", color: "#fff", fontSize: "0.8rem", fontWeight: 600, fontFamily: "'Outfit',sans-serif", cursor: "pointer", boxShadow: "0 2px 8px rgba(46,125,50,0.2)" },
  // Main area
  main: { flex: 1, overflowY: "auto", height: "100vh", WebkitOverflowScrolling: "touch" },
  content: { padding: 24, maxWidth: 1100 },
  secT: { fontSize: "1rem", fontWeight: 700, color: "#1e293b", margin: "0 0 12px", fontFamily: "'Outfit',sans-serif" },
  empty: { textAlign: "center", padding: "36px 20px", color: "#94a3b8", background: "#fff", borderRadius: 12, border: "1.5px dashed #e2e8f0", fontSize: "0.88rem" },
  formC: { background: "#fff", borderRadius: 16, padding: "26px 24px", boxShadow: "0 1px 8px rgba(0,0,0,0.06)", maxWidth: 640, margin: "0 auto" },
  th: { textAlign: "left", padding: "9px 10px", fontWeight: 600, color: "#94a3b8", fontSize: "0.68rem", textTransform: "uppercase", letterSpacing: "0.05em", borderBottom: "2px solid #e2e8f0", background: "#f8fafc", whiteSpace: "nowrap", fontFamily: "'Outfit',sans-serif" },
  td: { padding: "8px 10px", fontSize: "0.8rem", color: "#475569", verticalAlign: "middle", fontFamily: "'Outfit',sans-serif" },
  actBtn: { display: "inline-flex", alignItems: "center", justifyContent: "center", width: 30, height: 28, padding: 0, border: "1px solid #e2e8f0", borderRadius: 6, background: "#fff", cursor: "pointer", fontSize: "0.78rem", marginLeft: 4 },
  modOv: { position: "fixed", inset: 0, background: "rgba(11,20,32,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 9000, padding: 20 },
  mod: { background: "#fff", borderRadius: 16, padding: 24, maxWidth: 370, width: "100%", boxShadow: "0 20px 60px rgba(0,0,0,0.25)", fontFamily: "'Outfit',sans-serif" },
};
