import { useState, useEffect, useRef } from "react";
import { 
  LayoutDashboard, Users, BookOpen, CalendarDays, Grid3X3, 
  Building2, FileText, LogOut, Bell, ChevronDown, Plus, 
  Search, Download, Edit, Trash2, Eye, AlertCircle, 
  CheckCircle, Clock, ChevronRight, X, Menu, Filter,
  BarChart3, GraduationCap, BookMarked, Layers, Settings
} from "lucide-react";

// ─── SEED DATA ───────────────────────────────────────────────────────────────
const BRANCHES = [
  { id: 1, code: "CE", name: "Civil Engineering", lateral: false },
  { id: 2, code: "CE-LE", name: "Civil Engineering (Lateral Entry)", lateral: true },
  { id: 3, code: "PCE", name: "Petro Chemical Engineering", lateral: false },
  { id: 4, code: "PT", name: "Paint Technology", lateral: false },
];

const SEMESTERS = [
  { id: 1, no: 1, type: "ODD", year: "2025-26" },
  { id: 2, no: 2, type: "EVEN", year: "2025-26" },
  { id: 3, no: 3, type: "ODD", year: "2025-26" },
  { id: 4, no: 4, type: "EVEN", year: "2025-26" },
  { id: 5, no: 5, type: "ODD", year: "2025-26" },
  { id: 6, no: 6, type: "EVEN", year: "2025-26" },
];

const FACULTY = [
  { id: 1, name: "Dr. R. K. Sharma", designation: "Principal", dept: "Admin", email: "rksharma@poly.edu", maxPeriodsWeek: 10, active: true },
  { id: 2, name: "Prof. A. Mehta", designation: "H.O.D", dept: "Civil Engineering", email: "amehta@poly.edu", maxPeriodsWeek: 20, active: true },
  { id: 3, name: "Mr. S. Patel", designation: "Lecturer", dept: "Civil Engineering", email: "spatel@poly.edu", maxPeriodsWeek: 30, active: true },
  { id: 4, name: "Ms. P. Gupta", designation: "Lecturer", dept: "Civil Engineering", email: "pgupta@poly.edu", maxPeriodsWeek: 30, active: true },
  { id: 5, name: "Mr. K. Verma", designation: "Lecturer", dept: "Petro Chemical", email: "kverma@poly.edu", maxPeriodsWeek: 30, active: true },
  { id: 6, name: "Ms. N. Singh", designation: "Lecturer", dept: "Petro Chemical", email: "nsingh@poly.edu", maxPeriodsWeek: 30, active: true },
  { id: 7, name: "Mr. D. Rao", designation: "Lecturer", dept: "Paint Technology", email: "drao@poly.edu", maxPeriodsWeek: 30, active: true },
  { id: 8, name: "Ms. R. Joshi", designation: "Instructor", dept: "Civil Engineering", email: "rjoshi@poly.edu", maxPeriodsWeek: 28, active: true },
  { id: 9, name: "Mr. T. Kumar", designation: "Workshop Superintendent", dept: "Workshop", email: "tkumar@poly.edu", maxPeriodsWeek: 25, active: true },
  { id: 10, name: "Ms. S. Agarwal", designation: "Lecturer", dept: "Paint Technology", email: "sagarwal@poly.edu", maxPeriodsWeek: 30, active: true },
];

const SUBJECTS = [
  { id: 1, code: "CE301", name: "Structural Engineering", type: "Theory", credits: 4, periodsWeek: 4, branch: 1, sem: 3 },
  { id: 2, code: "CE302", name: "Fluid Mechanics", type: "Theory", credits: 3, periodsWeek: 3, branch: 1, sem: 3 },
  { id: 3, code: "CE303", name: "Surveying Lab", type: "Practical", credits: 2, periodsWeek: 4, branch: 1, sem: 3 },
  { id: 4, code: "CE304", name: "Engineering Drawing", type: "Practical", credits: 2, periodsWeek: 4, branch: 1, sem: 3 },
  { id: 5, code: "CE305", name: "Concrete Technology", type: "Theory", credits: 3, periodsWeek: 3, branch: 1, sem: 3 },
  { id: 6, code: "PCE301", name: "Chemical Process Calc", type: "Theory", credits: 4, periodsWeek: 4, branch: 3, sem: 3 },
  { id: 7, code: "PCE302", name: "Petroleum Refining", type: "Theory", credits: 3, periodsWeek: 3, branch: 3, sem: 3 },
  { id: 8, code: "PCE303", name: "Chemistry Lab", type: "Lab", credits: 2, periodsWeek: 4, branch: 3, sem: 3 },
  { id: 9, code: "PT301", name: "Pigments & Dyes", type: "Theory", credits: 3, periodsWeek: 3, branch: 4, sem: 3 },
  { id: 10, code: "PT302", name: "Paint Formulation Lab", type: "Practical", credits: 2, periodsWeek: 4, branch: 4, sem: 3 },
];

const ROOMS = [
  { id: 1, number: "LH-101", type: "Lecture", capacity: 60, active: true },
  { id: 2, number: "LH-102", type: "Lecture", capacity: 60, active: true },
  { id: 3, number: "LAB-201", type: "Lab", capacity: 30, active: true },
  { id: 4, number: "LAB-202", type: "Lab", capacity: 30, active: true },
  { id: 5, number: "WS-01", type: "Workshop", capacity: 40, active: true },
  { id: 6, number: "DH-01", type: "Drawing Hall", capacity: 50, active: true },
];

const TIME_SLOTS = [
  { id: 1, label: "Period 1", start: "10:00", end: "11:00", isBreak: false },
  { id: 2, label: "Period 2", start: "11:00", end: "12:00", isBreak: false },
  { id: 3, label: "Period 3", start: "12:00", end: "13:00", isBreak: false },
  { id: 4, label: "Lunch", start: "13:00", end: "14:00", isBreak: true },
  { id: 5, label: "Period 4", start: "14:00", end: "15:00", isBreak: false },
  { id: 6, label: "Period 5", start: "15:00", end: "16:00", isBreak: false },
  { id: 7, label: "Period 6", start: "16:00", end: "17:00", isBreak: false },
];

const DAYS = ["MON", "TUE", "WED", "THU", "FRI", "SAT"];

const INITIAL_TIMETABLE = [
  { id:1, branch:1, sem:3, subject:1, faculty:3, room:1, slot:1, day:"MON", year:"2025-26" },
  { id:2, branch:1, sem:3, subject:2, faculty:4, room:1, slot:2, day:"MON", year:"2025-26" },
  { id:3, branch:1, sem:3, subject:5, faculty:3, room:1, slot:3, day:"MON", year:"2025-26" },
  { id:4, branch:1, sem:3, subject:3, faculty:8, room:3, slot:5, day:"MON", year:"2025-26" },
  { id:5, branch:1, sem:3, subject:1, faculty:3, room:1, slot:1, day:"TUE", year:"2025-26" },
  { id:6, branch:1, sem:3, subject:4, faculty:4, room:6, slot:2, day:"TUE", year:"2025-26" },
  { id:7, branch:1, sem:3, subject:2, faculty:4, room:1, slot:5, day:"WED", year:"2025-26" },
  { id:8, branch:1, sem:3, subject:5, faculty:3, room:1, slot:6, day:"WED", year:"2025-26" },
  { id:9, branch:1, sem:3, subject:3, faculty:8, room:3, slot:1, day:"THU", year:"2025-26" },
  { id:10, branch:1, sem:3, subject:1, faculty:3, room:1, slot:3, day:"FRI", year:"2025-26" },
];

