import React, { useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
import { AnimatePresence, motion } from "framer-motion";
import {
  Bell,
  Building2,
  Camera,
  CalendarDays,
  Check,
  ChevronRight,
  Clock3,
  CreditCard,
  Download,
  FileText,
  HeartPulse,
  Home,
  LogOut,
  MapPin,
  Menu,
  Plus,
  QrCode,
  Search,
  Settings,
  ShieldCheck,
  Users,
  X,
} from "lucide-react";
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from "react-router-dom";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import "./index.css";

const API_BASE = import.meta.env.VITE_API_BASE || "";
const appVersion = "NeverLag Work v1.0.0";

const demoUsers = [
  { label: "Super Admin", username: "super", password: "admin123" },
  { label: "Company Admin / Boss", username: "boss", password: "boss123" },
  { label: "Branch Manager", username: "manager", password: "manager123" },
  { label: "Employee", username: "employee", password: "employee123" },
  { label: "QR/Selfie Test Employee", username: "tester", password: "tester123" },
];

const navByRole = {
  super_admin: [
    ["Home", Home],
    ["Companies", Building2],
    ["Plans", CreditCard],
    ["Reports", FileText],
    ["More", Menu],
  ],
  boss: [
    ["Home", Home],
    ["Branches", Building2],
    ["Employees", Users],
    ["Attendance", CalendarDays],
    ["Salary", CreditCard],
    ["More", Menu],
  ],
  branch_manager: [
    ["Home", Home],
    ["Employees", Users],
    ["Attendance", CalendarDays],
    ["Salary", CreditCard],
    ["More", Menu],
  ],
  employee: [
    ["Home", Home],
    ["Attendance", CalendarDays],
    ["Salary Slip", FileText],
    ["Notifications", Bell],
    ["Profile", Users],
  ],
};

function getNavForRole(role, showBranchTools) {
  const nav = navByRole[role] || [];
  if (!showBranchTools) return nav.filter(([name]) => name !== "Branches");
  return nav;
}

const statColors = {
  green: "bg-blue-50 text-primary",
  blue: "bg-blue-50 text-blue-700",
  orange: "bg-orange-50 text-orange-700",
  red: "bg-red-50 text-red-700",
  gray: "bg-slate-100 text-slate-600",
};

function HeroIcon({ name, className = "h-6 w-6" }) {
  const paths = {
    speed: "M3.75 13.5a8.25 8.25 0 1 1 16.5 0c0 2.1-.78 4.02-2.07 5.48a.75.75 0 0 1-.56.25H6.38a.75.75 0 0 1-.56-.25A8.22 8.22 0 0 1 3.75 13.5Zm8.25 0 3.75-4.5",
    shield: "M12 3.75 5.25 6v5.08c0 4.18 2.8 7.84 6.75 8.92 3.95-1.08 6.75-4.74 6.75-8.92V6L12 3.75Z",
    cloud: "M6.75 18.75h10.5a4.5 4.5 0 0 0 .5-8.97 6 6 0 0 0-11.44-1.66A5.25 5.25 0 0 0 6.75 18.75Z",
    lock: "M7.5 10.5V8.25a4.5 4.5 0 0 1 9 0v2.25m-10.5 0h12a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-.75.75h-12a.75.75 0 0 1-.75-.75v-7.5a.75.75 0 0 1 .75-.75Z",
  };
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" className={className}>
      <path d={paths[name] || paths.shield} />
    </svg>
  );
}

