'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { Plus, Trash2, Shield, Search, Save, X, Edit2, ChevronDown } from 'lucide-react';
import { listStaff, createStaff, updateStaff, deleteStaff } from '@client/api/staff';
import {
  listRoles, createRole, updateRole, deleteRole,
  defaultPermissionsMap, permsSummary, permissionsMatchRole,
  SECTIONS, type Role, type PermissionsMap, type CrudPerms,
} from '@client/api/roles';
import { useAuth } from '@client/contexts/AuthContext';
import { toast } from 'sonner';
import { InlineTableSkeleton } from '@client/components/skeletons/PageSkeletons';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

const SECTION_LABELS: Record<string, string> = {
  dashboard: 'Dashboard',
  orders: 'Orders',
  reservations: 'Reservations',
  ai_config: 'AI Configuration',
  knowledge_base: 'Knowledge Base',
  chat_widget: 'Chat Widget',
  conversations: 'Conversations',
  telephone: 'Telephone',
  whatsapp: 'WhatsApp',
  menu: 'Menu',
  customers: 'Customers',
  loyalty: 'Loyalty Program',
  storefront: 'QR Storefront',
  marketing: 'Marketing',
  gift_cards: 'Gift Cards',
  coupons: 'Coupons',
  staff: 'Staff',
  branches: 'Branches',
  analytics: 'Analytics',
  settings: 'Settings',
};

interface StaffMember {
  id: string;
  name: string;
  email: string;
  role: string;
  roleId: string | null;
  status: 'active' | 'inactive';
  lastActive: string;
  permissions: PermissionsMap;
}

function apiRowToStaff(row: Record<string, unknown>): StaffMember {
  let permissions = row.permissions as PermissionsMap;
  if (Array.isArray(permissions)) {
    permissions = defaultPermissionsMap(false);
  }
  if (!permissions || typeof permissions !== 'object') {
    permissions = defaultPermissionsMap(false);
  }
  return {
    id: row.id as string,
    name: (row.name as string) || 'Unknown',
    email: (row.email as string) || '',
    role: (row.role as string) || 'staff',
    roleId: (row.role_id as string) ?? null,
    status: row.is_active ? 'active' : 'inactive',
    lastActive: row.last_active_at ? new Date(row.last_active_at as string).toLocaleString() : 'Never',
    permissions,
  };
}