const EXAMS = [
  { id:1, name:"First Sessional", branch:1, sem:3, subject:1, date:"2026-03-10", start:"10:00", end:"12:00", room:1 },
  { id:2, name:"First Sessional", branch:1, sem:3, subject:2, date:"2026-03-11", start:"10:00", end:"12:00", room:1 },
  { id:3, name:"Second Sessional", branch:1, sem:3, subject:1, date:"2026-04-15", start:"10:00", end:"12:00", room:2 },
  { id:4, name:"Third Sessional", branch:1, sem:3, subject:1, date:"2026-05-20", start:"10:00", end:"12:00", room:2 },
];

const USERS_DB = [
  { username: "admin", password: "admin123", role: "super_admin", name: "Super Admin", facultyId: null },
  { username: "faculty", password: "faculty123", role: "faculty", name: "Mr. S. Patel", facultyId: 3 },
  { username: "hod", password: "hod123", role: "dept_admin", name: "Prof. A. Mehta", facultyId: 2 },
];

// ─── HELPERS ─────────────────────────────────────────────────────────────────
const typeColor = { Theory: "#2563eb", Practical: "#16a34a", Lab: "#16a34a", Workshop: "#ea580c" };
const typeBg = { Theory: "#dbeafe", Practical: "#dcfce7", Lab: "#dcfce7", Workshop: "#ffedd5" };

function getSubject(id) { return SUBJECTS.find(s => s.id === id); }
function getFaculty(id) { return FACULTY.find(f => f.id === id); }
function getRoom(id) { return ROOMS.find(r => r.id === id); }

// ─── COMPONENTS ──────────────────────────────────────────────────────────────

function Badge({ children, color = "#2563eb", bg = "#dbeafe" }) {
  return (
    <span style={{ background: bg, color, fontSize: 11, fontWeight: 700, padding: "2px 8px", borderRadius: 20, letterSpacing: 0.5 }}>
      {children}
    </span>
  );
}