async function api(path, options = {}) {
  const token = sessionStorage.getItem("authToken");
  const res = await fetch(`${API_BASE}${path}`, {
    method: options.method || "GET",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: options.body ? JSON.stringify(options.body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || "Data was not saved. Please check server/database connection.");
  return data;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/*" element={<Shell />} />
      </Routes>
    </BrowserRouter>
  );
}

function Login() {
  const navigate = useNavigate();
  const [form, setForm] = useState({ username: "boss", password: "boss123" });
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function submit(event) {
    event.preventDefault();
    setLoading(true);
    setError("");
    try {
      const data = await api("/api/auth/login", { method: "POST", body: form });
      sessionStorage.setItem("authToken", data.token);
      sessionStorage.setItem("currentUser", JSON.stringify(data.user));
      navigate("/");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="min-h-screen overflow-hidden bg-[radial-gradient(circle_at_18%_16%,rgba(32,108,243,0.15),transparent_26%),radial-gradient(circle_at_88%_14%,rgba(255,0,128,0.10),transparent_24%),#fbfbfd] px-4 py-8 text-navy sm:px-6 lg:px-8">
      <div className="mx-auto flex min-h-[calc(100vh-4rem)] max-w-7xl items-center justify-center">
        <div className="grid w-full gap-8 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-center">
          <motion.section initial={{ opacity: 0, y: -24 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.25 }} className="space-y-6">
            <div className="flex h-16 w-16 items-center justify-center rounded-[1.25rem] bg-white text-primary shadow-glow ring-1 ring-line">
              <HeroIcon name="shield" className="h-8 w-8" />
            </div>
            <div>
              <h1 className="gradient-text max-w-3xl text-[42px] font-semibold leading-[1.02] tracking-[-0.04em] sm:text-6xl lg:text-7xl">NeverLag Work</h1>
              <p className="mt-6 max-w-xl text-lg leading-8 text-muted">Employee Attendance & Payroll SaaS</p>
            </div>
            <div className="grid gap-4 sm:grid-cols-3">
              {[
                ["Speed", "Live attendance flow", "speed"],
                ["Security", "GPS, selfie, QR checks", "lock"],
                ["Cloud", "Branch-ready SaaS", "cloud"],
              ].map(([title, meta, icon]) => (
                <div key={title} className="app-card premium-glow p-5">
                  <HeroIcon name={icon} className="h-6 w-6 text-primary" />
                  <strong className="mt-4 block font-medium">{title}</strong>
                  <span className="mt-1 block text-sm text-muted">{meta}</span>
                </div>
              ))}
            </div>
          </motion.section>

          <motion.form
            onSubmit={submit}
            initial={{ opacity: 0, y: 26 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.25, delay: 0.08 }}
            className="app-card premium-glow p-6 sm:p-8"
          >
            <div className="mb-6">
              <h2 className="text-2xl font-semibold tracking-[-0.04em]">Login</h2>
              <p className="text-sm text-muted">Role is detected after login.</p>
            </div>
            <div className="space-y-4">
              <AnimatedField label="Username" value={form.username} onChange={(value) => setForm({ ...form, username: value })} />
              <AnimatedField label="Password" type="password" value={form.password} onChange={(value) => setForm({ ...form, password: value })} />
            </div>
            {error && <p className="mt-3 rounded-2xl bg-red-50 px-3 py-2 text-sm font-medium text-danger">{error}</p>}
            <motion.button whileTap={{ scale: 0.96 }} className="primary-pill mt-6 w-full">
              {loading ? "Signing in..." : "Login"}
            </motion.button>
            <div className="mt-5 grid gap-2">
              {demoUsers.map((user) => (
                <button
                  type="button"
                  key={user.username}
                  onClick={() => setForm({ username: user.username, password: user.password })}
                  className="secondary-pill justify-between text-left text-sm"
                >
                  <span>{user.label}</span>
                  <ChevronRight className="h-4 w-4 text-primary" />
                </button>
              ))}
            </div>
          </motion.form>
        </div>
      </div>
    </main>
  );
}

function AnimatedField({ label, type = "text", value, onChange }) {
  return (
    <motion.label initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} className="block">
      <span className="mb-2 block text-sm font-medium text-muted">{label}</span>
      <input
        className="min-h-12 w-full rounded-full border border-line bg-white px-4 font-medium text-navy outline-none ring-primary/20 focus:ring-4"
        type={type}
        value={value}
        onChange={(event) => onChange(event.target.value)}
      />
    </motion.label>
  );
}

function Shell() {
  const navigate = useNavigate();
  const [user, setUser] = useState(() => safeJson(sessionStorage.getItem("currentUser")));
  const [active, setActive] = useState("Home");
  const [data, setData] = useState(null);
  const [toast, setToast] = useState("");
  const [showNotifications, setShowNotifications] = useState(false);
  const showBranchTools = Boolean(data?.settings?.enableMultiBranch);
  const nav = getNavForRole(user?.role, showBranchTools);

  useEffect(() => {
    if (!sessionStorage.getItem("authToken")) navigate("/login");
  }, [navigate]);

  useEffect(() => {
    if (!user) return;
    refresh().catch((err) => setToast(err.message));
  }, [user]);

  useEffect(() => {
    if (active === "Branches" && !showBranchTools) setActive("Home");
  }, [active, showBranchTools]);

  async function refresh() {
    const [me, attendance, slips, notifications, settings] = await Promise.all([
      api("/api/auth/me"),
      api("/api/employee-attendance/today"),
      api("/api/employee-salary/slips"),
      api("/api/notifications"),
      ["boss", "branch_manager", "employee"].includes(user.role) ? api("/api/company/settings") : Promise.resolve({}),
    ]);
    setUser(me.user);
    sessionStorage.setItem("currentUser", JSON.stringify(me.user));
    setData({ attendance, slips, notifications, settings });
  }

  async function logout() {
    await api("/api/auth/logout", { method: "POST" }).catch(() => null);
    sessionStorage.removeItem("authToken");
    sessionStorage.removeItem("currentUser");
    navigate("/login");
  }

  if (!user) return null;

  return (
    <div className="min-h-screen bg-surface text-navy">
      <aside className="fixed inset-y-0 left-0 hidden w-72 border-r border-line bg-white p-6 text-navy shadow-premium lg:block">
        <Brand />
        <nav className="mt-10 space-y-2">
          {nav.map(([name, Icon]) => (
            <NavButton key={name} name={name} Icon={Icon} active={active === name} onClick={() => setActive(name)} />
          ))}
        </nav>
        <div className="absolute bottom-6 left-6 right-6 rounded-[1.25rem] border border-line bg-surface p-4 text-sm text-muted">{appVersion}</div>
      </aside>

      <main className="pb-24 lg:ml-72 lg:pb-0">
        <header className="sticky top-0 z-20 border-b border-line bg-white/85 px-4 backdrop-blur-xl lg:px-8">
          <div className="mx-auto flex h-20 max-w-7xl items-center justify-between">
          <div>
            <p className="text-sm font-medium text-muted">Good morning, {user.name}</p>
            <h1 className="text-xl font-semibold tracking-[-0.04em]">{active}</h1>
          </div>
          <div className="flex items-center gap-2">
            <motion.button type="button" onClick={() => setShowNotifications(true)} whileTap={{ scale: 0.96 }} animate={data?.notifications?.unread ? { scale: [1, 1.08, 1] } : {}} className="relative min-h-11 min-w-11 rounded-full bg-white p-3 text-primary shadow-premium transition hover:-translate-y-0.5 hover:shadow-lift">
              <Bell className="h-5 w-5" />
              {data?.notifications?.unread > 0 && <span className="absolute right-2 top-2 h-2.5 w-2.5 rounded-full bg-danger" />}
            </motion.button>
            <button onClick={logout} className="min-h-11 min-w-11 rounded-full bg-primary p-3 text-white shadow-lift transition hover:-translate-y-0.5 hover:bg-[#74a2f7]">
              <LogOut className="h-5 w-5" />
            </button>
          </div>
          </div>
        </header>

        <AnimatePresence mode="wait">
          <motion.section key={active} initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -12 }} transition={{ duration: 0.25 }} className="mx-auto max-w-7xl p-4 sm:p-6 lg:p-8">
            {renderPage({ user, active, setActive, data, refresh, setToast, showBranchTools })}
          </motion.section>
        </AnimatePresence>
      </main>

      <nav className="fixed bottom-0 left-0 right-0 z-30 border-t border-line bg-white/95 px-2 pb-[calc(0.5rem+env(safe-area-inset-bottom))] pt-2 backdrop-blur lg:hidden">
        <div className="grid grid-cols-5 gap-1">
          {nav.map(([name, Icon]) => (
            <button key={name} onClick={() => setActive(name)} className="relative flex min-h-14 flex-col items-center justify-center gap-1 rounded-2xl px-2 py-2 text-xs font-bold text-muted">
              {active === name && <motion.span layoutId="mobile-active" className="absolute inset-1 rounded-full bg-blue-50" />}
              <Icon className={`relative h-5 w-5 ${active === name ? "text-primary" : ""}`} />
              <span className={`relative truncate ${active === name ? "text-primary" : ""}`}>{name}</span>
            </button>
          ))}
        </div>
      </nav>

      <AnimatePresence>{toast && <Toast message={toast} onClose={() => setToast("")} />}</AnimatePresence>
      <AnimatePresence>{showNotifications && <NotificationDrawer notices={data?.notifications?.items || []} onClose={() => setShowNotifications(false)} />}</AnimatePresence>
    </div>
  );
}

function Brand() {
  return (
    <div className="flex items-center gap-3">
      <div className="gradient-bg flex h-12 w-12 items-center justify-center rounded-[1.25rem] text-white shadow-glow">
        <ShieldCheck className="h-7 w-7" />
      </div>
      <div>
        <strong className="gradient-text block text-lg font-semibold tracking-[-0.04em]">NeverLag Work</strong>
        <span className="text-sm text-muted">Employee Attendance & Payroll SaaS</span>
      </div>
    </div>
  );
}

function NavButton({ name, Icon, active, onClick }) {
  return (
    <button onClick={onClick} className={`flex min-h-12 w-full items-center gap-3 rounded-full px-4 py-3 font-medium transition ${active ? "bg-primary text-white shadow-lift" : "text-muted hover:-translate-y-0.5 hover:bg-blue-50 hover:text-primary"}`}>
      <Icon className={`h-5 w-5 ${active ? "text-white" : "text-primary"}`} />
      {name}
    </button>
  );
}

function renderPage(props) {
  if (props.user.role === "employee") return <EmployeePages {...props} />;
  if (["boss", "branch_manager"].includes(props.user.role)) return <BossPages {...props} />;
  return <SuperPages {...props} />;
}

function EmployeePages({ user, active, data, refresh, setToast }) {
  if (active === "Attendance") return <AttendanceCards data={data} />;
  if (active === "Salary Slip") return <SalarySlips slips={data?.slips || []} />;
  if (active === "Notifications") return <Notifications notices={data?.notifications?.items || []} />;
  if (active === "Profile") return <Profile />;
  return <EmployeeHome user={user} data={data} refresh={refresh} setToast={setToast} />;
}

function BossPages({ active, data, refresh, setToast, setActive, showBranchTools }) {
  if (active === "Branches") return showBranchTools ? <BranchesPage setToast={setToast} /> : <BossHome data={data} setToast={setToast} setActive={setActive} refresh={refresh} showBranchTools={showBranchTools} />;
  if (active === "Employees") return <EmployeesPage setToast={setToast} showBranchTools={showBranchTools} />;
  if (active === "Attendance") return <AttendanceCards data={data} boss refresh={refresh} setToast={setToast} />;
  if (active === "Salary") return <SalaryPanel slips={data?.slips || []} refresh={refresh} setToast={setToast} showBranchTools={showBranchTools} />;
  if (active === "More") return <MorePanel showBranchTools={showBranchTools} />;
  return <BossHome data={data} setToast={setToast} setActive={setActive} refresh={refresh} showBranchTools={showBranchTools} />;
}

function SuperPages({ active, data }) {
  if (active === "Companies") return <CompaniesPage />;
  if (active === "Plans") return <PlansPage />;
  if (active === "Reports") return <ReportsPage />;
  if (active === "More") return <MorePanel superAdmin />;
  return <SuperHome data={data} />;
}

function EmployeeHome({ user, data, refresh, setToast }) {
  const today = data?.attendance?.rows?.[0];
  const settings = data?.settings || {};
  const checkedIn = Boolean(today?.checkInTime);
  const checkedOut = Boolean(today?.checkOutTime);
  const status = today?.status || "Absent";
  const [selfie, setSelfie] = useState("");
  const [qrToken, setQrToken] = useState("");
  const [qrStatus, setQrStatus] = useState("");
  const [showCamera, setShowCamera] = useState(false);
  const [showQrScanner, setShowQrScanner] = useState(false);
  const qrEnabled = Boolean(user?.username === "tester" || settings.enableQRAttendance || settings.qrRequiredOnCheckIn || settings.qrRequiredOnCheckOut);

  async function verifyQrToken(token = qrToken) {
    if (!token) {
      setToast("Please scan office QR code to continue.");
      return;
    }
    const verified = await api("/api/employee-attendance/verify-qr", { method: "POST", body: { qrToken: token } });
    setQrToken(token);
    setQrStatus(`QR verified for branch ${verified.branchId}`);
    setToast("QR verified");
  }

  async function action(kind) {
    try {
      if ((kind === "in" && settings.selfieRequiredOnCheckIn || kind === "out" && settings.selfieRequiredOnCheckOut) && !selfie) {
        setShowCamera(true);
        throw new Error("Selfie required but not captured");
      }
      if ((kind === "in" && settings.qrRequiredOnCheckIn || kind === "out" && settings.qrRequiredOnCheckOut) && !qrToken) {
        throw new Error("Please scan office QR code to continue.");
      }
      let selfieUrl = "";
      if (selfie) {
        const upload = await api("/api/uploads/selfie", { method: "POST", body: { dataUrl: selfie } });
        selfieUrl = upload.url;
      }
      const position = await getLocation();
      await api(`/api/employee-attendance/${kind === "in" ? "check-in" : "check-out"}`, {
        method: "POST",
        body: { latitude: position.lat, longitude: position.lng, qrToken, selfieUrl, deviceInfo: navigator.userAgent },
      });
      setSelfie("");
      setQrToken("");
      setQrStatus("");
      setToast(kind === "in" ? "Check-in successful" : "Check-out successful");
      await refresh();
    } catch (err) {
      setToast(err.message);
    }
  }

  return (
    <div className="space-y-8">
      <HeroGreeting title="Good morning" subtitle={new Date().toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" })} />
      <motion.div whileHover={{ y: -4 }} className="app-card p-6">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-bold text-muted">Today status</p>
            <h2 className="text-3xl font-black">{status}</h2>
          </div>
          <StatusBadge status={status} />
        </div>
        <div className="mt-5 flex flex-wrap gap-2">
          <StatusBadge status="Location Required" />
          {settings.selfieRequiredOnCheckIn || settings.selfieRequiredOnCheckOut ? <StatusBadge status="Selfie Required" /> : null}
          {settings.qrRequiredOnCheckIn || settings.qrRequiredOnCheckOut ? <StatusBadge status="QR Required" /> : null}
        </div>
        <div className="mt-6 grid grid-cols-2 gap-4 text-sm">
          <Info label="Check-in" value={time(today?.checkInTime)} />
          <Info label="Check-out" value={time(today?.checkOutTime)} />
          <Info label="Working Hours" value={`${today?.workingHours || 0} hrs`} />
          <Info label="Location" value={today?.locationVerified ? "Inside Office" : "GPS Required"} />
        </div>
        {qrEnabled && <div className="mt-6 rounded-[1.25rem] border border-line bg-surface p-4">
          <Input label="Scan Office QR / Enter QR Token" value={qrToken} onChange={(value) => { setQrToken(value); setQrStatus(""); }} />
          <div className="mt-3 flex flex-wrap gap-2">
            <button type="button" onClick={() => setShowQrScanner(true)} className="primary-pill gap-2 px-4"><QrCode className="h-5 w-5" /> Scan QR</button>
            <button type="button" onClick={() => verifyQrToken().catch((err) => setToast(err.message))} className="secondary-pill px-4">Verify QR</button>
            {user?.username === "tester" && <button type="button" onClick={() => verifyQrToken("MAIN-OFFICE-DEMO-QR").catch((err) => setToast(err.message))} className="secondary-pill px-4">Use Demo QR</button>}
          </div>
          {qrStatus && <p className="mt-3 text-sm font-medium text-primary">{qrStatus}</p>}
        </div>}
        {(settings.selfieRequiredOnCheckIn || settings.selfieRequiredOnCheckOut) && <div className="mt-6">
          <button type="button" onClick={() => setShowCamera(true)} className="secondary-pill gap-2"><Camera className="h-5 w-5 text-primary" /> {selfie ? "Retake Selfie" : "Capture Selfie"}</button>
          {selfie && <img src={selfie} alt="Captured selfie preview" className="mt-4 h-28 w-28 rounded-2xl object-cover" />}
        </div>}
        <motion.button
          whileTap={{ scale: 0.96 }}
          disabled={checkedOut}
          onClick={() => action(checkedIn ? "out" : "in")}
          className={`mt-8 min-h-24 w-full rounded-full text-xl font-semibold shadow-lift transition hover:-translate-y-0.5 ${checkedOut ? "bg-slate-400 text-white" : checkedIn ? "bg-primary text-white hover:bg-[#74a2f7]" : "gradient-bg text-white shadow-glow"}`}
        >
          {checkedOut ? "Completed Today" : checkedIn ? "Check Out" : "Check In"}
        </motion.button>
      </motion.div>
      <AnimatePresence>{showCamera && <SelfieCapture onClose={() => setShowCamera(false)} onCapture={(image) => { setSelfie(image); setShowCamera(false); }} />}</AnimatePresence>
      <AnimatePresence>{showQrScanner && <QrScanner onClose={() => setShowQrScanner(false)} onScan={(token) => { setShowQrScanner(false); verifyQrToken(token).catch((err) => setToast(err.message)); }} />}</AnimatePresence>
    </div>
  );
}

function BossHome({ data, setToast, setActive, refresh, showBranchTools }) {
  const [branches, setBranches] = useState([]);
  const [branchId, setBranchId] = useState("");
  const [attendance, setAttendance] = useState(data?.attendance || {});
  const stats = attendance?.dashboard || {};
  useEffect(() => setAttendance(data?.attendance || {}), [data]);
  useEffect(() => {
    api("/api/branches").then(setBranches).catch((err) => setToast?.(err.message));
  }, [setToast]);
  useEffect(() => {
    api(`/api/employee-attendance/today${branchId ? `?branchId=${branchId}` : ""}`)
      .then(setAttendance)
      .catch((err) => setToast?.(err.message));
  }, [branchId, setToast]);
  return (
    <div className="space-y-8">
      <HeroGreeting title="Good morning" subtitle="Company attendance overview" />
      {showBranchTools && <BranchFilter branches={branches} value={branchId} onChange={setBranchId} />}
      <StatGrid stats={[
        ["Total Employees", stats.totalEmployees || 0, "blue"],
        ["Present Today", stats.presentToday || 0, "green"],
        ["Absent Today", stats.absentToday || 0, "red"],
        ["Late Today", stats.lateToday || 0, "orange"],
        ["Checked Out", stats.checkedOut || 0, "blue"],
        ["Currently Inside Office", stats.currentlyInsideOffice || 0, "green"],
        ["On Leave", stats.onLeave || 0, "gray"],
        ["Pending Salary Slips", stats.pendingSalarySlips || 0, "orange"],
      ]} />
      <AdvancedModuleShortcuts setActive={setActive} setToast={setToast} refresh={refresh} showBranchTools={showBranchTools} />
      <Charts />
      <AttendanceCards data={{ ...data, attendance }} boss />
    </div>
  );
}

function AdvancedModuleShortcuts({ setActive, setToast, refresh, showBranchTools }) {
  async function enableDemoTest() {
    await api("/api/company/settings", {
      method: "PUT",
      body: {
        enableSelfieAttendance: true,
        selfieRequiredOnCheckIn: true,
        selfieRequiredOnCheckOut: false,
        enableQRAttendance: true,
        qrRequiredOnCheckIn: true,
        qrRequiredOnCheckOut: false,
        enableMultiBranch: true,
      },
    });
    setToast?.("QR + Selfie test mode enabled. Demo QR token: MAIN-OFFICE-DEMO-QR");
    await refresh?.();
  }
  const modules = [
    ...(showBranchTools ? [["Branches", "Multiple offices, branch geofence, and branch status.", "Branches", Building2]] : []),
    ["Selfie Attendance", "Enable camera selfie rules from attendance settings.", "More", Camera],
    ["Attendance QR", "Generate, print, regenerate, and activate office QR codes.", "More", QrCode],
    ...(showBranchTools ? [["Branch Managers", "Create logins restricted to assigned branch data.", "More", Users]] : []),
    ["Premium Features", "Face Recognition and Biometric placeholders.", "More", ShieldCheck],
  ];
  return (
    <section className="grid gap-3 md:grid-cols-2 xl:grid-cols-6">
      {modules.map(([title, meta, target, Icon]) => (
        <button key={title} type="button" onClick={() => setActive(target)} className="app-card p-4 text-left transition hover:-translate-y-1 hover:shadow-lift">
          <Icon className="mb-3 h-5 w-5 text-primary" />
          <strong className="block text-sm font-medium">{title}</strong>
          <span className="mt-2 block text-xs leading-5 text-muted">{meta}</span>
        </button>
      ))}
      <button type="button" onClick={() => enableDemoTest().catch((err) => setToast?.(err.message))} className="app-card border-primary/25 bg-blue-50 p-4 text-left transition hover:-translate-y-1 hover:shadow-lift">
        <Check className="mb-3 h-5 w-5 text-primary" />
        <strong className="block text-sm font-medium">Enable Test Mode</strong>
        <span className="mt-2 block text-xs leading-5 text-muted">QR + Selfie required, token MAIN-OFFICE-DEMO-QR.</span>
      </button>
    </section>
  );
}

function SuperHome({ data }) {
  const stats = data?.attendance?.dashboard || {};
  return (
    <div className="space-y-8">
      <HeroGreeting title="NeverLag Work" subtitle="SaaS owner dashboard" />
      <StatGrid stats={[
        ["Total Companies", 1, "blue"],
        ["Active Companies", 1, "green"],
        ["Total Employees", stats.totalEmployees || 0, "blue"],
        ["Today Check-ins", stats.presentToday || 0, "green"],
        ["Monthly Revenue", 299, "orange"],
        ["Expired Subscriptions", 0, "red"],
      ]} />
      <MorePanel superAdmin />
    </div>
  );
}

function StatGrid({ stats }) {
  return (
    <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
      {stats.map(([label, value, color], index) => (
        <motion.article key={label} initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: index * 0.08 }} whileHover={{ y: -4 }} className={`app-card p-5 ${index === 0 || index === 3 ? "lg:col-span-2" : ""}`}>
          <div className="flex items-start justify-between gap-3">
            <p className="text-sm font-medium text-muted">{label}</p>
            <span className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-50 text-primary">
              <HeroIcon name={color === "red" ? "shield" : color === "orange" ? "cloud" : "speed"} className="h-5 w-5" />
            </span>
          </div>
          <Counter value={value} className="mt-5 block text-3xl font-semibold tracking-[-0.04em] text-navy" />
          <div className={`mt-5 h-1.5 rounded-full ${color === "orange" ? "gradient-bg" : color === "red" ? "bg-danger" : "bg-primary"}`} />
        </motion.article>
      ))}
    </div>
  );
}

function Counter({ value, className }) {
  const [shown, setShown] = useState(0);
  useEffect(() => {
    const numeric = Number(value) || 0;
    const id = setInterval(() => setShown((old) => (old >= numeric ? numeric : Math.min(numeric, old + Math.ceil(numeric / 12 || 1)))), 18);
    return () => clearInterval(id);
  }, [value]);
  return <strong className={className}>{shown}</strong>;
}

function AttendanceCards({ data, boss, refresh, setToast }) {
  const rows = data?.attendance?.rows || [];
  const [selectedMonth, setSelectedMonth] = useState(() => new Date().toISOString().slice(0, 7));
  const [monthlyRows, setMonthlyRows] = useState(rows);
  const [filter, setFilter] = useState("All");
  useEffect(() => setMonthlyRows(rows), [rows]);
  useEffect(() => {
    api(`/api/employee-attendance/monthly?month=${selectedMonth}`)
      .then(setMonthlyRows)
      .catch((err) => setToast?.(err.message));
  }, [selectedMonth, setToast]);
  const filtered = filter === "All" ? monthlyRows : monthlyRows.filter((row) => attendanceFilterMatch(row, filter));
  async function markLeave(row) {
    await api("/api/leaves/mark", { method: "POST", body: { employeeId: row.employeeId, date: row.date } });
    setToast?.("Leave marked");
    await refresh?.();
  }
  async function correct(row) {
    const reason = window.prompt("Correction reason");
    if (!reason) return;
    const status = window.prompt("New status: Present, Late, Half Day, Leave, Absent", row.status || "Present");
    if (!status) return;
    await api(`/api/employee-attendance/${row.id || row._id}/manual-correction`, { method: "PUT", body: { status, reason } });
    setToast?.("Attendance corrected");
    await refresh?.();
  }
  return (
    <section className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex gap-2 overflow-x-auto pb-1">
        {["All", "Present", "Absent", "Late", "Leave", "Checked Out", "Inside Office"].map((item) => (
          <button key={item} onClick={() => setFilter(item)} className={`min-h-11 shrink-0 rounded-full px-5 py-2 text-sm font-black transition hover:-translate-y-0.5 ${filter === item ? "bg-primary text-white shadow-lift" : "bg-white text-muted shadow-premium"}`}>{item}</button>
        ))}
        </div>
        <input type="month" value={selectedMonth} onChange={(event) => setSelectedMonth(event.target.value)} className="min-h-11 rounded-full border border-line bg-white px-4 font-medium text-navy shadow-premium outline-none focus:ring-4 focus:ring-primary/20" />
      </div>
      <AttendanceCalendar month={selectedMonth} rows={monthlyRows} filter={filter} boss={boss} />
      <div className="grid gap-4 lg:grid-cols-2">
        {filtered.map((row, index) => (
          <motion.article key={row.id || index} whileHover={{ y: -4 }} className="app-card p-5">
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-blue-50 font-black text-primary">{initials(row.employeeName || "Employee")}</div>
              <div className="min-w-0 flex-1">
                <h3 className="truncate font-black">{row.employeeName || "Employee"}</h3>
                <p className="text-sm text-muted">{row.department || "Department optional"}</p>
              </div>
              <StatusBadge status={row.status || "Absent"} />
            </div>
            <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
              <Info label="Check-in" value={time(row.checkInTime)} />
              <Info label="Check-out" value={time(row.checkOutTime)} />
              <Info label="Working Hours" value={`${row.workingHours || 0} hrs`} />
              <Info label="Location" value={row.locationVerified ? "Verified" : "GPS Required"} />
              <Info label="Branch" value={row.branchName || "Main Office"} />
              <Info label="QR" value={row.qrVerified ? "Verified" : "Not used"} />
            </div>
            {(row.checkInSelfieUrl || row.checkOutSelfieUrl) && <div className="mt-4 flex gap-3">
              {row.checkInSelfieUrl && <SelfieThumb label="Check-in Selfie" src={row.checkInSelfieUrl} />}
              {row.checkOutSelfieUrl && <SelfieThumb label="Check-out Selfie" src={row.checkOutSelfieUrl} />}
            </div>}
            {boss && <div className="mt-4 flex flex-wrap gap-2">
              <button onClick={() => markLeave(row).catch((err) => setToast?.(err.message))} className="min-h-11 rounded-2xl bg-slate-100 px-4 font-black">Mark Leave</button>
              <button onClick={() => correct(row).catch((err) => setToast?.(err.message))} className="min-h-11 rounded-2xl bg-primary px-4 font-black text-white">Correct</button>
            </div>}
          </motion.article>
        ))}
        {!filtered.length && <EmptyState text="No attendance records found for selected filter." />}
      </div>
    </section>
  );
}

function AttendanceCalendar({ month, rows, filter, boss }) {
  const days = calendarDays(month);
  const recordsByDate = rows.reduce((map, row) => {
    const key = row.date;
    map[key] = map[key] || [];
    map[key].push(row);
    return map;
  }, {});
  return (
    <section className="app-card overflow-hidden p-4 sm:p-5">
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-xl font-semibold tracking-[-0.04em]">Attendance Calendar</h2>
          <p className="text-sm text-muted">{new Date(`${month}-01T00:00:00`).toLocaleDateString([], { month: "long", year: "numeric" })}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          {attendanceLegend().map((item) => <span key={item.label} className={`inline-flex items-center gap-1 rounded-full px-3 py-1 ${item.legendClass}`}><span className={`h-2.5 w-2.5 rounded-full ${item.dotClass}`} />{item.label}</span>)}
        </div>
      </div>
      <div className="grid grid-cols-7 gap-1 text-center text-xs font-semibold text-muted">
        {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day) => <div key={day} className="py-2">{day}</div>)}
      </div>
      <div className="grid grid-cols-7 gap-1">
        {days.map((day, index) => {
          if (!day) return <div key={`empty-${index}`} className="min-h-24 rounded-[1rem] bg-transparent" />;
          const dayRows = recordsByDate[day.date] || [];
          const cell = attendanceCell(day, dayRows, filter, boss);
          return (
            <div key={day.date} className={`min-h-24 rounded-[1rem] border p-2 text-left transition hover:-translate-y-0.5 ${cell.className}`}>
              <div className="flex items-center justify-between gap-1">
                <span className="text-sm font-semibold">{day.dayNumber}</span>
                <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${cell.badgeClass}`}>{cell.short}</span>
              </div>
              <p className="mt-2 truncate text-xs font-medium">{cell.title}</p>
              <p className="mt-1 truncate text-[11px] opacity-80">{cell.meta}</p>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function calendarDays(month) {
  const [year, monthIndex] = month.split("-").map(Number);
  const first = new Date(year, monthIndex - 1, 1);
  const total = new Date(year, monthIndex, 0).getDate();
  const blanks = Array.from({ length: first.getDay() }, () => null);
  const days = Array.from({ length: total }, (_, index) => {
    const dayNumber = index + 1;
    const date = `${month}-${String(dayNumber).padStart(2, "0")}`;
    return { date, dayNumber };
  });
  return [...blanks, ...days];
}

function attendanceFilterMatch(row, filter) {
  if (filter === "All") return true;
  if (filter === "Checked Out") return Boolean(row.checkOutTime);
  if (filter === "Inside Office") return Boolean(row.checkInTime && !row.checkOutTime);
  return (row.status || "Absent") === filter;
}

function attendancePalette(status) {
  const normalized = status === "Half Day" ? "Late" : status;
  const palette = {
    Present: { short: "P", title: "Present", className: "border-emerald-200 bg-emerald-50 text-emerald-800", badgeClass: "bg-emerald-600 text-white", legendClass: "bg-emerald-50 text-emerald-700", dotClass: "bg-emerald-500" },
    Absent: { short: "A", title: "Absent", className: "border-red-200 bg-red-50 text-red-800", badgeClass: "bg-red-600 text-white", legendClass: "bg-red-50 text-red-700", dotClass: "bg-red-500" },
    Late: { short: "L", title: "Late", className: "border-amber-200 bg-amber-50 text-amber-800", badgeClass: "bg-amber-500 text-white", legendClass: "bg-amber-50 text-amber-700", dotClass: "bg-amber-500" },
    Leave: { short: "LV", title: "Leave", className: "border-violet-200 bg-violet-50 text-violet-800", badgeClass: "bg-violet-600 text-white", legendClass: "bg-violet-50 text-violet-700", dotClass: "bg-violet-500" },
    "Checked Out": { short: "OUT", title: "Checked Out", className: "border-sky-200 bg-sky-50 text-sky-800", badgeClass: "bg-sky-600 text-white", legendClass: "bg-sky-50 text-sky-700", dotClass: "bg-sky-500" },
    "Inside Office": { short: "IN", title: "Inside Office", className: "border-blue-200 bg-blue-50 text-blue-800", badgeClass: "bg-primary text-white", legendClass: "bg-blue-50 text-blue-700", dotClass: "bg-primary" },
    "No Record": { short: "-", title: "No Record", className: "border-line bg-white text-muted", badgeClass: "bg-surface text-muted", legendClass: "bg-slate-50 text-slate-600", dotClass: "bg-slate-300" },
  };
  return palette[normalized] || palette["No Record"];
}

function attendanceCell(day, rows, filter, boss) {
  const todayKey = new Date().toISOString().slice(0, 10);
  if (!rows.length) {
    const isPastOrToday = day.date <= todayKey;
    const generatedStatus = !boss && isPastOrToday ? "Absent" : "No Record";
    const palette = attendancePalette(generatedStatus);
    const hidden = filter !== "All" && filter !== generatedStatus;
    return { ...palette, className: `${palette.className} ${hidden ? "opacity-30" : ""}`, meta: generatedStatus === "Absent" ? "No check-in" : "No data yet" };
  }
  const checkedOut = rows.filter((row) => row.checkOutTime).length;
  const inside = rows.filter((row) => row.checkInTime && !row.checkOutTime).length;
  const priority = rows.find((row) => row.status === "Leave") || rows.find((row) => row.status === "Late") || rows.find((row) => row.status === "Absent") || rows[0];
  const status = checkedOut && rows.length === checkedOut ? "Checked Out" : inside && rows.length === inside ? "Inside Office" : priority.status || "Present";
  const palette = attendancePalette(status);
  const hidden = filter !== "All" && !rows.some((row) => attendanceFilterMatch(row, filter)) && !(filter === status);
  return {
    ...palette,
    className: `${palette.className} ${hidden ? "opacity-30" : ""}`,
    title: boss ? `${rows.length} record${rows.length === 1 ? "" : "s"}` : palette.title,
    meta: boss ? `${checkedOut} out / ${inside} inside` : `${time(priority.checkInTime)} - ${time(priority.checkOutTime)}`,
  };
}

function attendanceLegend() {
  return ["Present", "Absent", "Late", "Leave", "Checked Out", "Inside Office"].map((status) => ({ label: `${attendancePalette(status).short} ${status}`, ...attendancePalette(status) }));
}

function SelfieThumb({ label, src }) {
  return <div><img src={src} alt={label} className="h-20 w-20 rounded-2xl object-cover" /><p className="mt-1 text-xs font-bold text-muted">{label}</p></div>;
}

function BranchFilter({ branches, value, onChange }) {
  if (!branches || branches.length <= 1) return null;
  return (
    <label className="block max-w-sm">
      <span className="mb-1 block text-sm font-bold text-muted">Branch Filter</span>
      <select className="min-h-12 w-full rounded-full border border-line bg-white px-4 outline-none focus:ring-4 focus:ring-primary/20" value={value} onChange={(event) => onChange(event.target.value)}>
        <option value="">All Branches</option>
        {branches.map((branch) => <option key={branch.id || branch._id} value={branch.id || branch._id}>{branch.branchName}</option>)}
      </select>
    </label>
  );
}

function EmployeesPage({ setToast, showBranchTools }) {
  const [items, setItems] = useState([]);
  const [branches, setBranches] = useState([]);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(null);
  async function load() {
    const [employees, branchRows] = await Promise.all([api("/api/employees"), api("/api/branches")]);
    setItems(employees);
    setBranches(branchRows);
  }
  useEffect(() => {
    load().catch((err) => setToast(err.message));
  }, [setToast]);
  async function removeEmployee(employee) {
    await api(`/api/employees/${employee.id || employee._id}`, { method: "DELETE" });
    setItems((old) => old.filter((item) => (item.id || item._id) !== (employee.id || employee._id)));
    setToast("Employee deleted");
  }
  return (
    <section className="space-y-6">
      <div className="flex items-center gap-3 rounded-[1.5rem] border border-line bg-white p-3 shadow-premium">
        <Search className="h-5 w-5 text-muted" />
        <input className="min-h-11 flex-1 outline-none" placeholder="Search Employees" />
      </div>
      <div className="grid gap-4 lg:grid-cols-2">
        {items.map((employee) => <EmployeeCard key={employee.id || employee._id} employee={employee} onEdit={() => { setEditing(employee); setOpen(true); }} onDelete={() => removeEmployee(employee).catch((err) => setToast(err.message))} />)}
      </div>
      <motion.button whileTap={{ scale: 0.96 }} onClick={() => setOpen(true)} className="fixed bottom-24 right-5 z-30 flex h-16 w-16 items-center justify-center rounded-full bg-primary text-white shadow-lift transition hover:-translate-y-0.5 hover:bg-[#74a2f7] lg:bottom-8">
        <Plus className="h-7 w-7" />
      </motion.button>
      <AnimatePresence>{open && <EmployeeSheet initial={editing} branches={branches} showBranchTools={showBranchTools} onClose={() => { setOpen(false); setEditing(null); }} onSaved={(employee) => {
        setItems((old) => editing ? old.map((item) => (item.id || item._id) === (employee.id || employee._id) ? employee : item) : [employee, ...old]);
      }} setToast={setToast} />}</AnimatePresence>
    </section>
  );
}

function EmployeeCard({ employee, onEdit, onDelete }) {
  return (
    <motion.article whileHover={{ y: -4 }} className="app-card p-5">
      <div className="flex items-center gap-3">
        <div className="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 font-semibold text-primary">{initials(employee.name)}</div>
        <div className="min-w-0 flex-1">
          <h3 className="truncate font-black">{employee.name}</h3>
          <p className="text-sm text-muted">{employee.employeeCode} / {employee.mobile}</p>
        </div>
        <div className="flex gap-2">
          <button onClick={onEdit} className="min-h-11 min-w-11 rounded-2xl bg-slate-100 p-2 transition hover:bg-slate-200"><Settings className="h-5 w-5 text-muted" /></button>
          <button onClick={onDelete} className="min-h-11 min-w-11 rounded-2xl bg-red-50 p-2 font-black text-danger transition hover:bg-red-100">X</button>
        </div>
      </div>
      <p className="mt-3 text-sm text-muted">{employee.department || "Department optional"} / {employee.designation || "Designation optional"}</p>
      <p className="mt-1 text-sm font-bold text-muted">{employee.branchName || "Main Office"}</p>
    </motion.article>
  );
}

function EmployeeSheet({ initial, branches, showBranchTools, onClose, onSaved, setToast }) {
  const defaultBranchId = branches?.[0]?.id || branches?.[0]?._id || "";
  const [form, setForm] = useState(() => initial ? { ...initial, branchId: initial.branchId || defaultBranchId, username: initial.username || "", password: "" } : { name: "", employeeCode: "", mobile: "", email: "", department: "", designation: "", joiningDate: "", salary: "", shift: "General", branchId: defaultBranchId, username: "", password: "", status: "Active" });
  const [errors, setErrors] = useState({});

  async function save(event) {
    event.preventDefault();
    try {
      const id = initial?.id || initial?._id;
      const employee = await api(id ? `/api/employees/${id}` : "/api/employees", { method: id ? "PUT" : "POST", body: form });
      onSaved(employee);
      onClose();
    } catch (err) {
      setToast(err.message);
      setErrors({ form: err.message });
    }
  }

  return (
    <motion.div className="fixed inset-0 z-40 bg-navy/40" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <motion.form onSubmit={save} initial={{ y: "100%" }} animate={{ y: 0 }} exit={{ y: "100%" }} transition={{ type: "spring", damping: 28, stiffness: 260 }} className="absolute bottom-0 left-0 right-0 max-h-[92vh] overflow-y-auto rounded-t-[2rem] bg-white p-6 shadow-premium lg:left-auto lg:top-10 lg:mr-8 lg:w-[520px] lg:rounded-[2rem]">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-xl font-black">{initial ? "Edit Employee" : "Add Employee"}</h2>
          <button type="button" onClick={onClose} className="min-h-11 min-w-11 rounded-full bg-slate-100 p-2 transition hover:bg-slate-200"><X className="h-5 w-5" /></button>
        </div>
        <div className="grid gap-4">
          {Object.keys(form).filter((key) => showBranchTools || key !== "branchId").map((key) => key === "branchId" ? (
            <label key={key} className="block">
              <span className="mb-1 block text-sm font-bold capitalize text-muted">Assigned Branch</span>
              <select className={`min-h-12 w-full rounded-full border px-4 outline-none focus:ring-4 focus:ring-primary/20 ${errors[key] ? "border-danger" : "border-line"}`} value={form.branchId || ""} onChange={(event) => setForm({ ...form, branchId: event.target.value })}>
                <option value="">Select Branch</option>
                {branches.map((branch) => <option key={branch.id || branch._id} value={branch.id || branch._id}>{branch.branchName}</option>)}
              </select>
            </label>
          ) : (
            <label key={key} className="block">
              <span className="mb-1 block text-sm font-bold capitalize text-muted">{key.replace(/([A-Z])/g, " $1")}</span>
              <input className={`min-h-12 w-full rounded-full border px-4 outline-none focus:ring-4 focus:ring-primary/20 ${errors[key] ? "border-danger" : "border-line"}`} value={form[key]} onChange={(event) => setForm({ ...form, [key]: event.target.value })} />
              {errors[key] && <span className="text-xs font-bold text-danger">{errors[key]}</span>}
            </label>
          ))}
        </div>
        {errors.form && <p className="mt-3 text-sm font-bold text-danger">{errors.form}</p>}
        <button className="sticky bottom-0 mt-6 min-h-12 w-full rounded-2xl bg-primary font-black text-white shadow-lift transition hover:brightness-110">Save Employee</button>
      </motion.form>
    </motion.div>
  );
}

function SalaryPanel({ slips, refresh, setToast, showBranchTools }) {
  const [branches, setBranches] = useState([]);
  const [branchId, setBranchId] = useState("");
  const [rows, setRows] = useState(slips);
  useEffect(() => setRows(slips), [slips]);
  useEffect(() => {
    api("/api/branches").then(setBranches).catch((err) => setToast(err.message));
  }, [setToast]);
  useEffect(() => {
    api(`/api/employee-salary/slips${branchId ? `?branchId=${branchId}` : ""}`).then(setRows).catch((err) => setToast(err.message));
  }, [branchId, setToast]);
  async function generate() {
    try {
      await api("/api/employee-salary/generate", { method: "POST", body: { branchId } });
      setToast("Salary slip generated");
      setRows(await api(`/api/employee-salary/slips${branchId ? `?branchId=${branchId}` : ""}`));
      await refresh();
    } catch (err) {
      setToast(err.message);
    }
  }
  async function toggleStatus(slip) {
    const next = slip.paymentStatus === "Paid" ? "Pending" : "Paid";
    await api(`/api/employee-salary/slips/${slip.id || slip._id}/status`, { method: "PUT", body: { paymentStatus: next } });
    setToast(`Salary slip marked ${next}`);
    await refresh();
  }
  return (
    <section className="space-y-6">
      <div className="flex flex-wrap items-end gap-3">
        {showBranchTools && <BranchFilter branches={branches} value={branchId} onChange={setBranchId} />}
        <button onClick={generate} className="min-h-12 rounded-2xl bg-primary px-6 font-black text-white shadow-lift transition hover:-translate-y-0.5 hover:brightness-110">Generate Salary Slips</button>
      </div>
      <SalarySlips slips={rows} onToggleStatus={toggleStatus} />
    </section>
  );
}

function SalarySlips({ slips, onToggleStatus }) {
  return (
    <div className="grid gap-4 lg:grid-cols-2">
      {slips.map((slip) => (
        <article key={slip.id || slip._id} className="app-card p-6">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-sm font-bold text-muted">{slip.slipNumber}</p>
              <h3 className="text-xl font-black">{slip.month} {slip.year}</h3>
            </div>
            <StatusBadge status={slip.paymentStatus || "Pending"} />
          </div>
          <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
            <Info label="Present Days" value={slip.presentDays || 0} />
            <Info label="Absent Days" value={slip.absentDays || 0} />
            <Info label="Late Days" value={slip.lateDays || 0} />
            <Info label="Net Salary" value={`$${slip.netSalary || 0}`} />
            <Info label="Branch" value={slip.branchName || "Main Office"} />
          </div>
          <div className="mt-6 flex flex-wrap gap-2">
            <button type="button" onClick={() => downloadSalaryPdf(slip)} className="inline-flex min-h-11 items-center gap-2 rounded-2xl bg-slate-100 px-5 py-3 font-black transition hover:-translate-y-0.5 hover:bg-slate-200">
              <Download className="h-4 w-4" /> Download PDF
            </button>
            {onToggleStatus && <button onClick={() => onToggleStatus(slip)} className="min-h-11 rounded-2xl bg-primary px-5 py-3 font-black text-white transition hover:-translate-y-0.5">Mark {slip.paymentStatus === "Paid" ? "Pending" : "Paid"}</button>}
          </div>
        </article>
      ))}
      {!slips.length && <EmptyState text="No salary slips generated yet." />}
    </div>
  );
}

function Charts() {
  const weekly = [
    { day: "Mon", present: 42 },
    { day: "Tue", present: 45 },
    { day: "Wed", present: 39 },
    { day: "Thu", present: 48 },
    { day: "Fri", present: 44 },
  ];
  const monthly = [
    { name: "Present", value: 88 },
    { name: "Absent", value: 12 },
  ];
  return (
    <div className="grid gap-6 lg:grid-cols-2">
      <ChartCard title="Weekly Attendance Trend">
        <AreaChart data={weekly}>
          <CartesianGrid strokeDasharray="3 3" stroke="#E8E8ED" />
          <XAxis dataKey="day" />
          <YAxis />
          <Tooltip />
          <Area type="monotone" dataKey="present" stroke="#206CF3" fill="#EAF1FF" />
        </AreaChart>
      </ChartCard>
      <ChartCard title="Monthly Present vs Absent">
        <BarChart data={monthly}>
          <CartesianGrid strokeDasharray="3 3" stroke="#E8E8ED" />
          <XAxis dataKey="name" />
          <YAxis />
          <Tooltip />
          <Bar dataKey="value" fill="#206CF3" radius={[8, 8, 0, 0]} />
        </BarChart>
      </ChartCard>
    </div>
  );
}

function ChartCard({ title, children }) {
  return (
    <section className="app-card h-80 p-5">
      <h3 className="mb-4 font-medium tracking-[-0.04em]">{title}</h3>
      <ResponsiveContainer width="100%" height="82%">{children}</ResponsiveContainer>
    </section>
  );
}

function CompaniesPage() {
  const [companies, setCompanies] = useState([]);
  const [bosses, setBosses] = useState([]);
  const [form, setForm] = useState({ name: "", bossName: "", bossUsername: "", bossPassword: "" });
  const [message, setMessage] = useState("");
  async function load() {
    const [companyRows, bossRows] = await Promise.all([api("/api/companies"), api("/api/company-admins")]);
    setCompanies(companyRows);
    setBosses(bossRows);
  }
  useEffect(() => { load().catch((err) => setMessage(err.message)); }, []);
  async function save(event) {
    event.preventDefault();
    await api("/api/companies", { method: "POST", body: form });
    setForm({ name: "", bossName: "", bossUsername: "", bossPassword: "" });
    setMessage("Company and Boss login created");
    await load();
  }
  async function toggle(company) {
    await api(`/api/companies/${company.id || company._id}`, { method: "PUT", body: { status: company.status === "Active" ? "Inactive" : "Active" } });
    await load();
  }
  return (
    <section className="grid gap-4 lg:grid-cols-[minmax(0,1.35fr)_minmax(320px,0.65fr)]">
      <div className="space-y-4">
        <Panel title="Companies">
          <div className="grid gap-3">{companies.map((company) => <RowCard key={company.id || company._id} title={company.name} meta={`${company.status} / ${company.subscription || "Professional"}`} action={<button onClick={() => toggle(company)} className="min-h-11 rounded-2xl bg-slate-100 px-4 font-black">Toggle</button>} />)}</div>
        </Panel>
        <Panel title="Company Admins / Bosses">
          <div className="grid gap-3">{bosses.map((boss) => <RowCard key={boss.id || boss._id} title={boss.name} meta={`${boss.username} / ${boss.companyName}`} />)}</div>
        </Panel>
      </div>
      <Panel title="Add Company">
        <form onSubmit={save} className="grid gap-3">
          <Input label="Company Name" value={form.name} onChange={(value) => setForm({ ...form, name: value })} required />
          <Input label="Boss Name" value={form.bossName} onChange={(value) => setForm({ ...form, bossName: value })} required />
          <Input label="Boss Username" value={form.bossUsername} onChange={(value) => setForm({ ...form, bossUsername: value })} required />
          <Input label="Boss Password" type="password" value={form.bossPassword} onChange={(value) => setForm({ ...form, bossPassword: value })} required />
          <button className="min-h-12 rounded-2xl bg-primary px-5 font-black text-white">Save Company</button>
          {message && <p className="text-sm font-bold text-muted">{message}</p>}
        </form>
      </Panel>
    </section>
  );
}

function PlansPage() {
  const [plans, setPlans] = useState([]);
  const [payments, setPayments] = useState([]);
  const [form, setForm] = useState({ name: "", price: "", employeeLimit: "" });
  async function load() {
    const [planRows, paymentRows] = await Promise.all([api("/api/subscription-plans"), api("/api/payments")]);
    setPlans(planRows);
    setPayments(paymentRows);
  }
  useEffect(() => { load().catch(() => null); }, []);
  async function save(event) {
    event.preventDefault();
    await api("/api/subscription-plans", { method: "POST", body: form });
    setForm({ name: "", price: "", employeeLimit: "" });
    await load();
  }
  return (
    <section className="grid gap-4 lg:grid-cols-[minmax(0,1.35fr)_minmax(320px,0.65fr)]">
      <div className="space-y-4">
        <Panel title="Subscription Plans">
          <div className="grid gap-3">{plans.map((plan) => <RowCard key={plan.id || plan._id} title={plan.name} meta={`$${plan.price} / ${plan.employeeLimit} Employees / ${plan.status}`} />)}</div>
        </Panel>
        <Panel title="Payments / Billing">
          <div className="grid gap-3">{payments.map((payment) => <RowCard key={payment.id || payment._id} title={payment.companyName || payment.companyId} meta={`$${payment.amount} / ${payment.status} / ${payment.date || ""}`} />)} {!payments.length && <EmptyState text="No payments yet." />}</div>
        </Panel>
      </div>
      <Panel title="Add Plan">
        <form onSubmit={save} className="grid gap-3">
          <Input label="Plan Name" value={form.name} onChange={(value) => setForm({ ...form, name: value })} required />
          <Input label="Price" type="number" value={form.price} onChange={(value) => setForm({ ...form, price: value })} required />
          <Input label="Employee Limit" type="number" value={form.employeeLimit} onChange={(value) => setForm({ ...form, employeeLimit: value })} required />
          <button className="min-h-12 rounded-2xl bg-primary px-5 font-black text-white">Save Plan</button>
        </form>
      </Panel>
    </section>
  );
}

function ReportsPage() {
  const [attendance, setAttendance] = useState([]);
  const [salary, setSalary] = useState([]);
  useEffect(() => {
    Promise.all([api("/api/reports/attendance"), api("/api/reports/salary")]).then(([a, s]) => { setAttendance(a); setSalary(s); }).catch(() => null);
  }, []);
  return (
    <section className="grid gap-4 lg:grid-cols-2">
      <ReportCard title="Attendance Reports" rows={attendance} kinds={["Daily Attendance Report", "Monthly Attendance Report", "Employee-wise Report", "Late Coming Report", "Absent Report", "Working Hours Report"]} fileName="attendance-report.csv" />
      <ReportCard title="Salary Reports" rows={salary} kinds={["Salary Slip Report", "Paid / Pending Salary Report"]} fileName="salary-report.csv" />
    </section>
  );
}

function MorePanel({ superAdmin, showBranchTools }) {
  return superAdmin ? <AdminTools /> : <div className="space-y-4"><CompanySettingsPanel /><AttendanceQrPanel />{showBranchTools && <BranchManagersPanel />}<PremiumFeaturesPanel /></div>;
}

function BranchesPage({ setToast }) {
  const [branches, setBranches] = useState([]);
  const [form, setForm] = useState({ branchName: "", branchCode: "", address: "", city: "", state: "", pincode: "", contactPerson: "", mobile: "", email: "", latitude: "", longitude: "", geofenceRadius: "100", shiftStartTime: "09:00", shiftEndTime: "18:00", graceMinutes: "10", isMainBranch: false, status: "Active" });
  async function load() {
    setBranches(await api("/api/branches"));
  }
  useEffect(() => { load().catch((err) => setToast(err.message)); }, [setToast]);
  async function save(event) {
    event.preventDefault();
    await api("/api/branches", { method: "POST", body: form });
    setToast("Branch saved");
    setForm({ ...form, branchName: "", branchCode: "" });
    await load();
  }
  async function toggle(branch) {
    await api(`/api/branches/${branch.id || branch._id}`, { method: "PUT", body: { status: branch.status === "Active" ? "Inactive" : "Active" } });
    await load();
  }
  return (
    <section className="grid gap-4 lg:grid-cols-[1fr_420px]">
      <Panel title="Branches">
        <div className="grid gap-3">{branches.map((branch) => <RowCard key={branch.id || branch._id} title={branch.branchName} meta={`${branch.branchCode} / ${branch.city || ""} / ${branch.status}`} action={<button onClick={() => toggle(branch)} className="min-h-11 rounded-2xl bg-slate-100 px-4 font-black">Toggle</button>} />)}</div>
      </Panel>
      <Panel title="Add Branch">
        <form onSubmit={save} className="grid gap-3">
          {["branchName", "branchCode", "address", "city", "state", "pincode", "contactPerson", "mobile", "email", "latitude", "longitude", "geofenceRadius", "shiftStartTime", "shiftEndTime", "graceMinutes"].map((key) => <Input key={key} label={key.replace(/([A-Z])/g, " $1")} value={form[key]} onChange={(value) => setForm({ ...form, [key]: value })} required={["branchName", "branchCode", "latitude", "longitude", "geofenceRadius"].includes(key)} />)}
          <button className="min-h-12 rounded-2xl bg-primary px-5 font-black text-white">Save Branch</button>
        </form>
      </Panel>
    </section>
  );
}

function AttendanceQrPanel() {
  const [branches, setBranches] = useState([]);
  const [qrs, setQrs] = useState([]);
  const [form, setForm] = useState({ qrLabel: "Office QR", branchId: "" });
  const [token, setToken] = useState("");
  async function load() {
    const [branchRows, qrRows] = await Promise.all([api("/api/branches"), api("/api/attendance-qr")]);
    setBranches(branchRows);
    setQrs(qrRows);
    setForm((old) => ({ ...old, branchId: old.branchId || branchRows[0]?.id || "" }));
  }
  useEffect(() => { load().catch(() => null); }, []);
  async function generate() {
    const qr = await api("/api/attendance-qr/generate", { method: "POST", body: form });
    setToken(qr.qrToken);
    await load();
  }
  async function regenerate(qr) {
    const next = await api("/api/attendance-qr/regenerate", { method: "POST", body: { id: qr.id || qr._id } });
    setToken(next.qrToken);
    await load();
  }
  async function toggleStatus(qr) {
    await api("/api/attendance-qr/status", { method: "POST", body: { id: qr.id || qr._id, isActive: !qr.isActive } });
    await load();
  }
  return (
    <Panel title="Attendance QR">
      <div className="grid gap-3 md:grid-cols-3">
        <Input label="QR Label" value={form.qrLabel} onChange={(value) => setForm({ ...form, qrLabel: value })} />
        <label className="block"><span className="mb-1 block text-sm font-bold text-muted">Branch</span><select className="min-h-12 w-full rounded-2xl border border-line px-4" value={form.branchId} onChange={(event) => setForm({ ...form, branchId: event.target.value })}>{branches.map((branch) => <option key={branch.id || branch._id} value={branch.id || branch._id}>{branch.branchName}</option>)}</select></label>
        <button onClick={generate} className="min-h-12 self-end rounded-2xl bg-primary px-5 font-black text-white">Generate QR</button>
      </div>
      {token && <div className="mt-4 rounded-2xl bg-slate-50 p-4"><QrCode className="mb-2 h-8 w-8" /><strong>QR Token</strong><p className="break-all text-sm text-muted">{token}</p><button onClick={() => window.print()} className="mt-2 min-h-11 rounded-2xl bg-slate-100 px-4 font-black">Print / Download QR</button></div>}
      <div className="mt-4 grid gap-3">{qrs.map((qr) => <RowCard key={qr.id || qr._id} title={qr.qrLabel} meta={`${qr.isActive ? "Active" : "Inactive"} / ${branches.find((branch) => (branch.id || branch._id) === qr.branchId)?.branchName || ""}`} action={<div className="flex flex-wrap gap-2"><button onClick={() => regenerate(qr)} className="min-h-11 rounded-2xl bg-slate-100 px-4 font-black">Regenerate</button><button onClick={() => toggleStatus(qr)} className="min-h-11 rounded-2xl bg-slate-100 px-4 font-black">{qr.isActive ? "Set Inactive" : "Set Active"}</button></div>} />)}</div>
    </Panel>
  );
}

function BranchManagersPanel() {
  const [branches, setBranches] = useState([]);
  const [managers, setManagers] = useState([]);
  const [form, setForm] = useState({ name: "", mobile: "", email: "", branchId: "", username: "", password: "", status: "Active" });
  async function load() {
    const [branchRows, managerRows] = await Promise.all([api("/api/branches"), api("/api/branch-managers")]);
    setBranches(branchRows);
    setManagers(managerRows);
    setForm((old) => ({ ...old, branchId: old.branchId || branchRows[0]?.id || "" }));
  }
  useEffect(() => { load().catch(() => null); }, []);
  async function save(event) {
    event.preventDefault();
    await api("/api/branch-managers", { method: "POST", body: form });
    setForm({ ...form, name: "", mobile: "", username: "", password: "" });
    await load();
  }
  return (
    <Panel title="Branch Managers">
      <form onSubmit={save} className="mb-4 grid gap-3 md:grid-cols-3">
        {["name", "mobile", "email", "username", "password"].map((key) => <Input key={key} label={key} value={form[key]} onChange={(value) => setForm({ ...form, [key]: value })} required={["name", "mobile", "username", "password"].includes(key)} />)}
        <label className="block"><span className="mb-1 block text-sm font-bold text-muted">Assigned Branch</span><select className="min-h-12 w-full rounded-2xl border border-line px-4" value={form.branchId} onChange={(event) => setForm({ ...form, branchId: event.target.value })}>{branches.map((branch) => <option key={branch.id || branch._id} value={branch.id || branch._id}>{branch.branchName}</option>)}</select></label>
        <button className="min-h-12 self-end rounded-2xl bg-primary px-5 font-black text-white">Create Branch Manager</button>
      </form>
      <div className="grid gap-3">{managers.map((manager) => <RowCard key={manager.id || manager._id} title={manager.name} meta={`${manager.username} / ${manager.branchName} / ${manager.status}`} />)}</div>
    </Panel>
  );
}

function PremiumFeaturesPanel() {
  function request(name) {
    window.alert(`${name} is a premium feature. Contact Super Admin to enable.`);
  }
  return (
    <Panel title="Premium Features">
      <div className="grid gap-4 md:grid-cols-2">
        <RowCard title="Face Recognition Attendance" meta="Coming Soon / Premium - Verify employee face during attendance for higher security." action={<button onClick={() => request("Face Recognition")} className="min-h-11 rounded-2xl bg-primary px-4 font-black text-white">Request Activation</button>} />
        <RowCard title="Biometric Device Integration" meta="Coming Soon / Premium - Connect fingerprint or biometric machines with NeverLag Work." action={<button onClick={() => request("Biometric Device Integration")} className="min-h-11 rounded-2xl bg-primary px-4 font-black text-white">Request Activation</button>} />
      </div>
    </Panel>
  );
}

function Notifications({ notices }) {
  const [items, setItems] = useState(notices);
  useEffect(() => setItems(notices), [notices]);
  async function read(notice) {
    const id = notice.id || notice._id;
    await api(`/api/notifications/${id}/read`, { method: "PUT" });
    setItems((old) => old.map((item) => (item.id || item._id) === id ? { ...item, read: true } : item));
  }
  return <div className="grid gap-4">{items.map((notice) => <article key={notice.id || notice._id} className="app-card p-5"><strong>{notice.message}</strong><p className="text-sm text-muted">{timeAgo(notice.createdAt)} / {notice.read ? "Read" : "Unread"}</p>{!notice.read && <button onClick={() => read(notice)} className="mt-3 min-h-11 rounded-2xl bg-primary px-4 font-black text-white">Mark Read</button>}</article>)} {!items.length && <EmptyState text="No notifications yet." />}</div>;
}

function SelfieCapture({ onCapture, onClose }) {
  const videoRef = React.useRef(null);
  const streamRef = React.useRef(null);
  const [error, setError] = useState("");
  useEffect(() => {
    navigator.mediaDevices?.getUserMedia({ video: true })
      .then((stream) => {
        streamRef.current = stream;
        if (videoRef.current) videoRef.current.srcObject = stream;
      })
      .catch(() => setError("Camera permission is required for selfie attendance."));
    return () => streamRef.current?.getTracks().forEach((track) => track.stop());
  }, []);
  function capture() {
    const video = videoRef.current;
    if (!video) return;
    const canvas = document.createElement("canvas");
    canvas.width = video.videoWidth || 640;
    canvas.height = video.videoHeight || 480;
    canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
    onCapture(canvas.toDataURL("image/jpeg", 0.82));
  }
  return (
    <motion.div className="fixed inset-0 z-50 bg-navy/60" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <motion.section initial={{ y: "100%" }} animate={{ y: 0 }} exit={{ y: "100%" }} className="absolute bottom-0 left-0 right-0 rounded-t-[2rem] bg-white p-6 shadow-premium">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-2xl">Selfie Attendance</h2>
          <button type="button" onClick={onClose} className="min-h-11 min-w-11 rounded-2xl bg-slate-100 p-2"><X className="h-5 w-5" /></button>
        </div>
        {error ? <p className="rounded-2xl bg-red-50 p-4 font-bold text-danger">{error}</p> : <video ref={videoRef} autoPlay playsInline className="h-80 w-full rounded-3xl bg-slate-100 object-cover" />}
        <div className="mt-4 flex gap-2">
          <button type="button" onClick={capture} className="primary-pill px-6">Capture</button>
          <button type="button" onClick={onClose} className="min-h-12 rounded-2xl bg-slate-100 px-6 font-black">Cancel</button>
        </div>
      </motion.section>
    </motion.div>
  );
}

function QrScanner({ onScan, onClose }) {
  const videoRef = React.useRef(null);
  const streamRef = React.useRef(null);
  const frameRef = React.useRef(null);
  const detectorRef = React.useRef(null);
  const [error, setError] = useState("");

  useEffect(() => {
    let stopped = false;
    async function start() {
      if (!("BarcodeDetector" in window)) {
        setError("QR camera scanning is not supported in this browser. Enter the QR token manually.");
        return;
      }
      detectorRef.current = new window.BarcodeDetector({ formats: ["qr_code"] });
      try {
        const stream = await navigator.mediaDevices?.getUserMedia({ video: { facingMode: "environment" } });
        if (!stream) throw new Error("Camera permission is required to scan QR.");
        streamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          await videoRef.current.play();
        }
        const scan = async () => {
          if (stopped || !videoRef.current || !detectorRef.current) return;
          try {
            const codes = await detectorRef.current.detect(videoRef.current);
            const token = codes?.[0]?.rawValue;
            if (token) {
              onScan(token);
              return;
            }
          } catch {
            setError("Unable to read QR from camera. Try again or enter the token manually.");
          }
          frameRef.current = requestAnimationFrame(scan);
        };
        frameRef.current = requestAnimationFrame(scan);
      } catch (err) {
        setError(err.message || "Camera permission is required to scan QR.");
      }
    }
    start();
    return () => {
      stopped = true;
      if (frameRef.current) cancelAnimationFrame(frameRef.current);
      streamRef.current?.getTracks().forEach((track) => track.stop());
    };
  }, [onScan]);

  return (
    <motion.div className="fixed inset-0 z-50 bg-navy/45" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <motion.section initial={{ y: "100%" }} animate={{ y: 0 }} exit={{ y: "100%" }} className="absolute bottom-0 left-0 right-0 rounded-t-[2rem] bg-white p-6 shadow-premium">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-2xl font-semibold tracking-[-0.04em]">Scan Office QR</h2>
          <button type="button" onClick={onClose} className="min-h-11 min-w-11 rounded-full bg-surface p-2 transition hover:bg-blue-50"><X className="h-5 w-5 text-primary" /></button>
        </div>
        {error ? <p className="rounded-[1.25rem] bg-blue-50 p-4 font-medium text-primary">{error}</p> : <video ref={videoRef} muted playsInline className="h-80 w-full rounded-[1.25rem] bg-surface object-cover" />}
        <button type="button" onClick={onClose} className="secondary-pill mt-4 px-6">Cancel</button>
      </motion.section>
    </motion.div>
  );
}

function NotificationDrawer({ notices, onClose }) {
  return (
    <motion.div className="fixed inset-0 z-50 bg-navy/45" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <motion.aside
        initial={{ x: "100%" }}
        animate={{ x: 0 }}
        exit={{ x: "100%" }}
        transition={{ type: "spring", damping: 28, stiffness: 260 }}
        className="absolute bottom-0 right-0 top-0 w-full max-w-md overflow-y-auto bg-white p-6 shadow-premium"
      >
        <div className="mb-6 flex items-center justify-between">
          <div>
            <h2 className="text-2xl">Notifications</h2>
            <p className="text-sm text-muted">{notices.length} total</p>
          </div>
          <button type="button" onClick={onClose} className="min-h-11 min-w-11 rounded-2xl bg-slate-100 p-2 transition hover:bg-slate-200">
            <X className="h-5 w-5" />
          </button>
        </div>
        <Notifications notices={notices} />
      </motion.aside>
    </motion.div>
  );
}

function Profile() {
  const [form, setForm] = useState({ currentPassword: "", newPassword: "" });
  const [message, setMessage] = useState("");
  async function save(event) {
    event.preventDefault();
    await api("/api/profile/change-password", { method: "PUT", body: form });
    setForm({ currentPassword: "", newPassword: "" });
    setMessage("Password changed");
  }
  return (
    <Panel title="Profile / Change Password">
      <form onSubmit={(event) => save(event).catch((err) => setMessage(err.message))} className="grid max-w-md gap-3">
        <Input label="Current Password" type="password" value={form.currentPassword} onChange={(value) => setForm({ ...form, currentPassword: value })} required />
        <Input label="New Password" type="password" value={form.newPassword} onChange={(value) => setForm({ ...form, newPassword: value })} required />
        <button className="min-h-12 rounded-2xl bg-primary px-5 font-black text-white">Change Password</button>
        {message && <p className="text-sm font-bold text-muted">{message}</p>}
      </form>
    </Panel>
  );
}

function AdminTools() {
  const [health, setHealth] = useState(null);
  const [backups, setBackups] = useState([]);
  const [message, setMessage] = useState("");
  const [secret, setSecret] = useState("demo-secret");
  async function load() {
    const [healthRows, backupRows] = await Promise.all([api("/api/system/health"), api("/api/backups")]);
    setHealth(healthRows);
    setBackups(backupRows);
  }
  useEffect(() => { load().catch((err) => setMessage(err.message)); }, []);
  async function backup() {
    await api("/api/backups/manual", { method: "POST" });
    setMessage("Manual backup created");
    await load();
  }
  async function restore(id) {
    await api("/api/backups/restore", { method: "POST", body: { backupId: id, setupSecret: secret, confirmation: "RESTORE DATA" } });
    setMessage("Backup restored");
    await load();
  }
  async function freshReset() {
    await api("/api/system/fresh-reset", { method: "POST", body: { setupSecret: secret, confirmation: "DELETE ALL DATA" } });
    setMessage("Fresh Reset complete. Login again if session was cleared.");
  }
  return (
    <section className="grid gap-4 lg:grid-cols-2">
      <Panel title="System Health">
        <div className="grid gap-3">{health?.checks?.map((check) => <RowCard key={check.name} title={check.name} meta={`${check.status}${check.message ? ` / ${check.message}` : ""}`} />) || <EmptyState text="Loading health checks..." />}</div>
      </Panel>
      <Panel title="Backups / Restore / Fresh Reset">
        <div className="grid gap-3">
          <Input label="SETUP_SECRET" value={secret} onChange={setSecret} />
          <button onClick={backup} className="min-h-12 rounded-2xl bg-primary px-5 font-black text-white">Manual Backup</button>
          {backups.map((item) => <RowCard key={item.id || item._id} title={item.fileName} meta={`${item.type} / ${item.status}`} action={<button onClick={() => restore(item.id || item._id)} className="min-h-11 rounded-2xl bg-slate-100 px-4 font-black">Restore</button>} />)}
          <button onClick={() => freshReset().catch((err) => setMessage(err.message))} className="min-h-12 rounded-2xl bg-danger px-5 font-black text-white">Fresh Reset</button>
          {message && <p className="text-sm font-bold text-muted">{message}</p>}
        </div>
      </Panel>
    </section>
  );
}

function CompanySettingsPanel() {
  const [settings, setSettings] = useState(null);
  const [message, setMessage] = useState("");
  useEffect(() => { api("/api/company/settings").then(setSettings).catch((err) => setMessage(err.message)); }, []);
  if (!settings) return <EmptyState text={message || "Loading settings..."} />;
  async function save(event) {
    event.preventDefault();
    const saved = await api("/api/company/settings", { method: "PUT", body: settings });
    setSettings(saved);
    setMessage("Settings saved");
  }
  return (
    <Panel title="Company Settings / Office Location">
      <form onSubmit={(event) => save(event).catch((err) => setMessage(err.message))} className="grid gap-3 md:grid-cols-2">
        {["companyName", "officeName", "latitude", "longitude", "radius", "shiftStart", "shiftEnd", "graceMinutes", "fullDayHours", "halfDayHours", "weeklyOff"].map((key) => (
          <Input key={key} label={key.replace(/([A-Z])/g, " $1")} value={settings[key] ?? ""} onChange={(value) => setSettings({ ...settings, [key]: value })} />
        ))}
        {[
          ["enableSelfieAttendance", "Enable Selfie Attendance"],
          ["selfieRequiredOnCheckIn", "Selfie Required On Check In"],
          ["selfieRequiredOnCheckOut", "Selfie Required On Check Out"],
          ["enableQRAttendance", "Enable QR Attendance"],
          ["qrRequiredOnCheckIn", "QR Required On Check In"],
          ["qrRequiredOnCheckOut", "QR Required On Check Out"],
          ["enableMultiBranch", "Enable Multiple Branches"],
          ["allowAnyBranchCheckIn", "Allow Any Branch Check In"],
          ["faceRecognitionEnabled", "Face Recognition Enabled"],
          ["biometricIntegrationEnabled", "Biometric Integration Enabled"],
        ].map(([key, label]) => (
          <label key={key} className="flex min-h-12 items-center justify-between rounded-2xl border border-line px-4">
            <span className="font-bold text-muted">{label}</span>
            <input type="checkbox" checked={Boolean(settings[key])} onChange={(event) => setSettings({ ...settings, [key]: event.target.checked })} className="h-5 w-5 accent-emerald-500" />
          </label>
        ))}
        <button className="min-h-12 rounded-2xl bg-primary px-5 font-black text-white md:col-span-2">Save Settings</button>
        {message && <p className="text-sm font-bold text-muted md:col-span-2">{message}</p>}
      </form>
    </Panel>
  );
}

function Panel({ title, children }) {
  return <section className="app-card p-6"><h2 className="mb-4 text-xl font-semibold tracking-[-0.04em]">{title}</h2>{children}</section>;
}

function RowCard({ title, meta, action }) {
  return <article className="rounded-[1.25rem] border border-line bg-surface p-4"><div className="flex items-center justify-between gap-3"><div><strong className="font-medium">{title}</strong><p className="text-sm text-muted">{meta}</p></div>{action}</div></article>;
}

function Input({ label, value, onChange, type = "text", required = false }) {
  return <label className="block"><span className="mb-1 block text-sm font-medium capitalize text-muted">{label}</span><input required={required} type={type} value={value} onChange={(event) => onChange(event.target.value)} className="min-h-12 w-full rounded-full border border-line px-4 outline-none focus:ring-4 focus:ring-primary/20" /></label>;
}

function ReportCard({ title, rows, kinds, fileName }) {
  return (
    <Panel title={title}>
      <div className="mb-4 grid gap-2">{kinds.map((kind) => <RowCard key={kind} title={kind} meta={`${rows.length} records available`} />)}</div>
      <div className="flex flex-wrap gap-2">
        <button onClick={() => exportCsv(fileName, rows)} className="min-h-11 rounded-2xl bg-primary px-5 font-black text-white">Export CSV</button>
        <button onClick={() => exportCsv(fileName.replace(".csv", ".xls"), rows)} className="min-h-11 rounded-2xl bg-slate-100 px-5 font-black">Export Excel</button>
        <button onClick={() => window.print()} className="min-h-11 rounded-2xl bg-slate-100 px-5 font-black">Export PDF</button>
      </div>
    </Panel>
  );
}

function exportCsv(fileName, rows) {
  const safeRows = rows.length ? rows : [{ message: "No records" }];
  const headers = Object.keys(safeRows[0]);
  const csv = [headers.join(","), ...safeRows.map((row) => headers.map((key) => `"${String(row[key] ?? "").replaceAll('"', '""')}"`).join(","))].join("\n");
  const url = URL.createObjectURL(new Blob([csv], { type: "text/csv" }));
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(url);
}

async function downloadSalaryPdf(slip) {
  try {
    const id = slip.id || slip._id;
    const token = sessionStorage.getItem("authToken");
    const response = await fetch(`${API_BASE}/api/employee-salary/slips/${id}/download`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(text || "Unable to download PDF");
    }
    const blob = await response.blob();
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `${slip.slipNumber || "salary-slip"}.pdf`;
    link.click();
    URL.revokeObjectURL(url);
  } catch (error) {
    window.alert(error.message || "Unable to download PDF");
  }
}

function HeroGreeting({ title, subtitle }) {
  return <section className="app-card premium-glow overflow-hidden p-6 sm:p-8"><p className="font-medium text-muted">{subtitle}</p><h2 className="gradient-text mt-3 max-w-2xl text-[32px] font-semibold leading-tight tracking-[-0.04em] sm:text-5xl">{title}</h2></section>;
}

function Info({ label, value }) {
  return <div className="rounded-[1.25rem] bg-surface p-4"><p className="text-xs font-medium text-muted">{label}</p><strong className="font-semibold">{value || "-"}</strong></div>;
}

function StatusBadge({ status }) {
  const color = status === "Present" || status === "Paid" ? "green" : status === "Late" || status === "Pending" ? "orange" : status === "Absent" ? "red" : "blue";
  return <span className={`inline-flex min-h-7 items-center rounded-full px-3 py-1 text-xs font-black ${statColors[color]}`}>{status}</span>;
}

function Toast({ message, onClose }) {
  useEffect(() => {
    const id = setTimeout(onClose, 3200);
    return () => clearTimeout(id);
  }, [onClose]);
  return <motion.div initial={{ opacity: 0, x: 80 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: 80 }} className="fixed right-4 top-4 z-50 rounded-full bg-primary px-5 py-4 font-semibold text-white shadow-lift">{message}</motion.div>;
}

function EmptyState({ text }) {
  return <div className="app-card p-8 text-center font-bold text-muted">{text}</div>;
}

function safeJson(value) {
  try {
    return value ? JSON.parse(value) : null;
  } catch {
    return null;
  }
}

function time(value) {
  return value ? new Date(value).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "-";
}

function timeAgo(value) {
  if (!value) return "";
  const minutes = Math.max(1, Math.round((Date.now() - new Date(value).getTime()) / 60000));
  return `${minutes} min ago`;
}

function initials(name) {
  return String(name || "Employee").split(" ").map((item) => item[0]).join("").slice(0, 2).toUpperCase();
}

function getLocation() {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) return reject(new Error("GPS Required"));
    navigator.geolocation.getCurrentPosition(
      (position) => resolve({ lat: position.coords.latitude, lng: position.coords.longitude }),
      () => reject(new Error("GPS permission is required."))
    );
  });
}

createRoot(document.getElementById("root")).render(<App />);
