"use client";

import { useState, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Building2, Phone, Mail, Globe, Save, Plus, Trash2,
  GripVertical, Users, Clock, ChevronRight, CheckCircle2, Loader2,
  Shield, Pencil, X, Eye, EyeOff, UserPlus, Send, TestTube,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { API, authFetch } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";
import { clearCompanyNameCache } from "@/lib/pdf";

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

interface OrgSettings {
  name: string;
  legalName: string;
  industry: string;
  address: string;
  city: string;
  phone: string;
  email: string;
  website: string;
  ntn: string;
  eobi: string;
  pessi: string;
  workingHours: string;
  workingDays: string;
  dutyStart: string;
  dutyEnd: string;
  breakMinutes: string;
  eobiEmployerRate?: string;
  eobiEmployeeRate?: string;
  pessiEmployerRate?: string;
  pessiEmployeeRate?: string;
  minimumWage?: string;
  holidayRules?: { title?: string; from: string; to?: string; paid?: boolean }[];
  annualLeaveDays?: string;
  sickLeaveDays?: string;
  casualLeaveDays?: string;
  salaryDivisor?: string;
  dynamicSalaryDivisor?: boolean;
  timezone: string;
}

interface Shift {
  id: string;
  name: string;
  departments: string[];
  startTime: string;
  endTime: string;
  breakMinutes: number;
  gracePeriodMinutes: number;
  lateDeductionMinutes: number;
  overtimeGraceMinutes: number;
  overtimeRateMultiplier: number;
  workingDays: string;
}

interface UserRow {
  id: string;
  email: string;
  name: string;
  role: string;
  isActive: boolean;
  permissions: string | null;
  effectivePermissions: string[];
  createdAt: string;
}

interface PermConfig {
  allPermissions: string[];
  rolePermissions: Record<string, string[]>;
  permissionGroups: Record<string, string[]>;
}

const ROLE_OPTIONS = [
  { value: "ADMIN", label: "HR ADMIN" },
  { value: "HR_MANAGER", label: "HR Manager" },
  { value: "COMPLIANCE_OFFICER", label: "Compliance Officer" },
  { value: "SUPERVISOR", label: "Supervisor" },
  { value: "VIEWER", label: "Viewer" },
  { value: "EMPLOYEE", label: "Employee" },
];

/* ------------------------------------------------------------------ */
/*  Settings Page                                                      */
/* ------------------------------------------------------------------ */

export default function SettingsPage() {
  const { isSuperAdmin } = useAuth();

  const allTabs = [
    { id: "org", label: "Organisation", icon: Building2 },
    { id: "departments", label: "Departments", icon: Users },
    { id: "designations", label: "Designations", icon: ChevronRight },
    { id: "shifts", label: "Shifts", icon: Clock },
    { id: "hr", label: "HR Defaults", icon: Clock },
    { id: "email", label: "Email & SMTP", icon: Send },
    ...(isSuperAdmin ? [{ id: "users", label: "User Accounts", icon: Shield }] : []),
  ];

  const [activeTab, setActiveTab] = useState("org");
  const [saveState, setSaveState] = useState<"idle" | "saving" | "saved">("idle");
  const [isLoading, setIsLoading] = useState(true);

  const [org, setOrg] = useState<OrgSettings>({
    name: "Colour Club Studio",
    legalName: "",
    industry: "Textile / Garments",
    address: "",
    city: "Lahore",
    phone: "",
    email: "",
    website: "",
    ntn: "",
    eobi: "",
    pessi: "",
    workingHours: "8",
    workingDays: "6",
    dutyStart: "09:00",
    dutyEnd: "17:00",
    breakMinutes: "0",
    eobiEmployerRate: "",
    eobiEmployeeRate: "",
    pessiEmployerRate: "",
    pessiEmployeeRate: "",
    annualLeaveDays: "14",
    sickLeaveDays: "10",
    casualLeaveDays: "10",
    salaryDivisor: "26",
    dynamicSalaryDivisor: false,
    timezone: "Asia/Karachi",
  });

  const [departments, setDepartments] = useState<string[]>([]);
  const [newDept, setNewDept] = useState("");
  const [designations, setDesignations] = useState<string[]>([]);
  const [newDesig, setNewDesig] = useState("");
  const [shifts, setShifts] = useState<Shift[]>([]);
  const [newShift, setNewShift] = useState<Omit<Shift, "id">>({ name: "", departments: [], startTime: "09:00", endTime: "17:00", breakMinutes: 0, gracePeriodMinutes: 0, lateDeductionMinutes: 0, overtimeGraceMinutes: 15, overtimeRateMultiplier: 1.5, workingDays: "6" });
  const [editingShiftId, setEditingShiftId] = useState<string | null>(null);

  const [newHoliday, setNewHoliday] = useState({
    title: "",
    from: "",
    to: "",
    paid: true,
  });
  const [holidayYear, setHolidayYear] = useState(String(new Date().getFullYear()));
  const [holidayDates, setHolidayDates] = useState<string[]>([]);
  const [holidaysLoading, setHolidaysLoading] = useState(false);

  // Email/SMTP Configuration State
  const [emailConfig, setEmailConfig] = useState({
    smtpHost: "",
    smtpPort: "587",
    smtpSecure: false,
    smtpUser: "",
    smtpPassword: "",
    fromEmail: "",
    fromName: "",
    enableOnboardingEmail: true,
    enableSalaryEmail: true,
    enableAttendanceEmail: false,
    enableLeaveEmail: true,
  });
  const [showPassword, setShowPassword] = useState(false);
  const [testEmailLoading, setTestEmailLoading] = useState(false);
  const [cleaningCompliance, setCleaningCompliance] = useState(false);

  useEffect(() => {
    authFetch(`${API}/settings`)
      .then((r) => r.json())
      .then((data) => {
        setOrg({
          name: data.name ?? "",
          legalName: data.legalName ?? "",
          industry: data.industry ?? "Textile / Garments",
          address: data.address ?? "",
          city: data.city ?? "",
          phone: data.phone ?? "",
          email: data.email ?? "",
          website: data.website ?? "",
          ntn: data.ntn ?? "",
          eobi: data.eobi ?? "",
          pessi: data.pessi ?? "",
          workingHours: data.workingHours ?? "9",
          workingDays: data.workingDays ?? "6",
          dutyStart: data.dutyStart ?? "09:00",
          dutyEnd: data.dutyEnd ?? "17:00",
          breakMinutes: String(data.breakMinutes ?? 0),
          eobiEmployerRate: data.eobiEmployerRate != null ? String(data.eobiEmployerRate) : "",
          eobiEmployeeRate: data.eobiEmployeeRate != null ? String(data.eobiEmployeeRate) : "",
          pessiEmployerRate: data.pessiEmployerRate != null ? String(data.pessiEmployerRate) : "",
          pessiEmployeeRate: data.pessiEmployeeRate != null ? String(data.pessiEmployeeRate) : "",
          minimumWage: data.minimumWage != null ? String(data.minimumWage) : "40000",
          annualLeaveDays: data.annualLeaveDays != null ? String(data.annualLeaveDays) : "14",
          sickLeaveDays: data.sickLeaveDays != null ? String(data.sickLeaveDays) : "10",
          casualLeaveDays: data.casualLeaveDays != null ? String(data.casualLeaveDays) : "10",
          salaryDivisor: data.salaryDivisor != null ? String(data.salaryDivisor) : "26",
          dynamicSalaryDivisor: !!data.dynamicSalaryDivisor,
          timezone: data.timezone ?? "Asia/Karachi",
          holidayRules: (() => { try { const p = typeof data.holidayCalendar === "string" ? JSON.parse(data.holidayCalendar) : data.holidayCalendar; return Array.isArray(p) ? p : []; } catch { return []; } })(),
        });
          const parseCsv = (v: unknown): string[] => typeof v === "string" && v.trim() ? v.split(",").map((s) => s.trim()).filter(Boolean) : [];
        setDepartments(parseCsv(data.departments));
        setDesignations(parseCsv(data.designations));
        try { setShifts(typeof data.shifts === "string" ? JSON.parse(data.shifts) : (Array.isArray(data.shifts) ? data.shifts : [])); } catch { setShifts([]); }
        
        // Load email configuration
        if (data.emailConfig) {
          setEmailConfig({
            smtpHost: data.emailConfig.smtpHost || "",
            smtpPort: data.emailConfig.smtpPort || "587",
            smtpSecure: data.emailConfig.smtpSecure || false,
            smtpUser: data.emailConfig.smtpUser || "",
            smtpPassword: data.emailConfig.smtpPassword || "",
            fromEmail: data.emailConfig.fromEmail || "",
            fromName: data.emailConfig.fromName || "",
            enableOnboardingEmail: data.emailConfig.enableOnboardingEmail !== false,
            enableSalaryEmail: data.emailConfig.enableSalaryEmail !== false,
            enableAttendanceEmail: data.emailConfig.enableAttendanceEmail || false,
            enableLeaveEmail: data.emailConfig.enableLeaveEmail !== false,
          });
        }
      })
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, []);

  const saveShifts = async (updated: Shift[]) => {
    await authFetch(`${API}/settings`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ shifts: JSON.stringify(updated) }),
    });
  };

  const addShift = () => {
    if (!newShift.name.trim()) return;
    const updated = [...shifts, { ...newShift, id: Date.now().toString() }];
    setShifts(updated);
    saveShifts(updated);
    setNewShift({ name: "", departments: [], startTime: "09:00", endTime: "17:00", breakMinutes: 0, gracePeriodMinutes: 0, lateDeductionMinutes: 0, overtimeGraceMinutes: 15, overtimeRateMultiplier: 1.5, workingDays: "6" });
  };

  const removeShift = (id: string) => {
    const updated = shifts.filter((s) => s.id !== id);
    setShifts(updated);
    saveShifts(updated);
  };

  const updateShift = (id: string, patch: Partial<Shift>) => {
    const updated = shifts.map((s) => s.id === id ? { ...s, ...patch } : s);
    setShifts(updated);
    saveShifts(updated);
  };

  const handleSave = async () => {
    setSaveState("saving");
    try {
      const res = await authFetch(`${API}/settings`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
          ...org, 
          departments, 
          designations, 
          shifts: JSON.stringify(shifts),
          emailConfig 
        }),
      });
      if (!res.ok) throw new Error("Save failed");
      clearCompanyNameCache(); // Clear so PDFs get updated company name
      setSaveState("saved");
      setTimeout(() => setSaveState("idle"), 2500);
    } catch {
      setSaveState("idle");
      alert("Failed to save settings. Make sure the backend is running.");
    }
  };

  const patchSettings = async (patch: object) => {
    try {
      const res = await authFetch(`${API}/settings`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(patch),
      });
      if (!res.ok) throw new Error();
    } catch {
      alert("Failed to save. Make sure the backend is running.");
    }
  };

  const addDept = () => {
    const v = newDept.trim();
    if (!v || departments.includes(v)) return;
    const updated = [...departments, v];
    setDepartments(updated);
    setNewDept("");
    patchSettings({ departments: updated, designations });
  };

  const removeDept = (d: string) => {
    const updated = departments.filter((x) => x !== d);
    setDepartments(updated);
    patchSettings({ departments: updated, designations });
  };

  const addDesig = () => {
    const v = newDesig.trim();
    if (!v || designations.includes(v)) return;
    const updated = [...designations, v];
    setDesignations(updated);
    setNewDesig("");
    patchSettings({ departments, designations: updated });
  };

  const removeDesig = (d: string) => {
    const updated = designations.filter((x) => x !== d);
    setDesignations(updated);
    patchSettings({ departments, designations: updated });
  };

  const fetchPakistanHolidays = async () => {
    setHolidaysLoading(true);
    try {
      const yr = Number(holidayYear) || new Date().getFullYear();
      const res = await authFetch(`${API}/settings/holidays/pakistan?year=${yr}`);
      if (!res.ok) throw new Error("Failed");
      const data = await res.json();
      setHolidayDates(Array.isArray(data.holidays) ? data.holidays : []);
    } catch {
      alert("Failed to fetch Pakistan holidays.");
    } finally {
      setHolidaysLoading(false);
    }
  };

  const handleTestEmail = async () => {
    if (!emailConfig.smtpHost || !emailConfig.smtpUser || !emailConfig.fromEmail) {
      alert("Please configure SMTP host, username, and from email first.");
      return;
    }

    setTestEmailLoading(true);
    try {
      const res = await authFetch(`${API}/settings/test-email`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(emailConfig),
      });
      
      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.message || "Failed to send test email");
      }
      
      alert("Test email sent successfully! Please check your inbox.");
    } catch (error: any) {
      alert(`Failed to send test email: ${error.message}`);
    } finally {
      setTestEmailLoading(false);
    }
  };

  const handleCleanCompliance = async () => {
    if (!confirm("Are you sure you want to clean the compliance database? This will delete all attendance, payroll, and punch records. This action cannot be undone.")) return;
    
    setCleaningCompliance(true);
    try {
      const res = await authFetch(`${API}/dashboard/clean-compliance`, { method: "POST" });
      const data = await res.json();
      
      if (res.ok) {
        alert(`Compliance database cleaned successfully.\nDeleted:\n- ${data.deleted.salaryIncrements} salary increment records\n- ${data.deleted.punches} punches\n- ${data.deleted.attendance} attendance records\n- ${data.deleted.payroll} payroll records`);
      } else {
        throw new Error(data.error || "Failed to clean compliance database");
      }
    } catch (error: any) {
      alert(`Failed to clean compliance: ${error.message}`);
    } finally {
      setCleaningCompliance(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64 text-gray-400">
        <Loader2 className="h-6 w-6 animate-spin mr-2" /> Loading settings...
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold leading-7 text-gray-900 sm:text-3xl sm:tracking-tight">
            Settings
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            Manage your organisation profile, departments, and HR defaults.
          </p>
        </div>
        {activeTab !== "users" && (
          <button
            onClick={handleSave}
            disabled={saveState === "saving"}
            className={cn(
              "inline-flex items-center gap-2 rounded-lg px-5 py-2.5 text-sm font-semibold shadow-sm transition-all disabled:opacity-60",
              saveState === "saved"
                ? "bg-green-600 text-white"
                : "bg-brand-600 text-white hover:bg-brand-700"
            )}
          >
            {saveState === "saving" ? (
              <><Loader2 className="h-4 w-4 animate-spin" /> Saving...</>
            ) : saveState === "saved" ? (
              <><CheckCircle2 className="h-4 w-4" /> Saved!</>
            ) : (
              <><Save className="h-4 w-4" /> Save Changes</>
            )}
          </button>
        )}
      </div>

      <div className="flex gap-6">
        <div className="w-48 flex-shrink-0">
          <nav className="space-y-1">
            {allTabs.map((t) => (
              <button
                key={t.id}
                onClick={() => setActiveTab(t.id)}
                className={cn(
                  "w-full flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-left transition-colors",
                  activeTab === t.id
                    ? "bg-brand-50 text-brand-700 ring-1 ring-brand-100"
                    : "text-gray-600 hover:bg-gray-100"
                )}
              >
                <t.icon className={cn("h-4 w-4 flex-shrink-0", activeTab === t.id ? "text-brand-600" : "text-gray-400")} />
                {t.label}
              </button>
            ))}
          </nav>
        </div>

        <div className="flex-1 min-w-0">
          <motion.div
            key={activeTab}
            initial={{ opacity: 0, y: 6 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.18 }}
          >

            {activeTab === "org" && (
              <div className="space-y-6">
                <Section title="Company Identity">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Field label="Display Name">
                      <input value={org.name} onChange={e => setOrg({ ...org, name: e.target.value })} placeholder="Colour Club Studio" className={inputCls} />
                    </Field>
                    <Field label="Legal / Registered Name">
                      <input value={org.legalName} onChange={e => setOrg({ ...org, legalName: e.target.value })} placeholder="Colour Club Studio (Pvt) Ltd" className={inputCls} />
                    </Field>
                    <Field label="Industry">
                      <select value={org.industry} onChange={e => setOrg({ ...org, industry: e.target.value })} className={inputCls}>
                        <option>Textile / Garments</option>
                        <option>Printing Press</option>
                        <option>Manufacturing</option>
                        <option>Retail</option>
                        <option>IT / Technology</option>
                        <option>Food &amp; Beverage</option>
                        <option>Construction</option>
                        <option>Healthcare</option>
                        <option>Education</option>
                        <option>Other</option>
                      </select>
                    </Field>
                    <Field label="City">
                      <input value={org.city} onChange={e => setOrg({ ...org, city: e.target.value })} placeholder="Lahore" className={inputCls} />
                    </Field>
                    <Field label="System Timezone">
                      <select value={org.timezone} onChange={e => setOrg({ ...org, timezone: e.target.value })} className={inputCls}>
                        <option value="Asia/Karachi">Pakistan (Asia/Karachi)</option>
                        <option value="UTC">UTC</option>
                        <option value="Asia/Dubai">Gulf Standard Time (Asia/Dubai)</option>
                        <option value="Asia/Riyadh">Saudi Arabia (Asia/Riyadh)</option>
                        <option value="Europe/London">London (Europe/London)</option>
                        <option value="America/New_York">New York (America/New_York)</option>
                      </select>
                    </Field>
                  </div>
                  <Field label="Registered Address">
                    <textarea rows={2} value={org.address} onChange={e => setOrg({ ...org, address: e.target.value })} placeholder="Street, Area, City" className={inputCls + " resize-none"} />
                  </Field>
                </Section>

                <Section title="Contact Information">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Field label="Phone Number" icon={<Phone className="h-3.5 w-3.5 text-gray-400" />}>
                      <input value={org.phone} onChange={e => setOrg({ ...org, phone: e.target.value })} placeholder="+92-300-0000000" className={inputCls} />
                    </Field>
                    <Field label="Email Address" icon={<Mail className="h-3.5 w-3.5 text-gray-400" />}>
                      <input type="email" value={org.email} onChange={e => setOrg({ ...org, email: e.target.value })} placeholder="hr@company.com" className={inputCls} />
                    </Field>
                    <Field label="Website" icon={<Globe className="h-3.5 w-3.5 text-gray-400" />}>
                      <input value={org.website} onChange={e => setOrg({ ...org, website: e.target.value })} placeholder="https://yourcompany.com" className={inputCls} />
                    </Field>
                  </div>
                </Section>

                <Section title="Statutory Registration Numbers">
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <Field label="NTN Number">
                      <input value={org.ntn} onChange={e => setOrg({ ...org, ntn: e.target.value })} placeholder="e.g. 1234567-8" className={inputCls + " font-mono"} />
                    </Field>
                    <Field label="EOBI Registration No.">
                      <input value={org.eobi} onChange={e => setOrg({ ...org, eobi: e.target.value })} placeholder="e.g. EOBI-XXXXX" className={inputCls + " font-mono"} />
                    </Field>
                    <Field label="PESSI Registration No.">
                      <input value={org.pessi} onChange={e => setOrg({ ...org, pessi: e.target.value })} placeholder="e.g. PESSI-XXXXX" className={inputCls + " font-mono"} />
                    </Field>
                  </div>
                </Section>
              </div>
            )}

            {activeTab === "departments" && (
              <Section title="Departments" description="These departments appear in employee forms and reports.">
                <div className="flex gap-2 mb-4">
                  <input
                    value={newDept}
                    onChange={e => setNewDept(e.target.value)}
                    onKeyDown={e => e.key === "Enter" && (e.preventDefault(), addDept())}
                    placeholder="New department name..."
                    className={inputCls + " flex-1"}
                  />
                  <button
                    onClick={addDept}
                    className="inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors"
                  >
                    <Plus className="h-4 w-4" /> Add
                  </button>
                </div>
                <ul className="space-y-2">
                  {departments.map((d) => (
                    <motion.li
                      key={d}
                      layout
                      initial={{ opacity: 0, x: -8 }}
                      animate={{ opacity: 1, x: 0 }}
                      className="flex items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-3 shadow-sm"
                    >
                      <div className="flex items-center gap-3">
                        <GripVertical className="h-4 w-4 text-gray-300" />
                        <span className="text-sm font-medium text-gray-800">{d}</span>
                      </div>
                      <button onClick={() => removeDept(d)} className="text-gray-400 hover:text-red-500 transition-colors">
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </motion.li>
                  ))}
                </ul>
                {departments.length === 0 && (
                  <p className="text-sm text-gray-400 text-center py-8">No departments yet. Add one above.</p>
                )}
              </Section>
            )}

            {activeTab === "designations" && (
              <Section title="Designations / Job Titles" description="Used in employee forms as designation suggestions.">
                <div className="flex gap-2 mb-4">
                  <input
                    value={newDesig}
                    onChange={e => setNewDesig(e.target.value)}
                    onKeyDown={e => e.key === "Enter" && (e.preventDefault(), addDesig())}
                    placeholder="New designation title..."
                    className={inputCls + " flex-1"}
                  />
                  <button
                    onClick={addDesig}
                    className="inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors"
                  >
                    <Plus className="h-4 w-4" /> Add
                  </button>
                </div>
                <ul className="space-y-2">
                  {designations.map((d) => (
                    <motion.li
                      key={d}
                      layout
                      initial={{ opacity: 0, x: -8 }}
                      animate={{ opacity: 1, x: 0 }}
                      className="flex items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-3 shadow-sm"
                    >
                      <div className="flex items-center gap-3">
                        <GripVertical className="h-4 w-4 text-gray-300" />
                        <span className="text-sm font-medium text-gray-800">{d}</span>
                      </div>
                      <button onClick={() => removeDesig(d)} className="text-gray-400 hover:text-red-500 transition-colors">
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </motion.li>
                  ))}
                </ul>
                {designations.length === 0 && (
                  <p className="text-sm text-gray-400 text-center py-8">No designations yet. Add one above.</p>
                )}
              </Section>
            )}

            {activeTab === "shifts" && (
              <div className="space-y-6">
                <Section title="Shift Management" description="Define shift schedules and assign them to departments.">
                  {/* New shift form */}
                  <div className="rounded-xl border border-brand-100 bg-brand-50/50 p-4 space-y-4">
                    <h4 className="text-sm font-semibold text-brand-800">Add New Shift</h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Shift Name</label>
                        <input
                          value={newShift.name}
                          onChange={e => setNewShift({ ...newShift, name: e.target.value })}
                          placeholder="e.g. Morning Shift"
                          className={inputCls}
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Working Days / Week</label>
                        <select value={newShift.workingDays} onChange={e => setNewShift({ ...newShift, workingDays: e.target.value })} className={inputCls}>
                          {["5","6","7"].map(d => <option key={d} value={d}>{d} days</option>)}
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Start Time</label>
                        <input type="time" value={newShift.startTime} onChange={e => setNewShift({ ...newShift, startTime: e.target.value })} className={inputCls} />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">End Time</label>
                        <input type="time" value={newShift.endTime} onChange={e => setNewShift({ ...newShift, endTime: e.target.value })} className={inputCls} />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Break (minutes)</label>
                        <input type="number" min="0" value={newShift.breakMinutes} onChange={e => setNewShift({ ...newShift, breakMinutes: Number(e.target.value) })} className={inputCls} />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Grace Period (minutes)</label>
                        <input type="number" min="0" value={newShift.gracePeriodMinutes} onChange={e => setNewShift({ ...newShift, gracePeriodMinutes: Number(e.target.value) })} className={inputCls} placeholder="e.g. 15" />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Late Penalty (fixed minutes)</label>
                        <p className="text-xs text-gray-400 mb-1">Deducted + actual late minutes on arrival after grace</p>
                        <input type="number" min="0" value={newShift.lateDeductionMinutes} onChange={e => setNewShift({ ...newShift, lateDeductionMinutes: Number(e.target.value) })} className={inputCls} placeholder="e.g. 30" />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Overtime Grace (minutes)</label>
                        <p className="text-xs text-gray-400 mb-1">Must work this many extra minutes past end time before OT counts</p>
                        <input type="number" min="0" value={newShift.overtimeGraceMinutes} onChange={e => setNewShift({ ...newShift, overtimeGraceMinutes: Number(e.target.value) })} className={inputCls} placeholder="e.g. 15" />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">OT Rate Multiplier</label>
                        <p className="text-xs text-gray-400 mb-1">Hourly rate × this = OT pay per hour (e.g. 1.5)</p>
                        <input type="number" min="1" step="0.1" value={newShift.overtimeRateMultiplier} onChange={e => setNewShift({ ...newShift, overtimeRateMultiplier: Number(e.target.value) })} className={inputCls} placeholder="1.5" />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Assigned Departments</label>
                        <div className="flex flex-wrap gap-2 mt-1">
                          {departments.map(dept => (
                            <label key={dept} className="flex items-center gap-1.5 text-xs cursor-pointer">
                              <input
                                type="checkbox"
                                checked={newShift.departments.includes(dept)}
                                onChange={e => setNewShift({
                                  ...newShift,
                                  departments: e.target.checked
                                    ? [...newShift.departments, dept]
                                    : newShift.departments.filter(d => d !== dept)
                                })}
                                className="rounded border-gray-300 text-brand-600"
                              />
                              <span className="text-gray-700 font-medium">{dept}</span>
                            </label>
                          ))}
                          {departments.length === 0 && <span className="text-xs text-gray-400">Add departments first in the Departments tab.</span>}
                        </div>
                      </div>
                    </div>
                    <button
                      onClick={addShift}
                      disabled={!newShift.name.trim()}
                      className="inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-700 disabled:opacity-50 transition-colors"
                    >
                      <Plus className="h-4 w-4" /> Add Shift
                    </button>
                  </div>

                  {/* Existing shifts */}
                  <div className="space-y-3">
                    {shifts.length === 0 && (
                      <p className="text-sm text-gray-400 text-center py-8">No shifts defined yet. Add one above.</p>
                    )}
                    {shifts.map(shift => (
                      <div key={shift.id} className="rounded-xl border border-gray-200 bg-white shadow-sm overflow-hidden">
                        {editingShiftId === shift.id ? (
                          <div className="p-4 space-y-4">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Shift Name</label>
                                <input value={shift.name} onChange={e => updateShift(shift.id, { name: e.target.value })} className={inputCls} />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Working Days</label>
                                <select value={shift.workingDays} onChange={e => updateShift(shift.id, { workingDays: e.target.value })} className={inputCls}>
                                  {["5","6","7"].map(d => <option key={d} value={d}>{d} days</option>)}
                                </select>
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Start Time</label>
                                <input type="time" value={shift.startTime} onChange={e => updateShift(shift.id, { startTime: e.target.value })} className={inputCls} />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">End Time</label>
                                <input type="time" value={shift.endTime} onChange={e => updateShift(shift.id, { endTime: e.target.value })} className={inputCls} />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Break (minutes)</label>
                                <input type="number" min="0" value={shift.breakMinutes} onChange={e => updateShift(shift.id, { breakMinutes: Number(e.target.value) })} className={inputCls} />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Grace Period (minutes)</label>
                                <input type="number" min="0" value={shift.gracePeriodMinutes ?? 0} onChange={e => updateShift(shift.id, { gracePeriodMinutes: Number(e.target.value) })} className={inputCls} placeholder="e.g. 15" />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Late Penalty (fixed minutes)</label>
                                <p className="text-xs text-gray-400 mb-1">Deducted + actual late minutes on arrival after grace</p>
                                <input type="number" min="0" value={shift.lateDeductionMinutes ?? 0} onChange={e => updateShift(shift.id, { lateDeductionMinutes: Number(e.target.value) })} className={inputCls} placeholder="e.g. 30" />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Overtime Grace (minutes)</label>
                                <p className="text-xs text-gray-400 mb-1">Must work this many extra minutes past end time before OT counts</p>
                                <input type="number" min="0" value={shift.overtimeGraceMinutes ?? 15} onChange={e => updateShift(shift.id, { overtimeGraceMinutes: Number(e.target.value) })} className={inputCls} placeholder="e.g. 15" />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">OT Rate Multiplier</label>
                                <p className="text-xs text-gray-400 mb-1">Hourly rate × this = OT pay per hour (e.g. 1.5)</p>
                                <input type="number" min="1" step="0.1" value={shift.overtimeRateMultiplier ?? 1.5} onChange={e => updateShift(shift.id, { overtimeRateMultiplier: Number(e.target.value) })} className={inputCls} placeholder="1.5" />
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Departments</label>
                                <div className="flex flex-wrap gap-2 mt-1">
                                  {departments.map(dept => (
                                    <label key={dept} className="flex items-center gap-1.5 text-xs cursor-pointer">
                                      <input
                                        type="checkbox"
                                        checked={shift.departments.includes(dept)}
                                        onChange={e => updateShift(shift.id, {
                                          departments: e.target.checked
                                            ? [...shift.departments, dept]
                                            : shift.departments.filter(d => d !== dept)
                                        })}
                                        className="rounded border-gray-300 text-brand-600"
                                      />
                                      <span className="text-gray-700 font-medium">{dept}</span>
                                    </label>
                                  ))}
                                </div>
                              </div>
                            </div>
                            <button onClick={() => setEditingShiftId(null)} className="text-sm font-semibold text-brand-600 hover:underline">Done</button>
                          </div>
                        ) : (
                          <div className="flex items-center justify-between px-4 py-3">
                            <div className="space-y-1">
                              <p className="text-sm font-semibold text-gray-900">{shift.name}</p>
                              <div className="flex flex-wrap gap-3 text-xs text-gray-500">
                                <span className="flex items-center gap-1"><Clock className="h-3 w-3" />{shift.startTime} – {shift.endTime}</span>
                                <span>{shift.workingDays} days/week</span>
                                <span>{shift.breakMinutes}m break</span>
                                {(shift.gracePeriodMinutes ?? 0) > 0 && <span>{shift.gracePeriodMinutes}m grace</span>}
                                {(shift.lateDeductionMinutes ?? 0) > 0 && <span>{shift.lateDeductionMinutes}m penalty</span>}
                                {(shift.overtimeGraceMinutes ?? 0) > 0 && <span>OT after {shift.overtimeGraceMinutes}m · ×{shift.overtimeRateMultiplier ?? 1.5}</span>}
                                {shift.departments.length > 0 && (
                                  <span className="flex gap-1">
                                    {shift.departments.map(d => (
                                      <span key={d} className="rounded-full bg-brand-50 text-brand-700 px-2 py-0.5 font-medium">{d}</span>
                                    ))}
                                  </span>
                                )}
                              </div>
                            </div>
                            <div className="flex items-center gap-2">
                              <button onClick={() => setEditingShiftId(shift.id)} className="text-gray-400 hover:text-brand-600 transition-colors">
                                <Pencil className="h-4 w-4" />
                              </button>
                              <button onClick={() => removeShift(shift.id)} className="text-gray-400 hover:text-red-500 transition-colors">
                                <Trash2 className="h-4 w-4" />
                              </button>
                            </div>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </Section>
              </div>
            )}

            {activeTab === "hr" && (
              <div className="space-y-6">
                <Section title="Working Schedule">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Field label="Duty Start Time">
                      <input type="time" value={org.dutyStart} onChange={e => setOrg({ ...org, dutyStart: e.target.value })} className={inputCls} />
                    </Field>
                    <Field label="Duty End Time">
                      <input type="time" value={org.dutyEnd} onChange={e => setOrg({ ...org, dutyEnd: e.target.value })} className={inputCls} />
                    </Field>
                    <Field label="Working Hours per Day">
                      <input type="number" min={1} max={24} value={org.workingHours} onChange={e => setOrg({ ...org, workingHours: e.target.value })} className={inputCls} />
                    </Field>
                    <Field label="Working Days per Week">
                      <select value={org.workingDays} onChange={e => setOrg({ ...org, workingDays: e.target.value })} className={inputCls}>
                        <option value="5">5 Days (Mon-Fri)</option>
                        <option value="6">6 Days (Mon-Sat)</option>
                        <option value="7">7 Days</option>
                      </select>
                    </Field>
                    <Field label="Break Time (minutes)">
                      <input type="number" min={0} max={180} value={org.breakMinutes} onChange={e => setOrg({ ...org, breakMinutes: e.target.value })} className={inputCls} />
                    </Field>
                    <Field label="Monthly Working Days (Salary Divisor)">
                      <input type="number" min={1} max={31} value={org.salaryDivisor} onChange={e => setOrg({ ...org, salaryDivisor: e.target.value })} className={inputCls} placeholder="e.g. 30" />
                      <p className="mt-1 text-[10px] text-gray-400">This number will be used to divide your monthly salary to get the daily/hourly rate for OT and deductions.</p>
                    </Field>
                  </div>
                  {org.dutyStart && org.dutyEnd && (
                    <p className="mt-2 text-xs text-gray-400">
                      Shift: {org.dutyStart} &ndash; {org.dutyEnd} &nbsp;&middot;&nbsp;
                      Arrivals after {org.dutyStart} marked <span className="text-yellow-600 font-semibold">Late</span> &nbsp;&middot;&nbsp;
                      Hours beyond shift duration counted as <span className="text-brand-600 font-semibold">Overtime</span>
                    </p>
                  )}
                </Section>

                <Section title="Minimum Wage & Social Security">
                  <div className="rounded-lg bg-amber-50 border border-amber-200 px-4 py-4 space-y-3">
                    <div>
                      <p className="text-sm font-semibold text-amber-800">Punjab Minimum Wage (2025-26)</p>
                      <p className="text-xs text-amber-600 mt-0.5">Source: Punjab Minimum Wages Board. Used in compliance checks.</p>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-semibold text-amber-700">Rs.</span>
                      <input
                        type="number"
                        min="0"
                        step="1000"
                        value={org.minimumWage ?? "40000"}
                        onChange={e => setOrg({ ...org, minimumWage: e.target.value })}
                        className="w-40 rounded-lg border-0 py-2 px-3 text-lg font-bold text-amber-700 bg-amber-100 ring-1 ring-inset ring-amber-300 focus:ring-2 focus:ring-amber-500 focus:outline-none"
                      />
                      <span className="text-sm text-amber-600">/ month</span>
                    </div>
                    <p className="text-xs text-amber-500">Edit and click Save Settings to update compliance threshold.</p>
                  </div>
                  <div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div className="rounded-lg bg-white border border-gray-200 px-3 py-3 space-y-2">
                      <p className="text-xs font-semibold text-gray-600 uppercase tracking-wider">EOBI Rates (% of basic salary)</p>
                      <div className="grid grid-cols-2 gap-2">
                        <Field label="Employer %">
                          <input type="number" min={0} step="0.01" value={org.eobiEmployerRate ?? ""} onChange={e => setOrg({ ...org, eobiEmployerRate: e.target.value })} className={inputCls} />
                        </Field>
                        <Field label="Employee %">
                          <input type="number" min={0} step="0.01" value={org.eobiEmployeeRate ?? ""} onChange={e => setOrg({ ...org, eobiEmployeeRate: e.target.value })} className={inputCls} />
                        </Field>
                      </div>
                    </div>
                    <div className="rounded-lg bg-white border border-gray-200 px-3 py-3 space-y-2">
                      <p className="text-xs font-semibold text-gray-600 uppercase tracking-wider">PESSI Rates (% of basic salary)</p>
                      <div className="grid grid-cols-2 gap-2">
                        <Field label="Employer %">
                          <input type="number" min={0} step="0.01" value={org.pessiEmployerRate ?? ""} onChange={e => setOrg({ ...org, pessiEmployerRate: e.target.value })} className={inputCls} />
                        </Field>
                        <Field label="Employee %">
                          <input type="number" min={0} step="0.01" value={org.pessiEmployeeRate ?? ""} onChange={e => setOrg({ ...org, pessiEmployeeRate: e.target.value })} className={inputCls} />
                        </Field>
                      </div>
                    </div>
                  </div>
                </Section>

                <Section title="Leave Allowances (Annual)">
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    {([
                      { label: "Annual Leave Days", key: "annualLeaveDays" },
                      { label: "Sick Leave Days",   key: "sickLeaveDays" },
                      { label: "Casual Leave Days", key: "casualLeaveDays" },
                    ] as { label: string; key: keyof OrgSettings }[]).map(item => (
                      <Field key={item.label} label={item.label}>
                        <input
                          type="number" min={0}
                          value={org[item.key] as string ?? ""}
                          onChange={e => setOrg(o => ({ ...o, [item.key]: e.target.value }))}
                          className={inputCls}
                        />
                      </Field>
                    ))}
                  </div>
                  <p className="text-xs text-gray-400 mt-2">Used for leave encashment calculation in Full &amp; Final Settlement.</p>
                </Section>


                <Section title="Holidays Calendar">
                  <p className="text-xs text-gray-500">
                    Add your own holiday ranges (Eid, Chand Raat, extra company holidays). Attendance treats these dates as holidays.
                  </p>
                  <div className="grid grid-cols-1 sm:grid-cols-5 gap-3 items-end">
                    <Field label="Title">
                      <input
                        value={newHoliday.title}
                        onChange={(e) => setNewHoliday({ ...newHoliday, title: e.target.value })}
                        placeholder="Eid ul Fitr"
                        className={inputCls}
                      />
                    </Field>
                    <Field label="From">
                      <input
                        type="date"
                        value={newHoliday.from}
                        onChange={(e) => setNewHoliday({ ...newHoliday, from: e.target.value })}
                        className={inputCls}
                      />
                    </Field>
                    <Field label="To">
                      <input
                        type="date"
                        value={newHoliday.to}
                        onChange={(e) => setNewHoliday({ ...newHoliday, to: e.target.value })}
                        className={inputCls}
                      />
                    </Field>
                    <Field label="Type">
                      <select
                        value={newHoliday.paid ? "paid" : "unpaid"}
                        onChange={(e) => setNewHoliday({ ...newHoliday, paid: e.target.value === "paid" })}
                        className={inputCls}
                      >
                        <option value="paid">Paid Holiday</option>
                        <option value="unpaid">Unpaid Holiday</option>
                      </select>
                    </Field>
                    <button
                      type="button"
                      onClick={async () => {
                        if (!newHoliday.from) return;
                        const item = {
                          title: newHoliday.title.trim() || "Holiday",
                          from: newHoliday.from,
                          to: newHoliday.to || newHoliday.from,
                          paid: newHoliday.paid,
                        };
                        const updatedRules = [...(org.holidayRules ?? []), item];
                        setOrg((prev) => ({
                          ...prev,
                          holidayRules: updatedRules,
                        }));
                        await patchSettings({ holidayCalendar: JSON.stringify(updatedRules) });
                        setNewHoliday({ title: "", from: "", to: "", paid: true });
                      }}
                      className="inline-flex items-center justify-center rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-brand-700"
                    >
                      Add Holiday
                    </button>
                  </div>

                  <div className="rounded-lg border border-gray-200 bg-gray-50 p-3 max-h-56 overflow-y-auto">
                    {(org.holidayRules ?? []).length === 0 ? (
                      <p className="text-sm text-gray-500">No custom holidays added yet.</p>
                    ) : (
                      <div className="space-y-2">
                        {(org.holidayRules ?? []).map((h, idx) => (
                          <div key={`${h.from}-${idx}`} className="flex items-center justify-between rounded bg-white border border-gray-200 px-3 py-2">
                            <div className="text-xs text-gray-700">
                              <span className="font-semibold">{h.title || "Holiday"}</span> - {h.from} to {h.to || h.from} ({h.paid === false ? "Unpaid" : "Paid"})
                            </div>
                            <button
                              type="button"
                              onClick={async () => {
                                const updatedRules = (org.holidayRules ?? []).filter((_, i) => i !== idx);
                                setOrg((prev) => ({
                                  ...prev,
                                  holidayRules: updatedRules,
                                }));
                                await patchSettings({ holidayCalendar: JSON.stringify(updatedRules) });
                              }}
                              className="text-red-600 text-xs font-semibold hover:text-red-700"
                            >
                              Remove
                            </button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </Section>
              </div>
            )}

            {activeTab === "email" && (
              <div className="space-y-6">
                <Section title="SMTP Configuration" description="Configure your email server settings to send automated notifications to employees.">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Field label="SMTP Host">
                      <input 
                        value={emailConfig.smtpHost} 
                        onChange={e => setEmailConfig({ ...emailConfig, smtpHost: e.target.value })} 
                        placeholder="smtp.gmail.com" 
                        className={inputCls} 
                      />
                    </Field>
                    <Field label="SMTP Port">
                      <select 
                        value={emailConfig.smtpPort} 
                        onChange={e => setEmailConfig({ ...emailConfig, smtpPort: e.target.value })} 
                        className={inputCls}
                      >
                        <option value="587">587 (TLS)</option>
                        <option value="465">465 (SSL)</option>
                        <option value="25">25 (None)</option>
                      </select>
                    </Field>
                    <Field label="SMTP Username">
                      <input 
                        value={emailConfig.smtpUser} 
                        onChange={e => setEmailConfig({ ...emailConfig, smtpUser: e.target.value })} 
                        placeholder="your-email@gmail.com" 
                        className={inputCls} 
                      />
                    </Field>
                    <Field label="SMTP Password">
                      <div className="relative">
                        <input 
                          type={showPassword ? "text" : "password"}
                          value={emailConfig.smtpPassword} 
                          onChange={e => setEmailConfig({ ...emailConfig, smtpPassword: e.target.value })} 
                          placeholder="••••••••" 
                          className={inputCls + " pr-10"}
                        />
                        <button 
                          type="button" 
                          onClick={() => setShowPassword(!showPassword)} 
                          className="absolute right-2.5 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                        >
                          {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                        </button>
                      </div>
                    </Field>
                    <Field label="From Email">
                      <input 
                        type="email"
                        value={emailConfig.fromEmail} 
                        onChange={e => setEmailConfig({ ...emailConfig, fromEmail: e.target.value })} 
                        placeholder="hr@company.com" 
                        className={inputCls} 
                      />
                    </Field>
                    <Field label="From Name">
                      <input 
                        value={emailConfig.fromName} 
                        onChange={e => setEmailConfig({ ...emailConfig, fromName: e.target.value })} 
                        placeholder="HR Department" 
                        className={inputCls} 
                      />
                    </Field>
                  </div>
                  <div className="flex items-center">
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input 
                        type="checkbox" 
                        checked={emailConfig.smtpSecure} 
                        onChange={e => setEmailConfig({ ...emailConfig, smtpSecure: e.target.checked })} 
                        className="sr-only peer" 
                      />
                      <div className="w-9 h-5 bg-gray-200 peer-checked:bg-brand-600 rounded-full peer-focus:ring-2 peer-focus:ring-brand-300 transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-full" />
                    </label>
                    <span className="ml-3 text-sm text-gray-700">Use SSL/TLS encryption</span>
                  </div>
                </Section>

                <Section title="Email Notifications" description="Choose which automated emails to send to employees.">
                  <div className="space-y-4">
                    {[
                      { key: "enableOnboardingEmail", label: "Employee Onboarding", description: "Welcome email when new employee is added" },
                      { key: "enableSalaryEmail", label: "Salary Slips", description: "Monthly salary slip emails" },
                      { key: "enableAttendanceEmail", label: "Attendance Reports", description: "Weekly/monthly attendance summaries" },
                      { key: "enableLeaveEmail", label: "Leave Status", description: "Leave request approval/rejection notifications" },
                    ].map(emailType => (
                      <div key={emailType.key} className="flex items-center justify-between py-3 border-b border-gray-100 last:border-0">
                        <div>
                          <h4 className="text-sm font-medium text-gray-900">{emailType.label}</h4>
                          <p className="text-xs text-gray-500">{emailType.description}</p>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input 
                            type="checkbox" 
                            checked={emailConfig[emailType.key as keyof typeof emailConfig] as boolean} 
                            onChange={e => setEmailConfig({ ...emailConfig, [emailType.key]: e.target.checked })} 
                            className="sr-only peer" 
                          />
                          <div className="w-9 h-5 bg-gray-200 peer-checked:bg-brand-600 rounded-full peer-focus:ring-2 peer-focus:ring-brand-300 transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-full" />
                        </label>
                      </div>
                    ))}
                  </div>
                </Section>

                <Section title="Test Configuration" description="Send a test email to verify your SMTP settings are working correctly.">
                  <div className="flex items-center gap-4">
                    <button
                      onClick={handleTestEmail}
                      disabled={testEmailLoading || !emailConfig.smtpHost || !emailConfig.smtpUser || !emailConfig.fromEmail}
                      className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {testEmailLoading ? (
                        <><Loader2 className="h-4 w-4 animate-spin" /> Sending...</>
                      ) : (
                        <><TestTube className="h-4 w-4" /> Send Test Email</>
                      )}
                    </button>
                    <span className="text-xs text-gray-500">
                      Test email will be sent to: {emailConfig.fromEmail || "configured from email"}
                    </span>
                  </div>
                </Section>
              </div>
            )}

            {activeTab === "users" && isSuperAdmin && <UsersTab />}

            {isSuperAdmin && (
              <div className="mt-8 pt-6 border-t border-gray-200">
                <Section title="Danger Zone" description="Irreversible and destructive actions. Proceed with caution.">
                  <div className="flex items-center justify-between">
                    <div>
                      <h4 className="text-sm font-semibold text-gray-900">Clean Compliance Database</h4>
                      <p className="text-xs text-gray-500 mt-0.5">Delete all attendance, payroll, and punch records from the compliance database.</p>
                    </div>
                    <button
                      onClick={handleCleanCompliance}
                      disabled={cleaningCompliance}
                      className="inline-flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {cleaningCompliance ? (
                        <><Loader2 className="h-4 w-4 animate-spin" /> Cleaning...</>
                      ) : (
                        <><Trash2 className="h-4 w-4" /> Clean Compliance</>
                      )}
                    </button>
                  </div>
                </Section>
              </div>
            )}

          </motion.div>
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Users Tab                                                          */
/* ------------------------------------------------------------------ */

function UsersTab() {
  const [users, setUsers] = useState<UserRow[]>([]);
  const [permConfig, setPermConfig] = useState<PermConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingUser, setEditingUser] = useState<UserRow | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      const [uRes, pRes] = await Promise.all([
        authFetch(`${API}/users`),
        authFetch(`${API}/users/permissions-config`),
      ]);
      if (uRes.ok) setUsers(await uRes.json());
      if (pRes.ok) setPermConfig(await pRes.json());
    } catch { /* ignore */ }
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);

  const handleDelete = async (id: string) => {
    await authFetch(`${API}/users/${id}`, { method: "DELETE" });
    setDeleteConfirm(null);
    load();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-40 text-gray-400">
        <Loader2 className="h-5 w-5 animate-spin mr-2" /> Loading users...
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-sm font-semibold text-gray-900">User Accounts</h3>
          <p className="text-xs text-gray-500 mt-0.5">Create and manage login accounts with role-based permissions.</p>
        </div>
        <button
          onClick={() => { setEditingUser(null); setShowForm(true); }}
          className="inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors"
        >
          <UserPlus className="h-4 w-4" /> Add User
        </button>
      </div>

      <div className="rounded-xl border border-gray-200 overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">User</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Role</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Status</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Permissions</th>
              <th className="px-4 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100 bg-white">
            {users.length === 0 && (
              <tr><td colSpan={5} className="px-4 py-8 text-center text-sm text-gray-400">No users created yet.</td></tr>
            )}
            {users.map((u) => (
              <tr key={u.id} className="hover:bg-gray-50/50 transition-colors">
                <td className="px-4 py-3">
                  <div className="flex items-center gap-3">
                    <div className="h-8 w-8 rounded-full bg-brand-100 flex items-center justify-center flex-shrink-0">
                      <span className="text-brand-800 font-bold text-xs">
                        {u.name ? u.name.split(" ").map(w => w[0]).join("").toUpperCase().slice(0, 2) : "??"}
                      </span>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-900">{u.name || "—"}</p>
                      <p className="text-xs text-gray-500">{u.email}</p>
                    </div>
                  </div>
                </td>
                <td className="px-4 py-3">
                  <span className="inline-flex items-center rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700">
                    {ROLE_OPTIONS.find(r => r.value === u.role)?.label ?? u.role}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className={cn(
                    "inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium",
                    u.isActive ? "bg-green-50 text-green-700" : "bg-red-50 text-red-600",
                  )}>
                    <span className={cn("h-1.5 w-1.5 rounded-full", u.isActive ? "bg-green-500" : "bg-red-400")} />
                    {u.isActive ? "Active" : "Disabled"}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-xs text-gray-500">{u.effectivePermissions.length} permissions</span>
                </td>
                <td className="px-4 py-3 text-right">
                  <div className="flex items-center justify-end gap-1">
                    <button
                      onClick={() => { setEditingUser(u); setShowForm(true); }}
                      className="p-1.5 rounded-md text-gray-400 hover:text-brand-600 hover:bg-brand-50 transition-colors"
                      title="Edit"
                    >
                      <Pencil className="h-4 w-4" />
                    </button>
                    {deleteConfirm === u.id ? (
                      <div className="flex items-center gap-1">
                        <button onClick={() => handleDelete(u.id)} className="px-2 py-1 rounded text-xs font-medium bg-red-600 text-white hover:bg-red-700">Delete</button>
                        <button onClick={() => setDeleteConfirm(null)} className="px-2 py-1 rounded text-xs font-medium text-gray-600 hover:bg-gray-100">Cancel</button>
                      </div>
                    ) : (
                      <button
                        onClick={() => setDeleteConfirm(u.id)}
                        className="p-1.5 rounded-md text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                        title="Delete"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <AnimatePresence>
        {showForm && permConfig && (
          <UserFormModal
            permConfig={permConfig}
            user={editingUser}
            onClose={() => { setShowForm(false); setEditingUser(null); }}
            onSaved={() => { setShowForm(false); setEditingUser(null); load(); }}
          />
        )}
      </AnimatePresence>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  User Create/Edit Modal                                             */
/* ------------------------------------------------------------------ */

function UserFormModal({ permConfig, user, onClose, onSaved }: {
  permConfig: PermConfig;
  user: UserRow | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const isEdit = !!user;

  const [name, setName] = useState(user?.name ?? "");
  const [email, setEmail] = useState(user?.email ?? "");
  const [password, setPassword] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [role, setRole] = useState(user?.role ?? "HR_MANAGER");
  const [isActive, setIsActive] = useState(user?.isActive ?? true);
  const [overrides, setOverrides] = useState<Record<string, boolean>>(() => {
    if (user?.permissions) {
      try { return JSON.parse(user.permissions); } catch { return {}; }
    }
    return {};
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const rolePerms = new Set(permConfig.rolePermissions[role] ?? []);

  const getEffective = (perm: string) => {
    if (perm in overrides) return overrides[perm];
    return rolePerms.has(perm);
  };

  const togglePerm = (perm: string) => {
    const currentlyOn = getEffective(perm);
    const roleDefault = rolePerms.has(perm);

    if (currentlyOn === roleDefault) {
      setOverrides((prev) => ({ ...prev, [perm]: !roleDefault }));
    } else {
      setOverrides((prev) => {
        const copy = { ...prev };
        delete copy[perm];
        return copy;
      });
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");

    const permJson = Object.keys(overrides).length > 0 ? JSON.stringify(overrides) : null;

    try {
      const body: any = { name, email, role, isActive, permissions: permJson };
      if (password) body.password = password;

      const url = isEdit ? `${API}/users/${user!.id}` : `${API}/users`;
      const method = isEdit ? "PATCH" : "POST";

      if (!isEdit && !password) {
        setError("Password is required for new users.");
        setSaving(false);
        return;
      }

      const res = await authFetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || "Failed to save");
      }
      onSaved();
    } catch (err: any) {
      setError(err.message || "Failed to save user");
    } finally {
      setSaving(false);
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-start justify-center bg-black/40 backdrop-blur-sm pt-16 px-4 overflow-y-auto pb-8"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <motion.div
        initial={{ opacity: 0, y: 20, scale: 0.97 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        exit={{ opacity: 0, y: 20, scale: 0.97 }}
        className="bg-white rounded-2xl shadow-xl border border-gray-200 w-full max-w-2xl"
      >
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900">{isEdit ? "Edit User" : "Add New User"}</h3>
          <button onClick={onClose} className="p-1 rounded-md text-gray-400 hover:text-gray-600 hover:bg-gray-100">
            <X className="h-5 w-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-5">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Full Name">
              <input value={name} onChange={e => setName(e.target.value)} required placeholder="John Doe" className={inputCls} />
            </Field>
            <Field label="Email Address">
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} required placeholder="user@company.com" className={inputCls} />
            </Field>
            <Field label={isEdit ? "New Password (leave blank to keep)" : "Password"}>
              <div className="relative">
                <input
                  type={showPw ? "text" : "password"}
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                  required={!isEdit}
                  placeholder={isEdit ? "••••••••" : "min 6 characters"}
                  minLength={isEdit && !password ? undefined : 6}
                  className={inputCls + " pr-10"}
                />
                <button type="button" onClick={() => setShowPw(!showPw)} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                  {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </Field>
            <Field label="Role">
              <select value={role} onChange={e => { setRole(e.target.value); setOverrides({}); }} className={inputCls}>
                {ROLE_OPTIONS.map(r => (
                  <option key={r.value} value={r.value}>{r.label}</option>
                ))}
              </select>
            </Field>
          </div>

          <div className="flex items-center gap-3">
            <label className="relative inline-flex items-center cursor-pointer">
              <input type="checkbox" checked={isActive} onChange={e => setIsActive(e.target.checked)} className="sr-only peer" />
              <div className="w-9 h-5 bg-gray-200 peer-checked:bg-brand-600 rounded-full peer-focus:ring-2 peer-focus:ring-brand-300 transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-full" />
            </label>
            <span className="text-sm text-gray-700">{isActive ? "Active" : "Disabled"}</span>
          </div>

          {/* Permissions panel */}
          <div className="rounded-xl border border-gray-200 p-4 space-y-3">
            <div className="flex items-center justify-between">
              <h4 className="text-sm font-semibold text-gray-900">Permission Overrides</h4>
              <span className="text-xs text-gray-400">
                {Object.keys(overrides).length > 0
                  ? `${Object.keys(overrides).length} override(s)`
                  : "Using role defaults"}
              </span>
            </div>
            <p className="text-xs text-gray-500">
              Checked permissions come from the <strong>{ROLE_OPTIONS.find(r => r.value === role)?.label}</strong> role template.
              Click a checkbox to override.
            </p>

            <div className="max-h-72 overflow-y-auto space-y-4 pr-1">
              {Object.entries(permConfig.permissionGroups).map(([group, perms]) => (
                <div key={group}>
                  <p className="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-1.5">{group}</p>
                  <div className="grid grid-cols-2 gap-x-4 gap-y-1">
                    {perms.map((perm) => {
                      const on = getEffective(perm);
                      const isOverridden = perm in overrides;
                      return (
                        <label
                          key={perm}
                          className={cn(
                            "flex items-center gap-2 rounded px-2 py-1 text-sm cursor-pointer transition-colors",
                            isOverridden ? "bg-amber-50 ring-1 ring-amber-200" : "hover:bg-gray-50",
                          )}
                        >
                          <input
                            type="checkbox"
                            checked={on}
                            onChange={() => togglePerm(perm)}
                            className="h-3.5 w-3.5 rounded border-gray-300 text-brand-600 focus:ring-brand-500"
                          />
                          <span className={cn("text-xs", on ? "text-gray-900" : "text-gray-400")}>
                            {perm.replace("_", " ")}
                          </span>
                          {isOverridden && (
                            <span className="ml-auto text-[10px] text-amber-600 font-medium">override</span>
                          )}
                        </label>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>

            {Object.keys(overrides).length > 0 && (
              <button
                type="button"
                onClick={() => setOverrides({})}
                className="text-xs text-brand-600 hover:text-brand-800 font-medium"
              >
                Reset all overrides
              </button>
            )}
          </div>

          {error && <p className="text-sm text-red-600">{error}</p>}

          <div className="flex items-center justify-end gap-3 pt-2">
            <button type="button" onClick={onClose} className="px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg transition-colors">
              Cancel
            </button>
            <button
              type="submit"
              disabled={saving}
              className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2 text-sm font-semibold text-white hover:bg-brand-700 disabled:opacity-60 transition-colors"
            >
              {saving && <Loader2 className="h-4 w-4 animate-spin" />}
              {isEdit ? "Save Changes" : "Create User"}
            </button>
          </div>
        </form>
      </motion.div>
    </motion.div>
  );
}

/* ------------------------------------------------------------------ */
/*  Shared sub-components                                              */
/* ------------------------------------------------------------------ */

const inputCls = "block w-full rounded-lg border-0 py-2.5 px-3 text-sm text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 transition-colors shadow-sm";

function Section({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
  return (
    <div className="rounded-2xl bg-white border border-gray-200 shadow-sm p-6 space-y-4">
      <div className="border-b border-gray-100 pb-3">
        <h3 className="text-sm font-semibold text-gray-900">{title}</h3>
        {description && <p className="text-xs text-gray-500 mt-0.5">{description}</p>}
      </div>
      {children}
    </div>
  );
}

function Field({ label, icon, children }: { label: string; icon?: React.ReactNode; children: React.ReactNode }) {
  return (
    <div>
      <label className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">
        {icon}{label}
      </label>
      {children}
    </div>
  );
}