function StatCard({ icon: Icon, label, value, sub, accent }) {
  return (
    <div style={{ background: "#fff", borderRadius: 16, padding: "20px 24px", boxShadow: "0 1px 4px rgba(0,0,0,0.07)", display: "flex", gap: 16, alignItems: "center", border: "1px solid #f1f5f9" }}>
      <div style={{ width: 48, height: 48, borderRadius: 12, background: accent + "18", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        <Icon size={22} color={accent} />
      </div>
      <div>
        <div style={{ fontSize: 26, fontWeight: 800, color: "#0f172a", lineHeight: 1 }}>{value}</div>
        <div style={{ fontSize: 13, color: "#64748b", marginTop: 3, fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 2 }}>{sub}</div>}
      </div>
    </div>
  );
}

// ─── LOGIN ───────────────────────────────────────────────────────────────────
function LoginPage({ onLogin }) {
  const [u, setU] = useState("admin");
  const [p, setP] = useState("admin123");
  const [err, setErr] = useState("");
  const [loading, setLoading] = useState(false);

  const handle = () => {
    setLoading(true); setErr("");
    setTimeout(() => {
      const user = USERS_DB.find(x => x.username === u && x.password === p);
      if (user) onLogin(user);
      else { setErr("Invalid credentials. Try admin/admin123"); setLoading(false); }
    }, 800);
  };

  return (
    <div style={{ minHeight: "100vh", background: "linear-gradient(135deg, #0f172a 0%, #1e3a5f 50%, #0f172a 100%)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "'Segoe UI', system-ui, sans-serif", position: "relative", overflow: "hidden" }}>
      {/* BG pattern */}
      <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(circle at 2px 2px, rgba(255,255,255,0.04) 1px, transparent 0)", backgroundSize: "40px 40px" }} />
      <div style={{ position: "relative", background: "rgba(255,255,255,0.97)", borderRadius: 24, padding: "48px 44px", width: 400, boxShadow: "0 40px 100px rgba(0,0,0,0.5)" }}>
        <div style={{ textAlign: "center", marginBottom: 36 }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: "linear-gradient(135deg, #0ea5e9, #0369a1)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
            <GraduationCap size={28} color="#fff" />
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, color: "#0f172a", letterSpacing: -0.5 }}>Timetable ERP</div>
          <div style={{ fontSize: 13, color: "#64748b", marginTop: 4 }}>Classroom Management Portal</div>
        </div>
        <div style={{ marginBottom: 16 }}>
          <label style={{ fontSize: 12, fontWeight: 700, color: "#374151", letterSpacing: 0.5, textTransform: "uppercase" }}>Username</label>
          <input value={u} onChange={e => setU(e.target.value)} style={{ width: "100%", marginTop: 6, padding: "11px 14px", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: 14, outline: "none", background: "#f8fafc", boxSizing: "border-box", transition: "border 0.2s" }} onFocus={e => e.target.style.borderColor = "#0ea5e9"} onBlur={e => e.target.style.borderColor = "#e2e8f0"} />
        </div>
        <div style={{ marginBottom: 20 }}>
          <label style={{ fontSize: 12, fontWeight: 700, color: "#374151", letterSpacing: 0.5, textTransform: "uppercase" }}>Password</label>
          <input type="password" value={p} onChange={e => setP(e.target.value)} onKeyDown={e => e.key === "Enter" && handle()} style={{ width: "100%", marginTop: 6, padding: "11px 14px", border: "1.5px solid #e2e8f0", borderRadius: 10, fontSize: 14, outline: "none", background: "#f8fafc", boxSizing: "border-box" }} onFocus={e => e.target.style.borderColor = "#0ea5e9"} onBlur={e => e.target.style.borderColor = "#e2e8f0"} />
        </div>
        {err && <div style={{ background: "#fef2f2", border: "1px solid #fca5a5", borderRadius: 8, padding: "10px 14px", fontSize: 13, color: "#dc2626", marginBottom: 16, display: "flex", alignItems: "center", gap: 8 }}><AlertCircle size={14} />{err}</div>}
        <button onClick={handle} disabled={loading} style={{ width: "100%", padding: "13px", background: "linear-gradient(135deg, #0ea5e9, #0369a1)", color: "#fff", border: "none", borderRadius: 10, fontSize: 15, fontWeight: 700, cursor: "pointer", transition: "opacity 0.2s", opacity: loading ? 0.7 : 1 }}>
          {loading ? "Signing in..." : "Sign In"}
        </button>
        <div style={{ marginTop: 20, background: "#f8fafc", borderRadius: 10, padding: 14, fontSize: 12, color: "#64748b" }}>
          <b>Demo:</b> admin/admin123 · faculty/faculty123 · hod/hod123
        </div>
      </div>
    </div>
  );
}

// ─── DASHBOARD ───────────────────────────────────────────────────────────────
function Dashboard({ timetable, user }) {
  const conflicts = [];
  const today = new Date();
  const upcoming = EXAMS.filter(e => new Date(e.date) > today).slice(0, 3);
  const activeEntries = timetable.length;
  const activeFaculty = [...new Set(timetable.map(t => t.faculty))].length;

  return (
    <div>
      <div style={{ marginBottom: 28 }}>
        <h2 style={{ fontSize: 24, fontWeight: 800, color: "#0f172a", margin: 0 }}>Dashboard</h2>
        <p style={{ color: "#64748b", marginTop: 4, fontSize: 14 }}>Academic Year 2025–26 | ODD Semester</p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 28 }}>
        <StatCard icon={Grid3X3} label="Active Timetable Entries" value={activeEntries} sub="This semester" accent="#0ea5e9" />
        <StatCard icon={Users} label="Faculty Assigned" value={activeFaculty} sub={`of ${FACULTY.length} total`} accent="#8b5cf6" />
        <StatCard icon={BookOpen} label="Subjects Configured" value={SUBJECTS.length} sub="4 branches" accent="#10b981" />
        <StatCard icon={AlertCircle} label="Conflicts Detected" value={conflicts.length} sub="All clear!" accent="#f59e0b" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        {/* Upcoming Exams */}
        <div style={{ background: "#fff", borderRadius: 16, padding: 24, border: "1px solid #f1f5f9", boxShadow: "0 1px 4px rgba(0,0,0,0.06)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: "#0f172a" }}>Upcoming Exams</h3>
            <CalendarDays size={18} color="#94a3b8" />
          </div>
          {upcoming.map(ex => {
            const sub = getSubject(ex.subject);
            const br = BRANCHES.find(b => b.id === ex.branch);
            return (
              <div key={ex.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 0", borderBottom: "1px solid #f8fafc" }}>
                <div style={{ width: 44, height: 44, borderRadius: 10, background: "#fef3c7", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                  <span style={{ fontSize: 13, fontWeight: 800, color: "#d97706" }}>{new Date(ex.date).getDate()}</span>
                  <span style={{ fontSize: 9, color: "#d97706", fontWeight: 600 }}>{new Date(ex.date).toLocaleString("default", { month: "short" }).toUpperCase()}</span>
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a" }}>{sub?.name}</div>
                  <div style={{ fontSize: 12, color: "#64748b" }}>{ex.name} · {br?.code} Sem-3</div>
                </div>
                <Badge color="#d97706" bg="#fef3c7">{ex.start}</Badge>
              </div>
            );
          })}
        </div>

        {/* Branch Overview */}
        <div style={{ background: "#fff", borderRadius: 16, padding: 24, border: "1px solid #f1f5f9", boxShadow: "0 1px 4px rgba(0,0,0,0.06)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: "#0f172a" }}>Branch Status</h3>
            <Layers size={18} color="#94a3b8" />
          </div>
          {BRANCHES.map(br => {
            const entries = timetable.filter(t => t.branch === br.id).length;
            const pct = Math.min(100, Math.round((entries / 18) * 100));
            return (
              <div key={br.id} style={{ marginBottom: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "#374151" }}>{br.code}</span>
                  <span style={{ fontSize: 12, color: "#64748b" }}>{entries} slots</span>
                </div>
                <div style={{ height: 7, background: "#f1f5f9", borderRadius: 10, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: `${pct}%`, background: "linear-gradient(90deg, #0ea5e9, #0369a1)", borderRadius: 10, transition: "width 0.8s ease" }} />
                </div>
              </div>
            );
          })}
        </div>

        {/* Faculty Workload */}
        <div style={{ background: "#fff", borderRadius: 16, padding: 24, border: "1px solid #f1f5f9", boxShadow: "0 1px 4px rgba(0,0,0,0.06)", gridColumn: "1/-1" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: "#0f172a" }}>Faculty Workload (Periods/Week)</h3>
            <BarChart3 size={18} color="#94a3b8" />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 12 }}>
            {FACULTY.slice(0, 10).map(f => {
              const periods = timetable.filter(t => t.faculty === f.id).length;
              const pct = Math.min(100, Math.round((periods / f.maxPeriodsWeek) * 100));
              const color = pct > 80 ? "#ef4444" : pct > 60 ? "#f59e0b" : "#10b981";
              return (
                <div key={f.id} style={{ textAlign: "center" }}>
                  <div style={{ fontSize: 11, color: "#64748b", marginBottom: 6, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.name.split(" ").slice(-1)[0]}</div>
                  <div style={{ height: 60, background: "#f8fafc", borderRadius: 8, display: "flex", alignItems: "flex-end", overflow: "hidden", justifyContent: "center" }}>
                    <div style={{ width: "60%", height: `${Math.max(8, pct)}%`, background: color, borderRadius: "4px 4px 0 0", transition: "height 0.8s ease" }} />
                  </div>
                  <div style={{ fontSize: 12, fontWeight: 700, color, marginTop: 4 }}>{periods}p</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── TIMETABLE GRID ──────────────────────────────────────────────────────────
function TimetableGrid({ timetable, setTimetable, user }) {
  const [selBranch, setSelBranch] = useState(1);
  const [selSem, setSelSem] = useState(3);
  const [dragEntry, setDragEntry] = useState(null);
  const [hovCell, setHovCell] = useState(null);
  const [modal, setModal] = useState(null); // { day, slot }
  const [form, setForm] = useState({ subject: "", faculty: "", room: "" });

  const canEdit = ["super_admin", "admin", "dept_admin"].includes(user.role);

  const filtered = timetable.filter(t => t.branch === selBranch && t.sem === selSem);

  const getCell = (day, slotId) => filtered.find(t => t.day === day && t.slot === slotId);

  const openAdd = (day, slotId) => {
    if (!canEdit) return;
    setModal({ day, slot: slotId });
    setForm({ subject: "", faculty: "", room: "" });
  };

  const saveEntry = () => {
    if (!form.subject || !form.faculty) return;
    // Conflict check
    const facConflict = timetable.find(t => t.faculty === +form.faculty && t.slot === modal.slot && t.day === modal.day && !(t.branch === selBranch && t.sem === selSem));
    const roomConflict = form.room ? timetable.find(t => t.room === +form.room && t.slot === modal.slot && t.day === modal.day && !(t.branch === selBranch && t.sem === selSem)) : false;
    if (facConflict) { alert("⚠️ Faculty clash detected! This faculty is already scheduled at this time."); return; }
    if (roomConflict) { alert("⚠️ Room clash detected! This room is already booked at this time."); return; }
    const newEntry = { id: Date.now(), branch: selBranch, sem: selSem, subject: +form.subject, faculty: +form.faculty, room: +form.room || null, slot: modal.slot, day: modal.day, year: "2025-26" };
    setTimetable(prev => [...prev, newEntry]);
    setModal(null);
  };

  const removeEntry = (id) => { setTimetable(prev => prev.filter(t => t.id !== id)); };

  const handleDrop = (day, slotId) => {
    if (!dragEntry || !canEdit) return;
    const slot = TIME_SLOTS.find(s => s.id === slotId);
    if (slot?.isBreak) return;
    setTimetable(prev => prev.map(t => t.id === dragEntry.id ? { ...t, day, slot: slotId } : t));
    setDragEntry(null); setHovCell(null);
  };

  const semList = SEMESTERS.filter(s => {
    if (BRANCHES.find(b => b.id === selBranch)?.lateral) return s.no >= 3;
    return true;
  });

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 }}>
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 800, color: "#0f172a", margin: 0 }}>Timetable Grid</h2>
          <p style={{ color: "#64748b", marginTop: 4, fontSize: 14 }}>Click empty cells to add · Drag entries to move · Delete with ×</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <select value={selBranch} onChange={e => setSelBranch(+e.target.value)} style={selStyle}>
            {BRANCHES.map(b => <option key={b.id} value={b.id}>{b.code}</option>)}
          </select>
          <select value={selSem} onChange={e => setSelSem(+e.target.value)} style={selStyle}>
            {semList.map(s => <option key={s.id} value={s.no}>Sem {s.no} ({s.type})</option>)}
          </select>
          <button style={{ padding: "8px 16px", background: "#0ea5e9", color: "#fff", border: "none", borderRadius: 8, cursor: "pointer", fontSize: 13, fontWeight: 600 }}
            onClick={() => { const csv = filtered.map(t => `${t.day},${TIME_SLOTS.find(s=>s.id===t.slot)?.label},${getSubject(t.subject)?.name},${getFaculty(t.faculty)?.name}`).join("\n"); const b = new Blob([`Day,Slot,Subject,Faculty\n${csv}`],{type:"text/csv"}); const a=document.createElement("a"); a.href=URL.createObjectURL(b); a.download="timetable.csv"; a.click(); }}>
            <Download size={14} style={{ marginRight: 6 }} />Export
          </button>
        </div>
      </div>

      <div style={{ overflowX: "auto", borderRadius: 16, boxShadow: "0 2px 12px rgba(0,0,0,0.08)", border: "1px solid #e2e8f0" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", background: "#fff", minWidth: 860 }}>
          <thead>
            <tr style={{ background: "#0f172a" }}>
              <th style={{ padding: "14px 18px", textAlign: "left", color: "#94a3b8", fontSize: 12, fontWeight: 700, letterSpacing: 0.8, width: 100 }}>TIME</th>
              {DAYS.map(d => <th key={d} style={{ padding: "14px 10px", textAlign: "center", color: "#e2e8f0", fontSize: 13, fontWeight: 700, letterSpacing: 0.5 }}>{d}</th>)}
            </tr>
          </thead>
          <tbody>
            {TIME_SLOTS.map((slot, si) => (
              <tr key={slot.id} style={{ background: slot.isBreak ? "#fafafa" : (si % 2 === 0 ? "#fff" : "#fafeff") }}>
                <td style={{ padding: "10px 18px", borderRight: "1px solid #f1f5f9", borderBottom: "1px solid #f1f5f9" }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: slot.isBreak ? "#94a3b8" : "#374151" }}>{slot.label}</div>
                  <div style={{ fontSize: 11, color: "#94a3b8" }}>{slot.start}–{slot.end}</div>
                </td>
                {DAYS.map(day => {
                  const entry = getCell(day, slot.id);
                  const isHov = hovCell?.day === day && hovCell?.slot === slot.id;
                  if (slot.isBreak) return (
                    <td key={day} style={{ borderBottom: "1px solid #f1f5f9", borderRight: "1px solid #f8fafc", background: "#f8f9fa", textAlign: "center" }}>
                      <span style={{ fontSize: 11, color: "#94a3b8", fontStyle: "italic" }}>Lunch Break</span>
                    </td>
                  );
                  const sub = entry ? getSubject(entry.subject) : null;
                  const fac = entry ? getFaculty(entry.faculty) : null;
                  return (
                    <td key={day} style={{ borderBottom: "1px solid #f1f5f9", borderRight: "1px solid #f8fafc", padding: 4, verticalAlign: "top", minHeight: 72 }}
                      onDragOver={e => { e.preventDefault(); setHovCell({ day, slot: slot.id }); }}
                      onDrop={() => handleDrop(day, slot.id)}
                      onDragLeave={() => setHovCell(null)}
                      onClick={() => !entry && openAdd(day, slot.id)}
                    >
                      {entry ? (
                        <div draggable={canEdit} onDragStart={() => setDragEntry(entry)}
                          style={{ background: typeBg[sub?.type] || "#f0f9ff", border: `1.5px solid ${typeColor[sub?.type] || "#0ea5e9"}`, borderRadius: 8, padding: "7px 8px", cursor: canEdit ? "grab" : "default", position: "relative", opacity: dragEntry?.id === entry.id ? 0.5 : 1 }}>
                          <div style={{ fontSize: 12, fontWeight: 700, color: typeColor[sub?.type] || "#0369a1", lineHeight: 1.2, marginBottom: 3, marginRight: 16 }}>{sub?.name}</div>
                          <div style={{ fontSize: 11, color: "#374151", fontWeight: 500 }}>{fac?.name.split(" ").slice(-2).join(" ")}</div>
                          <div style={{ fontSize: 10, color: "#64748b" }}>{sub?.code}</div>
                          {canEdit && (
                            <button onClick={e => { e.stopPropagation(); removeEntry(entry.id); }} style={{ position: "absolute", top: 4, right: 4, background: "none", border: "none", cursor: "pointer", padding: 2, color: "#94a3b8", lineHeight: 1 }}>
                              <X size={12} />
                            </button>
                          )}
                        </div>
                      ) : (
                        <div style={{ minHeight: 66, display: "flex", alignItems: "center", justifyContent: "center", opacity: isHov ? 1 : 0, transition: "opacity 0.2s", color: "#0ea5e9", fontSize: 20, cursor: "pointer" }}>
                          <Plus size={20} />
                        </div>
                      )}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Legend */}
      <div style={{ display: "flex", gap: 16, marginTop: 16 }}>
        {Object.entries(typeColor).map(([type, color]) => (
          <div key={type} style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <div style={{ width: 12, height: 12, borderRadius: 3, background: typeBg[type], border: `1.5px solid ${color}` }} />
            <span style={{ fontSize: 12, color: "#64748b", fontWeight: 500 }}>{type}</span>
          </div>
        ))}
      </div>

      {/* Add Entry Modal */}
      {modal && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.6)", zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div style={{ background: "#fff", borderRadius: 20, padding: 32, width: 420, boxShadow: "0 30px 80px rgba(0,0,0,0.3)" }}>
            <h3 style={{ margin: "0 0 6px", fontSize: 18, fontWeight: 800, color: "#0f172a" }}>Add Class Entry</h3>
            <p style={{ margin: "0 0 24px", fontSize: 13, color: "#64748b" }}>{modal.day} · {TIME_SLOTS.find(s => s.id === modal.slot)?.label}</p>
            <div style={{ marginBottom: 14 }}>
              <label style={lblStyle}>Subject</label>
              <select value={form.subject} onChange={e => setForm(f => ({ ...f, subject: e.target.value }))} style={{ ...selStyle, width: "100%", marginTop: 6 }}>
                <option value="">— Select Subject —</option>
                {SUBJECTS.filter(s => s.branch === selBranch && s.sem === selSem).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={lblStyle}>Faculty</label>
              <select value={form.faculty} onChange={e => setForm(f => ({ ...f, faculty: e.target.value }))} style={{ ...selStyle, width: "100%", marginTop: 6 }}>
                <option value="">— Select Faculty —</option>
                {FACULTY.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 24 }}>
              <label style={lblStyle}>Room (optional)</label>
              <select value={form.room} onChange={e => setForm(f => ({ ...f, room: e.target.value }))} style={{ ...selStyle, width: "100%", marginTop: 6 }}>
                <option value="">— Select Room —</option>
                {ROOMS.map(r => <option key={r.id} value={r.id}>{r.number} ({r.type}, cap {r.capacity})</option>)}
              </select>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <button onClick={() => setModal(null)} style={{ flex: 1, padding: "11px", background: "#f1f5f9", border: "none", borderRadius: 10, fontSize: 14, fontWeight: 600, cursor: "pointer", color: "#64748b" }}>Cancel</button>
              <button onClick={saveEntry} style={{ flex: 2, padding: "11px", background: "linear-gradient(135deg, #0ea5e9, #0369a1)", border: "none", borderRadius: 10, fontSize: 14, fontWeight: 700, cursor: "pointer", color: "#fff" }}>Add Entry</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── FACULTY MGMT ─────────────────────────────────────────────────────────────
function FacultyManagement({ timetable, user }) {
  const [search, setSearch] = useState("");
  const [faculty, setFaculty] = useState(FACULTY);
  const [modal, setModal] = useState(null);
  const [form, setForm] = useState({ name: "", designation: "Lecturer", dept: "", email: "", maxPeriodsWeek: 30 });

  const canEdit = ["super_admin", "admin"].includes(user.role);
  const filtered = faculty.filter(f => f.name.toLowerCase().includes(search.toLowerCase()) || f.dept.toLowerCase().includes(search.toLowerCase()));

  const openAdd = () => { setForm({ name: "", designation: "Lecturer", dept: "", email: "", maxPeriodsWeek: 30 }); setModal("add"); };
  const save = () => {
    if (modal === "add") setFaculty(prev => [...prev, { ...form, id: Date.now(), active: true, maxPeriodsWeek: +form.maxPeriodsWeek }]);
    setModal(null);
  };

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 }}>
        <div><h2 style={{ fontSize: 24, fontWeight: 800, color: "#0f172a", margin: 0 }}>Faculty Management</h2>
          <p style={{ color: "#64748b", marginTop: 4, fontSize: 14 }}>{faculty.length} faculty members registered</p></div>
        <div style={{ display: "flex", gap: 10 }}>
          <div style={{ position: "relative" }}>
            <Search size={15} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "#94a3b8" }} />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search faculty..." style={{ ...selStyle, paddingLeft: 36, width: 220 }} />
          </div>
          {canEdit && <button onClick={openAdd} style={{ padding: "9px 18px", background: "#0ea5e9", color: "#fff", border: "none", borderRadius: 8, cursor: "pointer", fontSize: 13, fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}><Plus size={15} />Add Faculty</button>}
        </div>
      </div>

      <div style={{ background: "#fff", borderRadius: 16, border: "1px solid #e2e8f0", overflow: "hidden", boxShadow: "0 1px 4px rgba(0,0,0,0.06)" }}>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead style={{ background: "#f8fafc" }}>
            <tr>
              {["Name", "Designation", "Department", "Email", "Max Periods/Wk", "Assigned", "Status", ""].map(h => (
                <th key={h} style={{ padding: "12px 16px", textAlign: "left", fontSize: 12, fontWeight: 700, color: "#64748b", letterSpacing: 0.5, borderBottom: "1px solid #f1f5f9" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map((f, i) => {
              const assigned = timetable.filter(t => t.faculty === f.id).length;
              const overload = assigned > f.maxPeriodsWeek;
              return (
                <tr key={f.id} style={{ borderBottom: "1px solid #f8fafc", transition: "background 0.15s" }} onMouseEnter={e => e.currentTarget.style.background = "#fafffe"} onMouseLeave={e => e.currentTarget.style.background = ""}>
                  <td style={{ padding: "13px 16px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <div style={{ width: 36, height: 36, borderRadius: 10, background: `hsl(${(f.id * 47) % 360}, 65%, 92%)`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 800, color: `hsl(${(f.id * 47) % 360}, 55%, 35%)` }}>
                        {f.name.split(" ").map(w => w[0]).join("").slice(0, 2)}
                      </div>
                      <span style={{ fontWeight: 700, color: "#0f172a", fontSize: 14 }}>{f.name}</span>
                    </div>
                  </td>
                  <td style={{ padding: "13px 16px" }}><Badge color="#6d28d9" bg="#ede9fe">{f.designation}</Badge></td>
                  <td style={{ padding: "13px 16px", fontSize: 13, color: "#374151" }}>{f.dept}</td>
                  <td style={{ padding: "13px 16px", fontSize: 13, color: "#64748b" }}>{f.email}</td>
                  <td style={{ padding: "13px 16px", fontSize: 14, fontWeight: 700, color: "#374151", textAlign: "center" }}>{f.maxPeriodsWeek}</td>
                  <td style={{ padding: "13px 16px", textAlign: "center" }}>
                    <span style={{ fontSize: 14, fontWeight: 700, color: overload ? "#ef4444" : "#10b981" }}>{assigned}</span>
                  </td>
                  <td style={{ padding: "13px 16px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      <div style={{ width: 8, height: 8, borderRadius: "50%", background: f.active ? "#10b981" : "#94a3b8" }} />
                      <span style={{ fontSize: 12, color: f.active ? "#10b981" : "#94a3b8", fontWeight: 600 }}>{f.active ? "Active" : "Inactive"}</span>
                    </div>
                  </td>
                  <td style={{ padding: "13px 16px" }}>
                    {canEdit && <button onClick={() => { setForm({ ...f }); setModal("edit"); }} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 6, padding: "5px 10px", cursor: "pointer", color: "#64748b", fontSize: 12 }}><Edit size={12} /></button>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {modal && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.6)", zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div style={{ background: "#fff", borderRadius: 20, padding: 32, width: 440, boxShadow: "0 30px 80px rgba(0,0,0,0.3)" }}>
            <h3 style={{ margin: "0 0 24px", fontSize: 18, fontWeight: 800, color: "#0f172a" }}>{modal === "add" ? "Add Faculty" : "Edit Faculty"}</h3>
            {[["Name","name","text"],["Department","dept","text"],["Email","email","email"]].map(([l, k, t]) => (
              <div key={k} style={{ marginBottom: 14 }}>
                <label style={lblStyle}>{l}</label>
                <input type={t} value={form[k]} onChange={e => setForm(f => ({ ...f, [k]: e.target.value }))} style={{ ...selStyle, width: "100%", marginTop: 6, boxSizing: "border-box" }} />
              </div>
            ))}
            <div style={{ marginBottom: 14 }}>
              <label style={lblStyle}>Designation</label>
              <select value={form.designation} onChange={e => setForm(f => ({ ...f, designation: e.target.value }))} style={{ ...selStyle, width: "100%", marginTop: 6 }}>
                {["Principal","H.O.D","Lecturer","Instructor","Workshop Superintendent"].map(d => <option key={d}>{d}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 24 }}>
              <label style={lblStyle}>Max Periods/Week</label>
              <input type="number" value={form.maxPeriodsWeek} onChange={e => setForm(f => ({ ...f, maxPeriodsWeek: e.target.value }))} style={{ ...selStyle, width: "100%", marginTop: 6, boxSizing: "border-box" }} />
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <button onClick={() => setModal(null)} style={{ flex: 1, padding: "11px", background: "#f1f5f9", border: "none", borderRadius: 10, fontSize: 14, fontWeight: 600, cursor: "pointer", color: "#64748b" }}>Cancel</button>
              <button onClick={save} style={{ flex: 2, padding: "11px", background: "linear-gradient(135deg, #0ea5e9, #0369a1)", border: "none", borderRadius: 10, fontSize: 14, fontWeight: 700, cursor: "pointer", color: "#fff" }}>Save</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── SUBJECTS ────────────────────────────────────────────────────────────────
function SubjectsPage({ user }) {
  const [selBranch, setSelBranch] = useState(1);
  const [selSem, setSelSem] = useState(3);
  const filtered = SUBJECTS.filter(s => s.branch === selBranch && s.sem === selSem);
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 }}>
        <div><h2 style={{ fontSize: 24, fontWeight: 800, color: "#0f172a", margin: 0 }}>Subject Management</h2>
          <p style={{ color: "#64748b", marginTop: 4, fontSize: 14 }}>Curriculum configuration per branch & semester</p></div>
        <div style={{ display: "flex", gap: 10 }}>
          <select value={selBranch} onChange={e => setSelBranch(+e.target.value)} style={selStyle}>{BRANCHES.map(b => <option key={b.id} value={b.id}>{b.code}</option>)}</select>
          <select value={selSem} onChange={e => setSelSem(+e.target.value)} style={selStyle}>{SEMESTERS.map(s => <option key={s.id} value={s.no}>Sem {s.no}</option>)}</select>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
        {filtered.length ? filtered.map(s => (
          <div key={s.id} style={{ background: "#fff", borderRadius: 14, padding: 20, border: `2px solid ${typeBg[s.type]}`, boxShadow: "0 1px 4px rgba(0,0,0,0.05)" }}>
            <div style={{ display: "flex", alignItems: "start", justifyContent: "space-between", marginBottom: 12 }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: 0.8, marginBottom: 4 }}>{s.code}</div>
                <div style={{ fontSize: 15, fontWeight: 800, color: "#0f172a", lineHeight: 1.3 }}>{s.name}</div>
              </div>
              <Badge color={typeColor[s.type]} bg={typeBg[s.type]}>{s.type}</Badge>
            </div>
            <div style={{ display: "flex", gap: 16 }}>
              <div style={{ textAlign: "center" }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: "#0f172a" }}>{s.credits}</div>
                <div style={{ fontSize: 11, color: "#64748b" }}>Credits</div>
              </div>
              <div style={{ textAlign: "center" }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: "#0f172a" }}>{s.periodsWeek}</div>
                <div style={{ fontSize: 11, color: "#64748b" }}>Periods/Wk</div>
              </div>
            </div>
          </div>
        )) : (
          <div style={{ gridColumn: "1/-1", textAlign: "center", padding: 60, color: "#94a3b8" }}>
            <BookOpen size={40} style={{ marginBottom: 12 }} />
            <div style={{ fontSize: 16, fontWeight: 600 }}>No subjects configured for this combination</div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── EXAM SCHEDULE ───────────────────────────────────────────────────────────
function ExamSchedule() {
  const [exams, setExams] = useState(EXAMS);
  const [modal, setModal] = useState(false);
  const [form, setForm] = useState({ name: "First Sessional", branch: 1, subject: 1, date: "", start: "10:00", end: "12:00", room: 1 });

  const save = () => {
    setExams(prev => [...prev, { ...form, id: Date.now(), branch: +form.branch, subject: +form.subject, room: +form.room }]);
    setModal(false);
  };

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 }}>
        <div><h2 style={{ fontSize: 24, fontWeight: 800, color: "#0f172a", margin: 0 }}>Examination Schedule</h2>
          <p style={{ color: "#64748b", marginTop: 4, fontSize: 14 }}>Sessional exam management & calendar</p></div>
        <button onClick={() => setModal(true)} style={{ padding: "9px 18px", background: "#0ea5e9", color: "#fff", border: "none", borderRadius: 8, cursor: "pointer", fontSize: 13, fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}><Plus size={15} />Schedule Exam</button>
      </div>

      {["First Sessional", "Second Sessional", "Third Sessional"].map(sessional => {
        const sessExams = exams.filter(e => e.name === sessional);
        return (
          <div key={sessional} style={{ marginBottom: 28 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
              <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800, color: "#0f172a" }}>{sessional}</h3>
              <div style={{ height: 1, flex: 1, background: "#f1f5f9" }} />
              <span style={{ fontSize: 12, color: "#64748b" }}>{sessExams.length} exams</span>
            </div>
            {sessExams.length ? (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12 }}>
                {sessExams.map(ex => {
                  const sub = getSubject(ex.subject);
                  const br = BRANCHES.find(b => b.id === ex.branch);
                  const room = getRoom(ex.room);
                  const d = new Date(ex.date);
                  return (
                    <div key={ex.id} style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 12, padding: 18, boxShadow: "0 1px 4px rgba(0,0,0,0.05)" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 12 }}>
                        <div style={{ width: 48, height: 48, borderRadius: 12, background: "#fef3c7", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                          <span style={{ fontSize: 15, fontWeight: 800, color: "#d97706" }}>{d.getDate()}</span>
                          <span style={{ fontSize: 10, color: "#d97706", fontWeight: 700 }}>{d.toLocaleString("default",{month:"short"}).toUpperCase()}</span>
                        </div>
                        <div>
                          <div style={{ fontSize: 14, fontWeight: 800, color: "#0f172a" }}>{sub?.name}</div>
                          <div style={{ fontSize: 12, color: "#64748b" }}>{br?.code} · {room?.number}</div>
                        </div>
                      </div>
                      <div style={{ display: "flex", gap: 8 }}>
                        <Badge color="#0369a1" bg="#e0f2fe">{ex.start} – {ex.end}</Badge>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : <div style={{ background: "#f8fafc", borderRadius: 12, padding: "24px", textAlign: "center", color: "#94a3b8", fontSize: 14 }}>No exams scheduled</div>}
          </div>
        );
      })}

      {modal && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.6)", zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div style={{ background: "#fff", borderRadius: 20, padding: 32, width: 440, boxShadow: "0 30px 80px rgba(0,0,0,0.3)" }}>
            <h3 style={{ margin: "0 0 24px", fontSize: 18, fontWeight: 800 }}>Schedule Exam</h3>
            <div style={{ marginBottom: 14 }}>
              <label style={lblStyle}>Sessional</label>
              <select value={form.name} onChange={e => setForm(f => ({...f, name: e.target.value}))} style={{...selStyle, width:"100%", marginTop:6}}>
                {["First Sessional","Second Sessional","Third Sessional"].map(n => <option key={n}>{n}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={lblStyle}>Branch</label>
              <select value={form.branch} onChange={e => setForm(f=>({...f,branch:e.target.value}))} style={{...selStyle,width:"100%",marginTop:6}}>
                {BRANCHES.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={lblStyle}>Subject</label>
              <select value={form.subject} onChange={e => setForm(f=>({...f,subject:e.target.value}))} style={{...selStyle,width:"100%",marginTop:6}}>
                {SUBJECTS.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:10, marginBottom:14 }}>
              <div><label style={lblStyle}>Date</label><input type="date" value={form.date} onChange={e=>setForm(f=>({...f,date:e.target.value}))} style={{...selStyle,width:"100%",marginTop:6,boxSizing:"border-box"}} /></div>
              <div><label style={lblStyle}>Start</label><input type="time" value={form.start} onChange={e=>setForm(f=>({...f,start:e.target.value}))} style={{...selStyle,width:"100%",marginTop:6,boxSizing:"border-box"}} /></div>
              <div><label style={lblStyle}>End</label><input type="time" value={form.end} onChange={e=>setForm(f=>({...f,end:e.target.value}))} style={{...selStyle,width:"100%",marginTop:6,boxSizing:"border-box"}} /></div>
            </div>
            <div style={{ marginBottom: 24 }}>
              <label style={lblStyle}>Room</label>
              <select value={form.room} onChange={e => setForm(f=>({...f,room:e.target.value}))} style={{...selStyle,width:"100%",marginTop:6}}>
                {ROOMS.map(r => <option key={r.id} value={r.id}>{r.number}</option>)}
              </select>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <button onClick={() => setModal(false)} style={{ flex:1, padding:"11px", background:"#f1f5f9", border:"none", borderRadius:10, fontSize:14, fontWeight:600, cursor:"pointer", color:"#64748b" }}>Cancel</button>
              <button onClick={save} style={{ flex:2, padding:"11px", background:"linear-gradient(135deg, #0ea5e9, #0369a1)", border:"none", borderRadius:10, fontSize:14, fontWeight:700, cursor:"pointer", color:"#fff" }}>Schedule</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── CLASSROOMS ──────────────────────────────────────────────────────────────
function ClassroomsPage() {
  const typeColors = { Lecture: ["#0369a1","#e0f2fe"], Lab: ["#166534","#dcfce7"], Workshop: ["#c2410c","#ffedd5"], "Drawing Hall": ["#6d28d9","#ede9fe"] };
  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ fontSize: 24, fontWeight: 800, color: "#0f172a", margin: 0 }}>Classroom & Resource Management</h2>
        <p style={{ color: "#64748b", marginTop: 4, fontSize: 14 }}>{ROOMS.filter(r=>r.active).length} active rooms registered</p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
        {ROOMS.map(r => {
          const [tc, bc] = typeColors[r.type] || ["#374151","#f1f5f9"];
          return (
            <div key={r.id} style={{ background: "#fff", borderRadius: 16, padding: 24, border: "1px solid #f1f5f9", boxShadow: "0 1px 4px rgba(0,0,0,0.05)" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
                <div style={{ width: 44, height: 44, borderRadius: 12, background: bc, display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Building2 size={20} color={tc} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <div style={{ width: 8, height: 8, borderRadius: "50%", background: r.active ? "#10b981" : "#94a3b8" }} />
                  <span style={{ fontSize: 12, color: r.active ? "#10b981" : "#94a3b8", fontWeight: 600 }}>{r.active ? "Active" : "Inactive"}</span>
                </div>
              </div>
              <div style={{ fontSize: 20, fontWeight: 800, color: "#0f172a", marginBottom: 4 }}>{r.number}</div>
              <Badge color={tc} bg={bc}>{r.type}</Badge>
              <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid #f1f5f9", display: "flex", alignItems: "center", gap: 6 }}>
                <Users size={14} color="#94a3b8" />
                <span style={{ fontSize: 13, color: "#64748b" }}>Capacity: <b style={{ color: "#374151" }}>{r.capacity}</b></span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── REPORTS ─────────────────────────────────────────────────────────────────
function ReportsPage({ timetable }) {
  const downloadCSV = (name, rows, headers) => {
    const csv = [headers.join(","), ...rows].join("\n");
    const b = new Blob([csv],{type:"text/csv"});
    const a = document.createElement("a"); a.href=URL.createObjectURL(b); a.download=`${name}.csv`; a.click();
  };

  const reports = [
    {
      title: "Branch Timetable", icon: Grid3X3, color: "#0ea5e9", bg: "#e0f2fe",
      desc: "Complete timetable per branch and semester",
      action: () => {
        const rows = timetable.map(t => [
          BRANCHES.find(b=>b.id===t.branch)?.code, `Sem ${t.sem}`, t.day,
          TIME_SLOTS.find(s=>s.id===t.slot)?.label,
          getSubject(t.subject)?.name, getFaculty(t.faculty)?.name, getRoom(t.room)?.number||"N/A"
        ].join(","));
        downloadCSV("branch_timetable", rows, ["Branch","Semester","Day","Slot","Subject","Faculty","Room"]);
      }
    },
    {
      title: "Faculty Workload", icon: BarChart3, color: "#8b5cf6", bg: "#ede9fe",
      desc: "Periods assigned per faculty per week",
      action: () => {
        const rows = FACULTY.map(f => {
          const periods = timetable.filter(t=>t.faculty===f.id).length;
          return [f.name, f.designation, f.dept, periods, f.maxPeriodsWeek, periods > f.maxPeriodsWeek ? "OVERLOAD" : "OK"].join(",");
        });
        downloadCSV("faculty_workload", rows, ["Name","Designation","Dept","Assigned Periods","Max Periods","Status"]);
      }
    },
    {
      title: "Exam Schedule", icon: CalendarDays, color: "#f59e0b", bg: "#fef3c7",
      desc: "All sessional examination dates and rooms",
      action: () => {
        const rows = EXAMS.map(e => [e.name, BRANCHES.find(b=>b.id===e.branch)?.code, getSubject(e.subject)?.name, e.date, e.start, e.end, getRoom(e.room)?.number].join(","));
        downloadCSV("exam_schedule", rows, ["Sessional","Branch","Subject","Date","Start","End","Room"]);
      }
    },
    {
      title: "Subject Coverage", icon: BookMarked, color: "#10b981", bg: "#dcfce7",
      desc: "Branch-wise subject allocation report",
      action: () => {
        const rows = SUBJECTS.map(s => [BRANCHES.find(b=>b.id===s.branch)?.code, `Sem ${s.sem}`, s.code, s.name, s.type, s.credits, s.periodsWeek].join(","));
        downloadCSV("subject_coverage", rows, ["Branch","Semester","Code","Subject","Type","Credits","Periods/Wk"]);
      }
    },
    {
      title: "Room Utilization", icon: Building2, color: "#ef4444", bg: "#fee2e2",
      desc: "Classroom usage statistics",
      action: () => {
        const rows = ROOMS.map(r => {
          const used = timetable.filter(t=>t.room===r.id).length;
          const total = DAYS.length * TIME_SLOTS.filter(s=>!s.isBreak).length;
          return [r.number, r.type, r.capacity, used, total, `${Math.round(used/total*100)}%`].join(",");
        });
        downloadCSV("room_utilization", rows, ["Room","Type","Capacity","Slots Used","Total Slots","Utilization"]);
      }
    },
    {
      title: "Full Timetable Export", icon: FileText, color: "#64748b", bg: "#f1f5f9",
      desc: "Complete raw data export (all entries)",
      action: () => {
        const rows = timetable.map(t=>[t.id,BRANCHES.find(b=>b.id===t.branch)?.code,t.sem,t.day,TIME_SLOTS.find(s=>s.id===t.slot)?.label,getSubject(t.subject)?.name||t.subject,getFaculty(t.faculty)?.name||t.faculty,getRoom(t.room)?.number||""].join(","));
        downloadCSV("full_timetable", rows, ["ID","Branch","Sem","Day","Slot","Subject","Faculty","Room"]);
      }
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ fontSize: 24, fontWeight: 800, color: "#0f172a", margin: 0 }}>Reports & Export</h2>
        <p style={{ color: "#64748b", marginTop: 4, fontSize: 14 }}>Download reports in CSV format</p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
        {reports.map(r => (
          <div key={r.title} style={{ background: "#fff", borderRadius: 16, padding: 24, border: "1px solid #f1f5f9", boxShadow: "0 1px 4px rgba(0,0,0,0.05)", display: "flex", flexDirection: "column" }}>
            <div style={{ width: 48, height: 48, borderRadius: 12, background: r.bg, display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
              <r.icon size={22} color={r.color} />
            </div>
            <div style={{ fontSize: 16, fontWeight: 800, color: "#0f172a", marginBottom: 6 }}>{r.title}</div>
            <div style={{ fontSize: 13, color: "#64748b", flex: 1, marginBottom: 20 }}>{r.desc}</div>
            <button onClick={r.action} style={{ padding: "10px 16px", background: r.bg, border: `1.5px solid ${r.color}30`, borderRadius: 10, color: r.color, fontWeight: 700, fontSize: 13, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, transition: "all 0.2s" }}
              onMouseEnter={e=>{e.currentTarget.style.background=r.color; e.currentTarget.style.color="#fff";}}
              onMouseLeave={e=>{e.currentTarget.style.background=r.bg; e.currentTarget.style.color=r.color;}}>
              <Download size={15} />Download CSV
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── SHARED STYLES ────────────────────────────────────────────────────────────
const selStyle = { padding: "8px 14px", border: "1.5px solid #e2e8f0", borderRadius: 8, fontSize: 13, outline: "none", background: "#fff", color: "#374151", cursor: "pointer" };
const lblStyle = { fontSize: 11, fontWeight: 700, color: "#374151", letterSpacing: 0.6, textTransform: "uppercase" };

// ─── SIDEBAR ──────────────────────────────────────────────────────────────────
const NAV = [
  { id: "dashboard", label: "Dashboard", icon: LayoutDashboard },
  { id: "timetable", label: "Timetable Grid", icon: Grid3X3 },
  { id: "faculty", label: "Faculty", icon: Users },
  { id: "subjects", label: "Subjects", icon: BookOpen },
  { id: "exams", label: "Exam Schedule", icon: CalendarDays },
  { id: "rooms", label: "Classrooms", icon: Building2 },
  { id: "reports", label: "Reports", icon: FileText },
];

// ─── MAIN APP ─────────────────────────────────────────────────────────────────
export default function App() {
  const [user, setUser] = useState(null);
  const [page, setPage] = useState("dashboard");
  const [timetable, setTimetable] = useState(INITIAL_TIMETABLE);
  const [sideCollapsed, setSideCollapsed] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);

  if (!user) return <LoginPage onLogin={setUser} />;

  const roleLabel = { super_admin: "Super Admin", admin: "Admin", dept_admin: "Dept. Admin", faculty: "Faculty", student: "Student" };

  return (
    <div style={{ display: "flex", height: "100vh", fontFamily: "'Segoe UI', system-ui, sans-serif", background: "#f8fafc", overflow: "hidden" }}>
      {/* SIDEBAR */}
      <div style={{ width: sideCollapsed ? 68 : 240, background: "#0f172a", display: "flex", flexDirection: "column", transition: "width 0.25s ease", flexShrink: 0, overflow: "hidden" }}>
        <div style={{ padding: sideCollapsed ? "20px 0" : "20px 20px", display: "flex", alignItems: "center", gap: 12, borderBottom: "1px solid rgba(255,255,255,0.08)", justifyContent: sideCollapsed ? "center" : "flex-start" }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "linear-gradient(135deg, #0ea5e9, #0369a1)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <GraduationCap size={18} color="#fff" />
          </div>
          {!sideCollapsed && <div>
            <div style={{ fontSize: 14, fontWeight: 800, color: "#f8fafc", letterSpacing: -0.3 }}>TimetableERP</div>
            <div style={{ fontSize: 10, color: "#64748b", fontWeight: 600 }}>Classroom Management</div>
          </div>}
        </div>

        <nav style={{ flex: 1, padding: "16px 0", overflowY: "auto" }}>
          {NAV.map(n => {
            const active = page === n.id;
            return (
              <button key={n.id} onClick={() => setPage(n.id)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, padding: sideCollapsed ? "12px 0" : "11px 20px", justifyContent: sideCollapsed ? "center" : "flex-start", background: active ? "rgba(14,165,233,0.15)" : "none", border: "none", cursor: "pointer", color: active ? "#0ea5e9" : "#94a3b8", fontSize: 14, fontWeight: active ? 700 : 500, transition: "all 0.15s", borderLeft: active ? "3px solid #0ea5e9" : "3px solid transparent" }}>
                <n.icon size={18} />
                {!sideCollapsed && n.label}
              </button>
            );
          })}
        </nav>

        <div style={{ padding: sideCollapsed ? "16px 0" : "16px 20px", borderTop: "1px solid rgba(255,255,255,0.08)" }}>
          {!sideCollapsed && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <div style={{ width: 34, height: 34, borderRadius: 9, background: "linear-gradient(135deg, #6d28d9, #4c1d95)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 800, color: "#fff" }}>
                {user.name.split(" ").map(w=>w[0]).join("").slice(0,2)}
              </div>
              <div>
                <div style={{ fontSize: 12, fontWeight: 700, color: "#e2e8f0" }}>{user.name}</div>
                <div style={{ fontSize: 11, color: "#64748b" }}>{roleLabel[user.role]}</div>
              </div>
            </div>
          )}
          <button onClick={() => setUser(null)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, padding: sideCollapsed ? "10px 0" : "10px 12px", justifyContent: sideCollapsed ? "center" : "flex-start", background: "rgba(239,68,68,0.1)", border: "none", borderRadius: 8, cursor: "pointer", color: "#ef4444", fontSize: 13, fontWeight: 600 }}>
            <LogOut size={16} />
            {!sideCollapsed && "Sign Out"}
          </button>
        </div>
      </div>

      {/* MAIN AREA */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        {/* TOPBAR */}
        <div style={{ height: 60, background: "#fff", borderBottom: "1px solid #f1f5f9", display: "flex", alignItems: "center", padding: "0 24px", gap: 16, flexShrink: 0 }}>
          <button onClick={() => setSideCollapsed(c => !c)} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 8, padding: "7px 10px", cursor: "pointer", color: "#64748b" }}>
            <Menu size={16} />
          </button>
          <div style={{ flex: 1 }} />
          <div style={{ fontSize: 13, color: "#94a3b8", fontWeight: 500 }}>AY 2025–26 · ODD Semester</div>
          <div style={{ position: "relative" }}>
            <button onClick={() => setNotifOpen(o=>!o)} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 8, padding: "7px 10px", cursor: "pointer", color: "#64748b", position: "relative" }}>
              <Bell size={16} />
              <div style={{ position: "absolute", top: 6, right: 8, width: 7, height: 7, borderRadius: "50%", background: "#ef4444", border: "2px solid #fff" }} />
            </button>
            {notifOpen && (
              <div style={{ position: "absolute", right: 0, top: 44, width: 300, background: "#fff", borderRadius: 14, border: "1px solid #f1f5f9", boxShadow: "0 20px 60px rgba(0,0,0,0.15)", zIndex: 50, padding: 16 }}>
                <div style={{ fontSize: 14, fontWeight: 800, color: "#0f172a", marginBottom: 12 }}>Notifications</div>
                {[
                  { msg: "First Sessional starts March 10", type: "warn" },
                  { msg: "CE Sem-3 timetable updated", type: "info" },
                  { msg: "Faculty S. Patel approaching workload limit", type: "warn" },
                ].map((n, i) => (
                  <div key={i} style={{ display: "flex", gap: 10, padding: "10px 0", borderBottom: "1px solid #f8fafc" }}>
                    <div style={{ width: 8, height: 8, borderRadius: "50%", background: n.type === "warn" ? "#f59e0b" : "#0ea5e9", marginTop: 4, flexShrink: 0 }} />
                    <span style={{ fontSize: 13, color: "#374151" }}>{n.msg}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* PAGE CONTENT */}
        <div style={{ flex: 1, overflow: "auto", padding: 28 }}>
          {page === "dashboard" && <Dashboard timetable={timetable} user={user} />}
          {page === "timetable" && <TimetableGrid timetable={timetable} setTimetable={setTimetable} user={user} />}
          {page === "faculty" && <FacultyManagement timetable={timetable} user={user} />}
          {page === "subjects" && <SubjectsPage user={user} />}
          {page === "exams" && <ExamSchedule />}
          {page === "rooms" && <ClassroomsPage />}
          {page === "reports" && <ReportsPage timetable={timetable} />}
        </div>
      </div>

      {/* Click outside notif */}
      {notifOpen && <div style={{ position: "fixed", inset: 0, zIndex: 49 }} onClick={() => setNotifOpen(false)} />}
    </div>
  );
}