function PermissionToggle({ value, onChange, disabled }: { value: boolean; onChange: (v: boolean) => void; disabled?: boolean }) {
  return (
    <button
      type="button"
      onClick={() => !disabled && onChange(!value)}
      className={`w-5 h-5 rounded flex items-center justify-center transition-all border ${
        disabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'
      }`}
      style={value
        ? { backgroundColor: 'hsl(var(--primary) / 0.12)', borderColor: 'hsl(var(--primary))', color: 'hsl(var(--primary))' }
        : { backgroundColor: 'transparent', borderColor: 'hsl(var(--border))', color: 'transparent' }
      }
      title={value ? 'Click to disable' : 'Click to enable'}
    >
      {value && (
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
          <path d="M1.5 5L4 7.5L8.5 2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      )}
    </button>
  );
}

const CRUD_META: { key: keyof CrudPerms; label: string; abbr: string }[] = [
  { key: 'create', label: 'Create', abbr: 'C' },
  { key: 'read',   label: 'Read',   abbr: 'R' },
  { key: 'update', label: 'Update', abbr: 'U' },
  { key: 'delete', label: 'Delete', abbr: 'D' },
];

function PermissionMatrix({
  permissions,
  onChange,
  disabled,
}: {
  permissions: PermissionsMap;
  onChange: (p: PermissionsMap) => void;
  disabled?: boolean;
}) {
  const { t } = useLanguage();
  const SECTION_LABELS: Record<string, string> = {
    dashboard:     t('staff.sections.dashboard',     'Dashboard'),
    orders:        t('staff.sections.orders',        'Orders'),
    reservations:  t('staff.sections.reservations',  'Reservations'),
    ai_config:     t('staff.sections.ai_config',     'AI Configuration'),
    knowledge_base:t('staff.sections.knowledge_base','Knowledge Base'),
    chat_widget:   t('staff.sections.chat_widget',   'Chat Widget'),
    conversations: t('staff.sections.conversations', 'Conversations'),
    telephone:     t('staff.sections.telephone',     'Telephone'),
    whatsapp:      t('staff.sections.whatsapp',      'WhatsApp'),
    menu:          t('staff.sections.menu',          'Menu'),
    customers:     t('staff.sections.customers',     'Customers'),
    loyalty:       t('staff.sections.loyalty',       'Loyalty Program'),
    storefront:    t('staff.sections.storefront',    'QR Storefront'),
    marketing:     t('staff.sections.marketing',     'Marketing'),
    gift_cards:    t('staff.sections.gift_cards',    'Gift Cards'),
    coupons:       t('staff.sections.coupons',       'Coupons'),
    staff:         t('staff.sections.staff',         'Staff'),
    branches:      t('staff.sections.branches',      'Branches'),
    analytics:     t('staff.sections.analytics',     'Analytics'),
    settings:      t('staff.sections.settings',      'Settings'),
  };

  const SECTION_GROUPS: { label: string; sections: string[] }[] = [
    { label: t('staff.groups.overview',    'Overview'),    sections: ['dashboard'] },
    { label: t('staff.groups.operations',  'Operations'),  sections: ['orders', 'reservations'] },
    { label: t('staff.groups.aiAgent',     'AI Agent'),    sections: ['ai_config', 'knowledge_base', 'chat_widget', 'conversations'] },
    { label: t('staff.groups.channels',    'Channels'),    sections: ['telephone', 'whatsapp'] },
    { label: t('staff.groups.restaurant',  'Restaurant'),  sections: ['menu', 'customers', 'loyalty', 'storefront'] },
    { label: t('staff.groups.growth',      'Growth'),      sections: ['marketing', 'gift_cards', 'coupons'] },
    { label: t('staff.groups.manage',      'Manage'),      sections: ['staff', 'branches', 'analytics', 'settings'] },
  ];

  const CRUD_META: { key: keyof CrudPerms; label: string; abbr: string }[] = [
    { key: 'create', label: t('staff.crud.create', 'Create'), abbr: t('staff.crud.createAbbr', 'C') },
    { key: 'read',   label: t('staff.crud.read', 'Read'),   abbr: t('staff.crud.readAbbr', 'R') },
    { key: 'update', label: t('staff.crud.update', 'Update'), abbr: t('staff.crud.updateAbbr', 'U') },
    { key: 'delete', label: t('staff.crud.delete', 'Delete'), abbr: t('staff.crud.deleteAbbr', 'D') },
  ];

  return (
    <div className="rounded-lg border overflow-hidden" style={{ borderColor: 'hsl(var(--border))' }}>
      <table className="w-full text-sm">
        <thead>
          <tr style={{ backgroundColor: 'hsl(var(--muted) / 0.5)' }}>
            <th className="text-left px-4 py-2.5 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))', width: '40%' }}>
              {t('staff.matrix.section', 'Section')}
            </th>
            {CRUD_META.map(({ key, label, abbr }) => (
              <th key={key} className="text-center px-3 py-2.5 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }} title={label}>
                <span className="hidden sm:inline">{label}</span>
                <span className="sm:hidden">{abbr}</span>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {SECTION_GROUPS.map((group) => (
            <React.Fragment key={group.label}>
              <tr style={{ backgroundColor: 'hsl(var(--muted) / 0.35)' }}>
                <td
                  colSpan={5}
                  className="px-4 py-1.5 text-xs font-semibold uppercase tracking-wider"
                  style={{ color: 'hsl(var(--muted-foreground))', borderTop: '1px solid hsl(var(--border))' }}
                >
                  {group.label}
                </td>
              </tr>
              {group.sections.map((section) => (
                <tr
                  key={section}
                  style={{ borderTop: '1px solid hsl(var(--border) / 0.5)' }}
                >
                  <td className="px-4 py-3 font-medium text-sm pl-6" style={{ color: 'hsl(var(--foreground))' }}>
                    {SECTION_LABELS[section]}
                  </td>
                  {CRUD_META.map(({ key: crud }) => (
                    <td key={crud} className="px-3 py-3 text-center">
                      <div className="flex justify-center">
                        <PermissionToggle
                          value={permissions[section as keyof PermissionsMap]?.[crud] ?? false}
                          disabled={disabled}
                          onChange={val => {
                            const updated = { ...permissions, [section]: { ...permissions[section as keyof PermissionsMap], [crud]: val } };
                            onChange(updated as PermissionsMap);
                          }}
                        />
                      </div>
                    </td>
                  ))}
                </tr>
              ))}
            </React.Fragment>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function RolePanel({
  role,
  onClose,
  onSaved,
}: {
  role: Role | null;
  onClose: () => void;
  onSaved: (r: Role) => void;
}) {
  const { t } = useLanguage();
  const isNew = role === null;
  const isOwner = role?.name === 'Owner' && role?.isSystem;
  const [name, setName] = useState(role?.name ?? '');
  const [description, setDescription] = useState(role?.description ?? '');
  const [permissions, setPermissions] = useState<PermissionsMap>(role?.permissions ?? defaultPermissionsMap(false));
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    if (!name.trim()) { toast.error(t('staff.errors.roleNameRequired', 'Role name is required')); return; }
    setSaving(true);
    try {
      let saved: Role;
      if (isNew) {
        saved = await createRole({ name, description, permissions });
        toast.success(t('staff.roleCreated', 'Role created'));
      } else {
        saved = await updateRole(role!.id, { name, description, permissions });
        toast.success(t('staff.roleUpdated', 'Role updated'));
      }
      onSaved(saved);
    } catch (err: unknown) {
      toast.error((err as Error).message || t('staff.errors.saveRoleFailed', 'Failed to save role'));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 sm:p-0">
      <div className="absolute inset-0" style={{ backgroundColor: 'rgba(0,0,0,0.4)' }} onClick={onClose} />
      <div className="relative w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]" style={{ backgroundColor: 'hsl(var(--surface))' }}>
        <div className="flex items-center justify-between px-6 py-4 border-b" style={{ borderColor: 'hsl(var(--border))' }}>
          <div>
            <h2 className="text-lg font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
              {isNew ? t('staff.newRole', 'New Role') : t('staff.editRole', 'Edit Role: {{name}}', { name: role!.name })}
            </h2>
            {isOwner && (
              <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('staff.ownerRoleDesc', 'Owner role is read-only — all permissions are always enabled')}</p>
            )}
          </div>
          <button className="btn-ghost p-1.5" onClick={onClose}><X size={18} /></button>
        </div>

        <div className="overflow-y-auto flex-1">
          {!isOwner && (
            <div className="px-6 pt-5 pb-5 border-b" style={{ borderColor: 'hsl(var(--border))' }}>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="text-xs font-semibold mb-1.5 block" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('staff.roleNameLabel', 'Role Name *')}</label>
                  <input
                    className="input-base w-full"
                    value={name}
                    onChange={e => setName(e.target.value)}
                    placeholder={t('staff.placeholders.roleName', 'e.g. Cashier')}
                    disabled={role?.isSystem}
                  />
                </div>
                <div>
                  <label className="text-xs font-semibold mb-1.5 block" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('staff.descriptionLabel', 'Description')}</label>
                  <input
                    className="input-base w-full"
                    value={description}
                    onChange={e => setDescription(e.target.value)}
                    placeholder={t('staff.placeholders.roleDescription', 'Short description of this role')}
                  />
                </div>
              </div>
            </div>
          )}

          <div className="px-6 pt-5 pb-6">
            <div className="flex items-baseline justify-between mb-3">
              <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('staff.permissionsTitle', 'Permissions')}</h3>
              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('staff.permissionsLegend', 'C = Create  R = Read  U = Update  D = Delete')}
              </span>
            </div>
            <PermissionMatrix permissions={permissions} onChange={setPermissions} disabled={isOwner} />
          </div>
        </div>

        {!isOwner && (
          <div className="flex gap-2 px-6 py-4 border-t" style={{ borderColor: 'hsl(var(--border))' }}>
            <button className="btn-primary" onClick={handleSave} disabled={saving}>
              <Save size={14} /> {saving ? t('staff.saving', 'Saving…') : t('staff.saveRole', 'Save Role')}
            </button>
            <button className="btn-secondary" onClick={onClose}><X size={14} /> {t('staff.cancel', 'Cancel')}</button>
          </div>
        )}
        {isOwner && (
          <div className="px-6 py-4 border-t" style={{ borderColor: 'hsl(var(--border))' }}>
            <button className="btn-secondary" onClick={onClose}>{t('staff.close', 'Close')}</button>
          </div>
        )}
      </div>
    </div>
  );
}

function StaffPanel({
  staff,
  roles,
  onClose,
  onSaved,
}: {
  staff: StaffMember | null;
  roles: Role[];
  onClose: () => void;
  onSaved: (s: StaffMember) => void;
}) {
  const { t } = useLanguage();
  const { branchId } = useAuth();
  const isNew = staff === null;
  const [name, setName] = useState(staff?.name ?? '');
  const [email, setEmail] = useState(staff?.email ?? '');
  const [roleId, setRoleId] = useState<string | null>(staff?.roleId ?? null);
  const [permissions, setPermissions] = useState<PermissionsMap>(staff?.permissions ?? defaultPermissionsMap(false));
  const [saving, setSaving] = useState(false);

  const selectedRole = roles.find(r => r.id === roleId) ?? null;

  const handleRoleChange = (newRoleId: string) => {
    setRoleId(newRoleId || null);
    const r = roles.find(r => r.id === newRoleId);
    if (r) setPermissions(r.permissions);
  };

  const isCustom = selectedRole && !permissionsMatchRole(permissions, selectedRole.permissions);

  const handleSave = async () => {
    if (!name.trim()) { toast.error(t('staff.errors.nameRequired', 'Name is required')); return; }
    setSaving(true);
    try {
      let saved: StaffMember;
      if (isNew) {
        const result = await createStaff({
          branch_id: branchId,
          name,
          email,
          role: selectedRole?.name.toLowerCase() ?? 'staff',
          role_id: roleId,
          permissions,
          is_active: true,
        });
        saved = apiRowToStaff(result.staff as unknown as Record<string, unknown>);
        toast.success(t('staff.staffAdded', 'Staff member added'));
      } else {
        const result = await updateStaff(staff!.id, {
          name,
          email,
          role: selectedRole?.name.toLowerCase() ?? staff!.role,
          role_id: roleId,
          permissions,
        });
        saved = apiRowToStaff(result.staff as unknown as Record<string, unknown>);
        toast.success(t('staff.staffUpdated', 'Staff member updated'));
      }
      onSaved(saved);
    } catch (err: unknown) {
      toast.error((err as Error).message || t('staff.errors.saveStaffFailed', 'Failed to save staff member'));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 sm:p-0">
      <div className="absolute inset-0" style={{ backgroundColor: 'rgba(0,0,0,0.4)' }} onClick={onClose} />
      <div className="relative w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]" style={{ backgroundColor: 'hsl(var(--surface))' }}>
        <div className="flex items-center justify-between px-6 py-4 border-b" style={{ borderColor: 'hsl(var(--border))' }}>
          <h2 className="text-lg font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
            {isNew ? t('staff.addStaffMember', 'Add Staff Member') : t('staff.editStaff', 'Edit: {{name}}', { name: staff!.name })}
          </h2>
          <button className="btn-ghost p-1.5" onClick={onClose}><X size={18} /></button>
        </div>

        <div className="overflow-y-auto p-6 flex-1">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-5">
            <div>
              <label className="text-xs font-semibold mb-1.5 block" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('staff.fullNameLabel', 'Full Name *')}</label>
              <input className="input-base w-full" value={name} onChange={e => setName(e.target.value)} placeholder={t('staff.placeholders.fullName', 'Full name')} />
            </div>
            <div>
              <label className="text-xs font-semibold mb-1.5 block" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('staff.emailLabel', 'Email')}</label>
              <input className="input-base w-full" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder={t('staff.placeholders.email', 'Email address')} />
            </div>
          </div>

          <div className="mb-5">
            <label className="text-xs font-semibold mb-1.5 block" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('staff.roleLabel', 'Role')}
              {isCustom && <span className="ml-2 badge badge-warning text-xs">{t('staff.customPermissions', 'Custom permissions')}</span>}
            </label>
            <div className="relative">
              <select
                className="input-base w-full appearance-none pr-8"
                value={roleId ?? ''}
                onChange={e => handleRoleChange(e.target.value)}
              >
                <option value="">{t('staff.noRoleAssigned', 'No role assigned')}</option>
                {roles.map(r => (
                  <option key={r.id} value={r.id}>{r.name}{r.isSystem ? ` (${t('staff.systemRole', 'System')})` : ''}</option>
                ))}
              </select>
              <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none" style={{ color: 'hsl(var(--muted-foreground))' }} />
            </div>
            {selectedRole && (
              <p className="text-xs mt-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {selectedRole.description || t('staff.rolePermissionsDesc', 'Permissions pre-filled from {{name}} role — you can customise below.', { name: selectedRole.name })}
              </p>
            )}
          </div>

          <div>
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('staff.permissionsTitle', 'Permissions')}</h3>
              {selectedRole && (
                <button
                  type="button"
                  className="text-xs btn-ghost px-2 py-1"
                  onClick={() => setPermissions(selectedRole.permissions)}
                >
                  {t('staff.resetToDefaults', 'Reset to {{name}} defaults', { name: selectedRole.name })}
                </button>
              )}
            </div>
            <PermissionMatrix permissions={permissions} onChange={setPermissions} />
          </div>
        </div>

        <div className="flex gap-2 px-6 py-4 border-t" style={{ borderColor: 'hsl(var(--border))' }}>
          <button className="btn-primary" onClick={handleSave} disabled={saving}>
            <Save size={14} /> {saving ? t('staff.saving', 'Saving…') : t('staff.save', 'Save')}
          </button>
          <button className="btn-secondary" onClick={onClose}><X size={14} /> {t('staff.cancel', 'Cancel')}</button>
        </div>
      </div>
    </div>
  );
}

export default function StaffPage() {
  const { t } = useLanguage();
  usePageHeader(t('staff.pageTitle', 'Staff & Team'), t('staff.pageSubtitle', 'Manage roles, permissions, and staff accounts'));
  const { restaurantId } = useAuth();

  const [activeTab, setActiveTab] = useState<'members' | 'roles'>('members');
  const [search, setSearch] = useState('');
  const [staffList, setStaffList] = useState<StaffMember[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(true);
  const [rolesLoading, setRolesLoading] = useState(true);

  const [editingStaff, setEditingStaff] = useState<StaffMember | null | undefined>(undefined);
  const [editingRole, setEditingRole] = useState<Role | null | undefined>(undefined);

  const fetchStaff = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const result = await listStaff({ limit: '100' });
      setStaffList((result.staff || []).map(s => apiRowToStaff(s as unknown as Record<string, unknown>)));
    } catch (err: unknown) {
      toast.error(t('staff.errors.loadStaff', 'Failed to load staff: ') + (err as Error).message);
    } finally {
      setLoading(false);
    }
  }, [restaurantId, t]);

  const fetchRoles = useCallback(async () => {
    if (!restaurantId) { setRolesLoading(false); return; }
    setRolesLoading(true);
    try {
      const result = await listRoles();
      setRoles(result);
    } catch (err: unknown) {
      toast.error(t('staff.errors.loadRoles', 'Failed to load roles: ') + (err as Error).message);
    } finally {
      setRolesLoading(false);
    }
  }, [restaurantId, t]);

  useEffect(() => { fetchStaff(); fetchRoles(); }, [fetchStaff, fetchRoles]);

  const handleToggleActive = async (id: string, current: boolean) => {
    try {
      await updateStaff(id, { is_active: !current });
      setStaffList(prev => prev.map(s => s.id === id ? { ...s, status: !current ? 'active' : 'inactive' } : s));
      toast.success(t('staff.statusUpdated', 'Staff status updated'));
    } catch (err: unknown) {
      toast.error(t('staff.errors.updateStaff', 'Failed to update staff: ') + (err as Error).message);
    }
  };

  const handleDeleteStaff = async (id: string) => {
    try {
      await deleteStaff(id);
      setStaffList(prev => prev.filter(s => s.id !== id));
      toast.success(t('staff.staffRemoved', 'Staff member removed'));
    } catch (err: unknown) {
      toast.error(t('staff.errors.deleteStaff', 'Failed to delete staff: ') + (err as Error).message);
    }
  };

  const handleDeleteRole = async (role: Role) => {
    if (role.isSystem) { toast.error(t('staff.errors.deleteSystemRole', 'System roles cannot be deleted')); return; }
    try {
      await deleteRole(role.id);
      setRoles(prev => prev.filter(r => r.id !== role.id));
      toast.success(t('staff.roleDeleted', 'Role deleted'));
    } catch (err: unknown) {
      toast.error((err as Error).message || t('staff.errors.deleteRoleFailed', 'Failed to delete role'));
    }
  };

  const filtered = staffList.filter(s =>
    s.name.toLowerCase().includes(search.toLowerCase()) ||
    s.role.toLowerCase().includes(search.toLowerCase()) ||
    s.email.toLowerCase().includes(search.toLowerCase())
  );

  const getRoleName = (member: StaffMember): string => {
    if (member.roleId) {
      const r = roles.find(r => r.id === member.roleId);
      if (r) {
        const isCustom = !permissionsMatchRole(member.permissions, r.permissions);
        return isCustom ? t('staff.customRoleName', '{{name}} (Custom)', { name: r.name }) : r.name;
      }
    }
    return member.role || t('staff.defaultRoleName', 'Staff');
  };

  const isCustomPerms = (member: StaffMember): boolean => {
    if (!member.roleId) return false;
    const r = roles.find(r => r.id === member.roleId);
    return r ? !permissionsMatchRole(member.permissions, r.permissions) : false;
  };

  return (
    <>
      {editingStaff !== undefined && (
        <StaffPanel
          staff={editingStaff}
          roles={roles}
          onClose={() => setEditingStaff(undefined)}
          onSaved={saved => {
            if (editingStaff === null) {
              setStaffList(prev => [...prev, saved]);
            } else {
              setStaffList(prev => prev.map(s => s.id === saved.id ? saved : s));
            }
            setEditingStaff(undefined);
          }}
        />
      )}

      {editingRole !== undefined && (
        <RolePanel
          role={editingRole}
          onClose={() => setEditingRole(undefined)}
          onSaved={saved => {
            if (editingRole === null) {
              setRoles(prev => [...prev, saved]);
            } else {
              setRoles(prev => prev.map(r => r.id === saved.id ? saved : r));
            }
            setEditingRole(undefined);
          }}
        />
      )}

      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          {[{ key: 'members', label: t('staff.tabs.members', 'Team Members') }, { key: 'roles', label: t('staff.tabs.roles', 'Roles & Permissions') }].map(t => (
            <button
              key={t.key}
              onClick={() => setActiveTab(t.key as 'members' | 'roles')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === t.key ? 'bg-white shadow-sm' : ''}`}
              style={{ color: activeTab === t.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
            >
              {t.label}
            </button>
          ))}
        </div>
        {activeTab === 'members' && (
          <button className="btn-primary" onClick={() => setEditingStaff(null)}>
            <Plus size={15} /> {t('staff.addStaff', 'Add Staff')}
          </button>
        )}
        {activeTab === 'roles' && (
          <button className="btn-primary" onClick={() => setEditingRole(null)}>
            <Plus size={15} /> {t('staff.newRole', 'New Role')}
          </button>
        )}
      </div>

      {activeTab === 'members' && (
        <div>
          <div className="relative max-w-sm mb-4">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
            <input className="input-base pl-9" placeholder={t('staff.placeholders.searchStaff', 'Search staff…')} value={search} onChange={e => setSearch(e.target.value)} />
          </div>

          {loading ? (
            <InlineTableSkeleton columns={5} rows={6} />
          ) : filtered.length === 0 ? (
            <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <p className="font-medium">{t('staff.noStaffMembers', 'No staff members yet')}</p>
              <p className="text-xs mt-1">{t('staff.addFirstMember', 'Add your first team member to get started')}</p>
            </div>
          ) : (
            <div className="card overflow-hidden">
              <table className="w-full">
                <thead>
                  <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                    {[t('staff.table.staffMember', 'Staff Member'), t('staff.table.role', 'Role'), t('staff.table.permissions', 'Permissions'), t('staff.table.status', 'Status'), t('staff.table.lastActive', 'Last Active'), ''].map(h => (
                      <th key={h} className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((s, idx) => (
                    <tr key={s.id} className="table-row-hover" style={{ borderBottom: idx < filtered.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold shrink-0" style={{ backgroundColor: 'hsl(var(--primary))' }}>
                            {s.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                          </div>
                          <div>
                            <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{s.name}</p>
                            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{s.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`badge ${isCustomPerms(s) ? 'badge-warning' : 'badge-neutral'} capitalize`}>
                          {getRoleName(s)}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                          {permsSummary(s.permissions) || '—'}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <button onClick={() => handleToggleActive(s.id, s.status === 'active')}>
                          <span className={`badge ${s.status === 'active' ? 'badge-success' : 'badge-neutral'}`}>{t(`staff.status.${s.status}`, s.status)}</span>
                        </button>
                      </td>
                      <td className="px-4 py-3 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{s.lastActive}</td>
                      <td className="px-4 py-3">
                        <div className="flex gap-1">
                          <button className="btn-ghost p-1.5" onClick={() => setEditingStaff(s)} title={t('staff.edit', 'Edit')}><Edit2 size={14} /></button>
                          <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDeleteStaff(s.id)} title={t('staff.delete', 'Delete')}><Trash2 size={14} /></button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {activeTab === 'roles' && (
        <div>
          {rolesLoading ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {[...Array(6)].map((_, i) => (
                <div key={i} className="card p-5 animate-pulse">
                  <div className="h-4 rounded mb-2" style={{ backgroundColor: 'hsl(var(--muted))', width: '40%' }} />
                  <div className="h-3 rounded mb-4" style={{ backgroundColor: 'hsl(var(--muted))', width: '70%' }} />
                  <div className="h-3 rounded" style={{ backgroundColor: 'hsl(var(--muted))', width: '90%' }} />
                </div>
              ))}
            </div>
          ) : roles.length === 0 ? (
            <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Shield size={32} className="mx-auto mb-3 opacity-30" />
              <p className="font-medium">{t('staff.noRoles', 'No roles yet')}</p>
              <p className="text-xs mt-1">{t('staff.createFirstRole', 'Create a role to define permission sets for your staff')}</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {roles.map(role => {
                const isOwner = role.name === 'Owner' && role.isSystem;
                const staffWithRole = staffList.filter(s => s.roleId === role.id).length;
                const permsText = permsSummary(role.permissions);
                return (
                  <div key={role.id} className="card p-5 flex flex-col gap-3">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <h3 className="font-semibold text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{role.name}</h3>
                          {role.isSystem && (
                            <span className="badge badge-info text-xs shrink-0">{t('staff.systemBadge', 'System')}</span>
                          )}
                          {isOwner && (
                            <span className="badge badge-success text-xs shrink-0">{t('staff.fullAccessBadge', 'Full Access')}</span>
                          )}
                        </div>
                        {role.description && (
                          <p className="text-xs mt-1 line-clamp-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{role.description}</p>
                        )}
                      </div>
                    </div>

                    <div className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {permsText || t('staff.noPermissions', 'No permissions assigned')}
                    </div>

                    <div className="flex items-center justify-between pt-1">
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {staffWithRole} {staffWithRole !== 1 ? t('staff.members', 'members') : t('staff.member', 'member')}
                      </span>
                      <div className="flex gap-1">
                        <button
                          className="btn-ghost p-1.5 text-xs"
                          onClick={() => setEditingRole(role)}
                          title={isOwner ? t('staff.viewRole', 'View role') : t('staff.editRoleTitle', 'Edit role')}
                        >
                          <Edit2 size={13} />
                        </button>
                        {!role.isSystem && (
                          <button
                            className="btn-ghost p-1.5"
                            style={{ color: 'hsl(var(--danger))' }}
                            onClick={() => handleDeleteRole(role)}
                            title={t('staff.deleteRole', 'Delete role')}
                          >
                            <Trash2 size={13} />
                          </button>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
              <button
                className="card border-dashed border-2 hover:bg-primary-light transition-all flex flex-col items-center justify-center p-8 gap-2 group"
                style={{ color: 'hsl(var(--muted-foreground))' }}
                onClick={() => setEditingRole(null)}
              >
                <div className="w-10 h-10 rounded-full border-2 border-dashed flex items-center justify-center group-hover:border-primary group-hover:text-primary">
                  <Plus size={20} />
                </div>
                <span className="text-sm font-medium group-hover:text-primary">{t('staff.addNewRole', 'Add New Role')}</span>
              </button>
            </div>
          )}
        </div>
      )}
    </>
  );
}
