import { useState, useEffect, useContext, useMemo, useRef } from 'react'
import { Plus, Search, Copy, Check, ExternalLink, Upload, Globe, Trash2, Edit2, FileText, Image as ImageIcon, Film, Sparkles, MessageSquare, LayoutGrid, List, ChevronUp, ChevronDown, X, Users, Save } from 'lucide-react'
import { AppContext } from '../App'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../i18n/LanguageContext'
import { api } from '../utils/api'
import Modal from '../components/Modal'
import BulkSelectBar from '../components/BulkSelectBar'
import SlidePanel from '../components/SlidePanel'
import { useToast } from '../components/ToastContainer'
import ArtefactVersionTimeline from '../components/ArtefactVersionTimeline'
import { SkeletonCard, SkeletonTable } from '../components/SkeletonLoader'
import ArtefactDetailPanel from '../components/ArtefactDetailPanel'
import ApproverMultiSelect from '../components/ApproverMultiSelect'

const STATUS_COLORS = {
  draft: 'bg-surface-tertiary text-text-secondary',
  pending_review: 'bg-amber-100 text-amber-700',
  approved: 'bg-emerald-100 text-emerald-700',
  rejected: 'bg-red-100 text-red-700',
  revision_requested: 'bg-orange-100 text-orange-700',
}

const TYPES = ['copy', 'design', 'video', 'other']

const AVAILABLE_LANGUAGES = [
  { code: 'AR', label: 'العربية' },
  { code: 'EN', label: 'English' },
  { code: 'FR', label: 'Français' },
  { code: 'ID', label: 'Bahasa Indonesia' },
]

const TYPE_ICONS = {
  copy: FileText,
  design: ImageIcon,
  video: Film,
  other: Sparkles,
}

const SORT_OPTIONS = [
  { value: 'updated_at', dir: 'desc', labelKey: 'artefacts.sortRecentlyUpdated' },
  { value: 'created_at', dir: 'desc', labelKey: 'artefacts.sortNewest' },
  { value: 'created_at', dir: 'asc', labelKey: 'artefacts.sortOldest' },
  { value: 'title', dir: 'asc', labelKey: 'artefacts.sortTitleAZ' },
]

export default function Artefacts() {
  const { t } = useLanguage()
  const { brands, teamMembers } = useContext(AppContext)
  const { user, canDeleteResource } = useAuth()
  const toast = useToast()

  const [artefacts, setArtefacts] = useState([])
  const [loading, setLoading] = useState(true)
  const [filters, setFilters] = useState({ brand: '', status: '', type: '', creator: '', project: '', campaign: '' })
  const [searchTerm, setSearchTerm] = useState('')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [selectedArtefact, setSelectedArtefact] = useState(null)
  const [newArtefact, setNewArtefact] = useState({ title: '', description: '', type: 'copy', brand_id: '', content: '', project_id: '', campaign_id: '', approver_ids: [] })
  const [saving, setSaving] = useState(false)

  // Bulk select
  const [selectedIds, setSelectedIds] = useState(new Set())
  const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false)

  // View + sort
  const [viewMode, setViewMode] = useState('list')
  const [sortOption, setSortOption] = useState(0) // index into SORT_OPTIONS
  const [listSortBy, setListSortBy] = useState('updated_at')
  const [listSortDir, setListSortDir] = useState('desc')

  // Projects, campaigns, assignable users for filters/dropdowns
  const [projects, setProjects] = useState([])
  const [campaigns, setCampaigns] = useState([])
  const [assignableUsers, setAssignableUsers] = useState([])

  useEffect(() => {
    loadArtefacts()
    api.get('/projects').then(res => setProjects(Array.isArray(res) ? res : [])).catch(() => {})
    api.get('/campaigns').then(res => setCampaigns(Array.isArray(res) ? res : [])).catch(() => {})
    api.get('/users/assignable').then(res => setAssignableUsers(Array.isArray(res) ? res : [])).catch(() => {})
  }, [])

  const loadArtefacts = async () => {
    try {
      const res = await api.get('/artefacts')
      setArtefacts(Array.isArray(res) ? res : [])
    } catch (err) {
      console.error('Failed to load artefacts:', err)
      toast.error(t('artefacts.loadFailed'))
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = async () => {
    if (!newArtefact.title) {
      toast.error(t('artefacts.titleRequired'))
      return
    }
    setSaving(true)
    try {
      const created = await api.post('/artefacts', {
        ...newArtefact,
        approver_ids: newArtefact.approver_ids.length > 0 ? newArtefact.approver_ids.join(',') : null,
      })
      toast.success(t('artefacts.created'))
      setShowCreateModal(false)
      setNewArtefact({ title: '', description: '', type: 'copy', brand_id: '', content: '', project_id: '', campaign_id: '', approver_ids: [] })
      loadArtefacts()
      setSelectedArtefact(created)
    } catch (err) {
      console.error('Create failed:', err)
      toast.error(t('artefacts.createFailed'))
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (artefactId) => {
    try {
      await api.delete(`/artefacts/${artefactId}`)
      toast.success(t('artefacts.deleted'))
      setSelectedArtefact(null)
      loadArtefacts()
    } catch (err) {
      console.error('Delete failed:', err)
      toast.error(t('artefacts.deleteFailed'))
    }
  }

  const handleBulkDelete = async () => {
    try {
      await api.post('/artefacts/bulk-delete', { ids: [...selectedIds] })
      toast.success(t('artefacts.deleted'))
      setSelectedIds(new Set())
      setShowBulkDeleteConfirm(false)
      loadArtefacts()
    } catch (err) {
      console.error('Bulk delete failed:', err)
      toast.error(t('artefacts.deleteFailed'))
    }
  }

  const toggleSelect = (id) => {
    setSelectedIds(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const toggleSelectAll = () => {
    if (selectedIds.size === sortedArtefacts.length) setSelectedIds(new Set())
    else setSelectedIds(new Set(sortedArtefacts.map(a => a.Id)))
  }

  // Filter
  const filteredArtefacts = useMemo(() => {
    return artefacts.filter(a => {
      if (filters.brand && String(a.brand_id) !== filters.brand) return false
      if (filters.status && a.status !== filters.status) return false
      if (filters.type && a.type !== filters.type) return false
      if (filters.creator && String(a.created_by_user_id) !== filters.creator) return false
      if (filters.project && String(a.project_id) !== filters.project) return false
      if (filters.campaign && String(a.campaign_id) !== filters.campaign) return false
      if (searchTerm && !a.title?.toLowerCase().includes(searchTerm.toLowerCase())) return false
      return true
    })
  }, [artefacts, filters, searchTerm])

  // Sort (for grid: use dropdown; for list: use column headers)
  const sortedArtefacts = useMemo(() => {
    const sBy = viewMode === 'grid' ? SORT_OPTIONS[sortOption].value : listSortBy
    const sDir = viewMode === 'grid' ? SORT_OPTIONS[sortOption].dir : listSortDir
    return [...filteredArtefacts].sort((a, b) => {
      let cmp = 0
      if (sBy === 'updated_at') {
        cmp = (a.UpdatedAt || a.updated_at || '').localeCompare(b.UpdatedAt || b.updated_at || '')
      } else if (sBy === 'created_at') {
        cmp = (a.CreatedAt || a.created_at || '').localeCompare(b.CreatedAt || b.created_at || '')
      } else if (sBy === 'title') {
        cmp = (a.title || '').localeCompare(b.title || '')
      } else if (sBy === 'status') {
        cmp = (a.status || '').localeCompare(b.status || '')
      } else if (sBy === 'type') {
        cmp = (a.type || '').localeCompare(b.type || '')
      }
      return sDir === 'asc' ? cmp : -cmp
    })
  }, [filteredArtefacts, viewMode, sortOption, listSortBy, listSortDir])

  const toggleListSort = (col) => {
    if (listSortBy === col) setListSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setListSortBy(col); setListSortDir('asc') }
  }

  const SortIcon = ({ col }) => {
    if (listSortBy !== col) return null
    return listSortDir === 'asc'
      ? <ChevronUp className="w-3 h-3 inline ml-0.5" />
      : <ChevronDown className="w-3 h-3 inline ml-0.5" />
  }

  const formatDate = (dateStr) => {
    if (!dateStr) return '—'
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
  }

  return (
    <div className="space-y-4 animate-fade-in">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">{t('artefacts.title')}</h1>
          <p className="text-sm text-text-secondary mt-1">{t('artefacts.subtitle')}</p>
        </div>
        <div className="flex items-center gap-3">
          {/* View switcher */}
          <div className="flex items-center bg-surface-tertiary rounded-lg p-0.5">
            {[
              { mode: 'grid', icon: LayoutGrid, label: t('artefacts.grid') },
              { mode: 'list', icon: List, label: t('artefacts.list') },
            ].map(({ mode, icon: Icon, label }) => (
              <button
                key={mode}
                onClick={() => setViewMode(mode)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
                  viewMode === mode
                    ? 'bg-white text-text-primary shadow-sm'
                    : 'text-text-tertiary hover:text-text-secondary'
                }`}
              >
                <Icon className="w-3.5 h-3.5" />
                {label}
              </button>
            ))}
          </div>

          <button
            onClick={() => setShowCreateModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light transition-colors shadow-sm"
          >
            <Plus className="w-4 h-4" />
            <span className="font-medium">{t('artefacts.newArtefact')}</span>
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3">
        <div className="relative flex-1 min-w-[200px] max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
          <input
            type="text"
            placeholder={t('artefacts.searchArtefacts')}
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary bg-surface transition-colors"
          />
        </div>

        <select
          value={filters.brand}
          onChange={e => setFilters(f => ({ ...f, brand: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('artefacts.allBrands')}</option>
          {brands.map(b => <option key={b._id} value={b._id}>{b.name}</option>)}
        </select>

        <select
          value={filters.status}
          onChange={e => setFilters(f => ({ ...f, status: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('artefacts.allStatuses')}</option>
          <option value="draft">{t('artefacts.status.draft')}</option>
          <option value="pending_review">{t('artefacts.status.pendingReview')}</option>
          <option value="approved">{t('artefacts.status.approved')}</option>
          <option value="rejected">{t('artefacts.status.rejected')}</option>
          <option value="revision_requested">{t('artefacts.status.revisionRequested')}</option>
        </select>

        <select
          value={filters.type}
          onChange={e => setFilters(f => ({ ...f, type: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('artefacts.allTypes')}</option>
          {TYPES.map(t => <option key={t} value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>)}
        </select>

        <select
          value={filters.creator}
          onChange={e => setFilters(f => ({ ...f, creator: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('artefacts.allCreators')}</option>
          {(teamMembers || []).map(m => <option key={m._id || m.id} value={m._id || m.id}>{m.name}</option>)}
        </select>

        <select
          value={filters.project}
          onChange={e => setFilters(f => ({ ...f, project: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('artefacts.allProjects')}</option>
          {projects.map(p => <option key={p.Id || p._id || p.id} value={p.Id || p._id || p.id}>{p.name || p.title}</option>)}
        </select>

        <select
          value={filters.campaign}
          onChange={e => setFilters(f => ({ ...f, campaign: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
        >
          <option value="">{t('artefacts.allCampaigns')}</option>
          {campaigns.map(c => <option key={c.Id || c._id || c.id} value={c.Id || c._id || c.id}>{c.name || c.title}</option>)}
        </select>

        {/* Sort dropdown (grid mode) */}
        {viewMode === 'grid' && (
          <select
            value={sortOption}
            onChange={e => setSortOption(Number(e.target.value))}
            className="text-sm border border-border rounded-lg px-3 py-2 bg-surface text-text-secondary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors"
          >
            {SORT_OPTIONS.map((opt, i) => (
              <option key={i} value={i}>{t(opt.labelKey)}</option>
            ))}
          </select>
        )}
      </div>

      {/* Grid View */}
      {viewMode === 'grid' && (
        loading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {[...Array(6)].map((_, i) => <SkeletonCard key={i} />)}
          </div>
        ) : sortedArtefacts.length === 0 ? (
          <div className="text-center py-12 bg-surface rounded-xl border-2 border-dashed border-border">
            <p className="text-text-secondary">{t('artefacts.noArtefacts')}</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 stagger-children">
            {sortedArtefacts.map(artefact => {
              const TypeIcon = TYPE_ICONS[artefact.type] || Sparkles
              return (
                <button
                  key={artefact.Id}
                  onClick={() => setSelectedArtefact(artefact)}
                  className="bg-surface border border-border rounded-xl p-4 hover:border-brand-primary/30 hover:shadow-sm transition-colors text-left"
                >
                  <div className="flex items-start gap-3 mb-2">
                    <div className="w-10 h-10 rounded-lg bg-brand-primary/10 flex items-center justify-center shrink-0">
                      <TypeIcon className="w-5 h-5 text-brand-primary" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <h3 className="font-semibold text-text-primary line-clamp-1">{artefact.title}</h3>
                      <div className="flex items-center gap-2 mt-1">
                        <span className={`text-xs px-2 py-0.5 rounded-full ${STATUS_COLORS[artefact.status] || 'bg-surface-tertiary text-text-secondary'}`}>
                          {artefact.status?.replace('_', ' ')}
                        </span>
                        {artefact.current_version && (
                          <span className="text-xs text-text-tertiary">v{artefact.current_version}</span>
                        )}
                      </div>
                    </div>
                  </div>
                  {artefact.description && (
                    <p className="text-sm text-text-secondary line-clamp-2 mb-3">{artefact.description}</p>
                  )}
                  <div className="flex items-center gap-2 text-xs text-text-tertiary flex-wrap">
                    <span className="capitalize">{artefact.type}</span>
                    {artefact.brand_name && <span>• {artefact.brand_name}</span>}
                    {artefact.creator_name && <span>• by {artefact.creator_name}</span>}
                    {artefact.project_name && (
                      <span className="px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 font-medium">{artefact.project_name}</span>
                    )}
                    {artefact.campaign_name && (
                      <span className="px-1.5 py-0.5 rounded bg-purple-50 text-purple-600 font-medium">{artefact.campaign_name}</span>
                    )}
                    {artefact.approvers?.length > 0 && (
                      <span className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 font-medium">
                        <Users className="w-3 h-3" />
                        {artefact.approvers.map(a => a.name).filter(Boolean).join(', ')}
                      </span>
                    )}
                  </div>
                </button>
              )
            })}
          </div>
        )
      )}

      {/* List View */}
      {viewMode === 'list' && (
        loading ? (
          <SkeletonTable rows={8} cols={7} />
        ) : sortedArtefacts.length === 0 ? (
          <div className="text-center py-12 bg-surface rounded-xl border-2 border-dashed border-border">
            <p className="text-text-secondary">{t('artefacts.noArtefacts')}</p>
          </div>
        ) : (
          <div className="bg-surface rounded-lg border border-border overflow-hidden">
            {selectedIds.size > 0 && (
              <div className="px-4 pt-3">
                <BulkSelectBar selectedCount={selectedIds.size} onDelete={() => setShowBulkDeleteConfirm(true)} onClear={() => setSelectedIds(new Set())} />
              </div>
            )}
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-surface-secondary border-b border-border">
                  <tr>
                    <th className="w-10 px-3 py-3" onClick={e => e.stopPropagation()}>
                      <input type="checkbox" checked={selectedIds.size === sortedArtefacts.length && sortedArtefacts.length > 0} onChange={toggleSelectAll} className="rounded border-border" />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer hover:text-text-primary" onClick={() => toggleListSort('title')}>
                      {t('artefacts.titleLabel')} <SortIcon col="title" />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer hover:text-text-primary" onClick={() => toggleListSort('type')}>
                      {t('artefacts.type')} <SortIcon col="type" />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer hover:text-text-primary" onClick={() => toggleListSort('status')}>
                      {t('artefacts.status')} <SortIcon col="status" />
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('artefacts.brand')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('artefacts.project')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('artefacts.campaign')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('artefacts.creator')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('artefacts.approvers')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase">{t('artefacts.version')}</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary uppercase cursor-pointer hover:text-text-primary" onClick={() => toggleListSort('updated_at')}>
                      {t('artefacts.updated')} <SortIcon col="updated_at" />
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {sortedArtefacts.map(artefact => {
                    const TypeIcon = TYPE_ICONS[artefact.type] || Sparkles
                    return (
                      <tr
                        key={artefact.Id}
                        onClick={() => setSelectedArtefact(artefact)}
                        className="hover:bg-surface-secondary cursor-pointer transition-colors"
                      >
                        <td className="w-10 px-3 py-3" onClick={e => e.stopPropagation()}>
                          <input type="checkbox" checked={selectedIds.has(artefact.Id)} onChange={() => toggleSelect(artefact.Id)} className="rounded border-border" />
                        </td>
                        <td className="px-4 py-3 text-sm font-medium text-text-primary">{artefact.title}</td>
                        <td className="px-4 py-3 text-sm text-text-secondary">
                          <span className="flex items-center gap-1.5">
                            <TypeIcon className="w-3.5 h-3.5" />
                            <span className="capitalize">{artefact.type}</span>
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm">
                          <span className={`text-xs px-2 py-0.5 rounded-full ${STATUS_COLORS[artefact.status] || 'bg-surface-tertiary text-text-secondary'}`}>
                            {artefact.status?.replace('_', ' ')}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm text-text-secondary">{artefact.brand_name || '—'}</td>
                        <td className="px-4 py-3 text-sm text-text-secondary">{artefact.project_name || '—'}</td>
                        <td className="px-4 py-3 text-sm text-text-secondary">{artefact.campaign_name || '—'}</td>
                        <td className="px-4 py-3 text-sm text-text-secondary">{artefact.creator_name || '—'}</td>
                        <td className="px-4 py-3 text-sm text-text-secondary">
                          {artefact.approvers?.length > 0
                            ? artefact.approvers.map(a => a.name).filter(Boolean).join(', ')
                            : '—'}
                        </td>
                        <td className="px-4 py-3 text-sm text-text-tertiary">{artefact.current_version ? `v${artefact.current_version}` : '—'}</td>
                        <td className="px-4 py-3 text-sm text-text-tertiary">{formatDate(artefact.UpdatedAt || artefact.updated_at)}</td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )
      )}

      {/* Create Modal */}
      <Modal isOpen={showCreateModal} onClose={() => setShowCreateModal(false)} title={t('artefacts.createArtefact')} size="md">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.titleLabel')} *</label>
            <input
              type="text"
              value={newArtefact.title}
              onChange={e => setNewArtefact(f => ({ ...f, title: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              placeholder={t('artefacts.titlePlaceholder')}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.type')}</label>
            <select
              value={newArtefact.type}
              onChange={e => setNewArtefact(f => ({ ...f, type: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
            >
              {TYPES.map(t => <option key={t} value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.brand')}</label>
            <select
              value={newArtefact.brand_id}
              onChange={e => setNewArtefact(f => ({ ...f, brand_id: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
            >
              <option value="">—</option>
              {brands.map(b => <option key={b._id} value={b._id}>{b.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.project')}</label>
            <select
              value={newArtefact.project_id}
              onChange={e => setNewArtefact(f => ({ ...f, project_id: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
            >
              <option value="">—</option>
              {projects.map(p => <option key={p.Id || p._id || p.id} value={p.Id || p._id || p.id}>{p.name || p.title}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.campaign')}</label>
            <select
              value={newArtefact.campaign_id}
              onChange={e => setNewArtefact(f => ({ ...f, campaign_id: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
            >
              <option value="">—</option>
              {campaigns.map(c => <option key={c.Id || c._id || c.id} value={c.Id || c._id || c.id}>{c.name || c.title}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.approvers')}</label>
            <ApproverMultiSelect
              users={assignableUsers}
              selected={newArtefact.approver_ids}
              onChange={ids => setNewArtefact(f => ({ ...f, approver_ids: ids }))}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.description')}</label>
            <textarea
              value={newArtefact.description}
              onChange={e => setNewArtefact(f => ({ ...f, description: e.target.value }))}
              rows={3}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              placeholder={t('artefacts.descriptionPlaceholder')}
            />
          </div>
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-border">
            <button
              onClick={() => setShowCreateModal(false)}
              className="px-4 py-2 text-sm font-medium text-text-secondary hover:bg-surface-tertiary rounded-lg"
            >
              {t('common.cancel')}
            </button>
            <button
              onClick={handleCreate}
              disabled={saving || !newArtefact.title}
              className="px-5 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
            >
              {saving ? t('artefacts.creating') : t('common.create')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Bulk Delete Confirmation */}
      <Modal
        isOpen={showBulkDeleteConfirm}
        onClose={() => setShowBulkDeleteConfirm(false)}
        title={t('common.bulkDeleteConfirm').replace('{count}', selectedIds.size)}
        isConfirm
        danger
        confirmText={t('common.deleteSelected')}
        onConfirm={handleBulkDelete}
      >
        {t('common.bulkDeleteDesc')}
      </Modal>

      {/* Detail Panel */}
      {selectedArtefact && (
        <ArtefactDetailPanel
          artefact={selectedArtefact}
          onClose={() => setSelectedArtefact(null)}
          onUpdate={loadArtefacts}
          onDelete={canDeleteResource('artefact', selectedArtefact) ? handleDelete : undefined}
          projects={projects}
          campaigns={campaigns}
          assignableUsers={assignableUsers}
        />
      )}
    </div>
  )
}
