import { useState, useEffect, useContext } from 'react'
import { Plus, Copy, Check, ExternalLink, Upload, Globe, Trash2, FileText, Image as ImageIcon, Film, Sparkles, MessageSquare, Save, FileEdit, Layers, ShieldCheck } from 'lucide-react'
import { AppContext } from '../App'
import { useLanguage } from '../i18n/LanguageContext'
import { api } from '../utils/api'
import Modal from './Modal'
import TabbedModal from './TabbedModal'
import { useToast } from './ToastContainer'
import ArtefactVersionTimeline from './ArtefactVersionTimeline'
import ApproverMultiSelect from './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 AVAILABLE_LANGUAGES = [
  { code: 'AR', label: '\u0627\u0644\u0639\u0631\u0628\u064A\u0629' },
  { code: 'EN', label: 'English' },
  { code: 'FR', label: 'Fran\u00E7ais' },
  { code: 'ID', label: 'Bahasa Indonesia' },
]

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

export default function ArtefactDetailPanel({ artefact, onClose, onUpdate, onDelete, projects = [], campaigns = [], assignableUsers = [] }) {
  const { t } = useLanguage()
  const { brands } = useContext(AppContext)
  const toast = useToast()
  const [versions, setVersions] = useState([])
  const [selectedVersion, setSelectedVersion] = useState(null)
  const [versionData, setVersionData] = useState(null)
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [freshReviewUrl, setFreshReviewUrl] = useState('')
  const [copied, setCopied] = useState(false)
  const [activeTab, setActiveTab] = useState('details')

  // Editable fields
  const [editTitle, setEditTitle] = useState(artefact.title || '')
  const [editDescription, setEditDescription] = useState(artefact.description || '')
  const [editProjectId, setEditProjectId] = useState(artefact.project_id || '')
  const [editCampaignId, setEditCampaignId] = useState(artefact.campaign_id || '')
  const [editApproverIds, setEditApproverIds] = useState(
    artefact.approvers?.map(a => String(a.id)) || (artefact.approver_ids ? artefact.approver_ids.split(',').map(s => s.trim()).filter(Boolean) : [])
  )
  const reviewUrl = freshReviewUrl || (artefact.approval_token ? `${window.location.origin}/review/${artefact.approval_token}` : '')
  const [savingDraft, setSavingDraft] = useState(false)
  const [deleting, setDeleting] = useState(false)
  const [confirmDeleteLangId, setConfirmDeleteLangId] = useState(null)
  const [confirmDeleteAttId, setConfirmDeleteAttId] = useState(null)
  const [showDeleteArtefactConfirm, setShowDeleteArtefactConfirm] = useState(false)

  // Language management (for copy type)
  const [showLanguageModal, setShowLanguageModal] = useState(false)
  const [languageForm, setLanguageForm] = useState({ language_code: '', language_label: '', content: '' })
  const [savingLanguage, setSavingLanguage] = useState(false)

  // New version modal
  const [showNewVersionModal, setShowNewVersionModal] = useState(false)
  const [newVersionNotes, setNewVersionNotes] = useState('')
  const [copyFromPrevious, setCopyFromPrevious] = useState(false)
  const [creatingVersion, setCreatingVersion] = useState(false)

  // File upload (for design/video)
  const [uploading, setUploading] = useState(false)

  // Video inline (Drive link input)
  const [driveUrl, setDriveUrl] = useState('')
  const [dragOver, setDragOver] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)

  // Comments
  const [comments, setComments] = useState([])
  const [newComment, setNewComment] = useState('')
  const [addingComment, setAddingComment] = useState(false)

  useEffect(() => {
    loadVersions()
  }, [artefact.Id])

  useEffect(() => {
    setEditTitle(artefact.title || '')
    setEditDescription(artefact.description || '')
    setEditProjectId(artefact.project_id || '')
    setEditCampaignId(artefact.campaign_id || '')
    setEditApproverIds(
      artefact.approvers?.map(a => String(a.id)) || (artefact.approver_ids ? artefact.approver_ids.split(',').map(s => s.trim()).filter(Boolean) : [])
    )
  }, [artefact.Id])

  const loadVersions = async () => {
    try {
      const res = await api.get(`/artefacts/${artefact.Id}/versions`)
      const versionsList = Array.isArray(res) ? res : []
      setVersions(versionsList)

      // Select latest version by default
      if (versionsList.length > 0) {
        const latest = versionsList[versionsList.length - 1]
        setSelectedVersion(latest)
        loadVersionData(latest.Id)
      }
    } catch (err) {
      console.error('Failed to load versions:', err)
      toast.error(t('artefacts.failedLoadVersions'))
    } finally {
      setLoading(false)
    }
  }

  const loadVersionData = async (versionId) => {
    try {
      const [versionRes, commentsRes] = await Promise.all([
        api.get(`/artefacts/${artefact.Id}/versions/${versionId}`),
        api.get(`/artefacts/${artefact.Id}/versions/${versionId}/comments`),
      ])

      setVersionData(versionRes.data || versionRes)
      setComments(commentsRes.data || commentsRes || [])
    } catch (err) {
      console.error('Failed to load version data:', err)
      toast.error(t('artefacts.failedLoadVersionData'))
    }
  }

  const handleSelectVersion = (version) => {
    setSelectedVersion(version)
    loadVersionData(version.Id)
  }

  const handleCreateVersion = async () => {
    setCreatingVersion(true)
    try {
      await api.post(`/artefacts/${artefact.Id}/versions`, {
        notes: newVersionNotes || `Version ${(versions[versions.length - 1]?.version_number || 0) + 1}`,
        copy_from_previous: artefact.type === 'copy' ? copyFromPrevious : false,
      })

      toast.success(t('artefacts.versionCreated'))
      setShowNewVersionModal(false)
      setNewVersionNotes('')
      setCopyFromPrevious(false)
      loadVersions()
      onUpdate()
    } catch (err) {
      console.error('Create version failed:', err)
      toast.error(t('artefacts.failedCreateVersion'))
    } finally {
      setCreatingVersion(false)
    }
  }

  const handleAddLanguage = async () => {
    if (!languageForm.language_code || !languageForm.language_label || !languageForm.content) {
      toast.error(t('artefacts.allFieldsRequired'))
      return
    }

    setSavingLanguage(true)
    try {
      await api.post(`/artefacts/${artefact.Id}/versions/${selectedVersion.Id}/texts`, languageForm)
      toast.success(t('artefacts.languageAdded'))
      setShowLanguageModal(false)
      setLanguageForm({ language_code: '', language_label: '', content: '' })
      loadVersionData(selectedVersion.Id)
    } catch (err) {
      console.error('Add language failed:', err)
      toast.error(t('artefacts.failedAddLanguage'))
    } finally {
      setSavingLanguage(false)
    }
  }

  const handleDeleteLanguage = async (textId) => {
    try {
      await api.delete(`/artefact-version-texts/${textId}`)
      toast.success(t('artefacts.languageDeleted'))
      loadVersionData(selectedVersion.Id)
    } catch (err) {
      toast.error(t('artefacts.failedDeleteLanguage'))
    }
  }

  const handleFileUpload = async (fileOrEvent) => {
    const file = fileOrEvent instanceof File ? fileOrEvent : fileOrEvent.target?.files?.[0]
    if (!file) return

    setUploading(true)
    setUploadProgress(0)
    try {
      const formData = new FormData()
      formData.append('file', file)
      await api.upload(`/artefacts/${artefact.Id}/versions/${selectedVersion.Id}/attachments`, formData, {
        onUploadProgress: (e) => {
          if (e.total) setUploadProgress(Math.round((e.loaded / e.total) * 100))
        }
      })
      toast.success(t('artefacts.fileUploaded'))
      loadVersionData(selectedVersion.Id)
    } catch (err) {
      console.error('Upload failed:', err)
      toast.error(t('artefacts.uploadFailed'))
    } finally {
      setUploading(false)
      setUploadProgress(0)
    }
  }

  const handleVideoDrop = (e) => {
    e.preventDefault()
    setDragOver(false)
    const file = e.dataTransfer.files?.[0]
    if (file && file.type.startsWith('video/')) {
      handleFileUpload(file)
    }
  }

  const handleAddDriveVideo = async () => {
    if (!driveUrl.trim()) {
      toast.error(t('artefacts.enterDriveUrl'))
      return
    }

    setUploading(true)
    try {
      await api.post(`/artefacts/${artefact.Id}/versions/${selectedVersion.Id}/attachments`, {
        drive_url: driveUrl,
      })
      toast.success(t('artefacts.videoLinkAdded'))
      setDriveUrl('')
      loadVersionData(selectedVersion.Id)
    } catch (err) {
      console.error('Add Drive link failed:', err)
      toast.error(t('artefacts.failedAddVideoLink'))
    } finally {
      setUploading(false)
    }
  }

  const handleDeleteAttachment = async (attId) => {
    try {
      await api.delete(`/artefact-attachments/${attId}`)
      toast.success(t('artefacts.attachmentDeleted'))
      loadVersionData(selectedVersion.Id)
    } catch (err) {
      toast.error(t('artefacts.failedDeleteAttachment'))
    }
  }

  const handleSubmitReview = async () => {
    setSubmitting(true)
    try {
      const res = await api.post(`/artefacts/${artefact.Id}/submit-review`)
      setFreshReviewUrl(res.reviewUrl || res.data?.reviewUrl || '')
      toast.success(t('artefacts.submittedForReview'))
      onUpdate()
    } catch (err) {
      toast.error(t('artefacts.failedSubmitReview'))
    } finally {
      setSubmitting(false)
    }
  }

  const copyReviewLink = () => {
    navigator.clipboard.writeText(reviewUrl)
    setCopied(true)
    toast.success(t('artefacts.linkCopied'))
    setTimeout(() => setCopied(false), 2000)
  }

  const handleAddComment = async () => {
    if (!newComment.trim()) return

    setAddingComment(true)
    try {
      await api.post(`/artefacts/${artefact.Id}/versions/${selectedVersion.Id}/comments`, {
        content: newComment.trim(),
      })
      toast.success(t('artefacts.commentAdded'))
      setNewComment('')
      loadVersionData(selectedVersion.Id)
    } catch (err) {
      toast.error(t('artefacts.failedAddComment'))
    } finally {
      setAddingComment(false)
    }
  }

  const handleUpdateField = async (field, value) => {
    try {
      await api.patch(`/artefacts/${artefact.Id}`, { [field]: value || null })
      toast.success(t('artefacts.updated'))
      onUpdate()
    } catch (err) {
      toast.error(t('artefacts.failedUpdate'))
    }
  }

  const handleSaveDraft = async () => {
    if (!editTitle.trim()) {
      toast.error(t('artefacts.titleRequired'))
      return
    }
    setSavingDraft(true)
    try {
      await api.patch(`/artefacts/${artefact.Id}`, {
        title: editTitle.trim(),
        description: editDescription.trim() || null,
      })
      toast.success(t('artefacts.draftSaved'))
      onUpdate()
    } catch (err) {
      toast.error(t('artefacts.failedSaveDraft'))
    } finally {
      setSavingDraft(false)
    }
  }

  const handleDeleteArtefact = async () => {
    setDeleting(true)
    try {
      await onDelete(artefact.Id || artefact.id || artefact._id)
    } catch (err) {
      toast.error(t('artefacts.failedDelete'))
      setDeleting(false)
    }
  }

  const extractDriveFileId = (url) => {
    const patterns = [
      /\/file\/d\/([^\/]+)/,
      /id=([^&]+)/,
      /\/d\/([^\/]+)/,
    ]

    for (const pattern of patterns) {
      const match = url.match(pattern)
      if (match) return match[1]
    }

    return null
  }

  const getDriveEmbedUrl = (url) => {
    const fileId = extractDriveFileId(url)
    return fileId ? `https://drive.google.com/file/d/${fileId}/preview` : url
  }

  const TypeIcon = TYPE_ICONS[artefact.type] || Sparkles

  const tabs = [
    { key: 'details', label: t('artefacts.details') || 'Details', icon: FileEdit },
    { key: 'versions', label: t('artefacts.versions') || 'Versions', icon: Layers, badge: versions.length },
    { key: 'discussion', label: t('artefacts.comments') || 'Discussion', icon: MessageSquare, badge: comments.length },
    { key: 'review', label: t('artefacts.review') || 'Review', icon: ShieldCheck },
  ]

  if (loading) {
    return (
      <TabbedModal onClose={onClose} size="xl">
        <div className="flex items-center justify-center h-64">
          <div className="w-8 h-8 border-4 border-brand-primary border-t-transparent rounded-full animate-spin"></div>
        </div>
      </TabbedModal>
    )
  }

  return (
    <>
      <TabbedModal
        onClose={onClose}
        size="xl"
        header={
          <>
            <div className="flex items-start gap-3">
              <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">
                <input
                  type="text"
                  value={editTitle}
                  onChange={e => setEditTitle(e.target.value)}
                  className="w-full text-lg font-semibold text-text-primary bg-transparent border-0 border-b border-transparent hover:border-border focus:border-brand-primary focus:outline-none focus:ring-0 px-0 py-0.5 transition-colors"
                />
                <div className="flex items-center gap-2 mt-1 flex-wrap">
                  <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>
                  <span className="text-xs text-text-tertiary capitalize">{artefact.type}</span>
                  {artefact.creator_name && (
                    <span className="text-xs text-text-secondary font-medium">
                      {t('review.createdBy')} <strong className="text-text-primary">{artefact.creator_name}</strong>
                    </span>
                  )}
                </div>
              </div>
            </div>
          </>
        }
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        footer={
          <>
            <div>
              {onDelete && (
                <button
                  onClick={() => setShowDeleteArtefactConfirm(true)}
                  disabled={deleting}
                  className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                  title={t('artefacts.deleteArtefactTooltip')}
                >
                  <Trash2 className="w-3.5 h-3.5" />
                  {t('common.delete')}
                </button>
              )}
            </div>
            <button
              onClick={handleSaveDraft}
              disabled={savingDraft}
              className="flex items-center gap-1.5 px-4 py-1.5 text-xs font-medium bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light disabled:opacity-50 transition-colors"
              title={t('artefacts.saveDraftTooltip')}
            >
              <Save className="w-3.5 h-3.5" />
              {savingDraft ? t('artefacts.savingDraft') : t('artefacts.saveDraft')}
            </button>
          </>
        }
      >
        {/* Details Tab */}
        {activeTab === 'details' && (
          <div className="p-6 space-y-5">
            {/* Description */}
            <div>
              <h4 className="text-xs font-semibold text-text-tertiary uppercase mb-2">{t('artefacts.descriptionLabel')}</h4>
              <textarea
                value={editDescription}
                onChange={e => setEditDescription(e.target.value)}
                rows={3}
                className="w-full px-3 py-2 text-sm text-text-secondary bg-surface-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary resize-none"
                placeholder={t('artefacts.descriptionFieldPlaceholder')}
              />
            </div>

            {/* Project & Campaign dropdowns */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <h4 className="text-xs font-semibold text-text-tertiary uppercase mb-1.5">{t('artefacts.project')}</h4>
                <select
                  value={editProjectId}
                  onChange={e => {
                    setEditProjectId(e.target.value)
                    handleUpdateField('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 bg-surface"
                >
                  <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>
                <h4 className="text-xs font-semibold text-text-tertiary uppercase mb-1.5">{t('artefacts.campaign')}</h4>
                <select
                  value={editCampaignId}
                  onChange={e => {
                    setEditCampaignId(e.target.value)
                    handleUpdateField('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 bg-surface"
                >
                  <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>

            {/* Approvers */}
            <div>
              <h4 className="text-xs font-semibold text-text-tertiary uppercase mb-1.5">{t('artefacts.approversLabel')}</h4>
              <ApproverMultiSelect
                users={assignableUsers}
                selected={editApproverIds}
                onChange={ids => {
                  setEditApproverIds(ids)
                  handleUpdateField('approver_ids', ids.length > 0 ? ids.join(',') : '')
                }}
              />
            </div>
          </div>
        )}

        {/* Versions Tab */}
        {activeTab === 'versions' && (
          <div className="p-6 space-y-5">
            {/* Version Timeline */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <h4 className="text-xs font-semibold text-text-tertiary uppercase">{t('artefacts.versions')}</h4>
                <button
                  onClick={() => setShowNewVersionModal(true)}
                  className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light transition-colors"
                >
                  <Plus className="w-3 h-3" />
                  {t('artefacts.newVersion')}
                </button>
              </div>
              <ArtefactVersionTimeline
                versions={versions}
                activeVersionId={selectedVersion?.Id}
                onSelectVersion={handleSelectVersion}
                artefactType={artefact.type}
              />
            </div>

            {/* Type-specific content */}
            {versionData && selectedVersion && (
              <div className="border-t border-border pt-5">
                {/* COPY TYPE: Language entries */}
                {artefact.type === 'copy' && (
                  <div>
                    <div className="flex items-center justify-between mb-3">
                      <h4 className="text-xs font-semibold text-text-tertiary uppercase">{t('artefacts.languages')}</h4>
                      <button
                        onClick={() => setShowLanguageModal(true)}
                        className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light transition-colors"
                      >
                        <Plus className="w-3 h-3" />
                        {t('artefacts.addLanguage')}
                      </button>
                    </div>

                    {versionData.texts && versionData.texts.length > 0 ? (
                      <div className="space-y-3">
                        {versionData.texts.map(text => (
                          <div key={text.Id} className="bg-surface-secondary rounded-lg p-4 border border-border">
                            <div className="flex items-start justify-between mb-2">
                              <div className="flex items-center gap-2">
                                <span className="px-2 py-0.5 bg-surface border border-border rounded text-xs font-mono font-medium">
                                  {text.language_code}
                                </span>
                                <span className="text-sm font-medium text-text-primary">{text.language_label}</span>
                              </div>
                              <button
                                onClick={() => setConfirmDeleteLangId(text.Id)}
                                className="text-red-600 hover:text-red-700"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                            <div className="bg-surface rounded border border-border p-3 text-sm text-text-primary whitespace-pre-wrap font-sans">
                              {text.content}
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="text-center py-8 bg-surface-secondary rounded-lg border-2 border-dashed border-border">
                        <Globe className="w-8 h-8 text-text-tertiary mx-auto mb-2" />
                        <p className="text-sm text-text-secondary">{t('artefacts.noLanguages')}</p>
                      </div>
                    )}
                  </div>
                )}

                {/* DESIGN TYPE: Image gallery */}
                {artefact.type === 'design' && (
                  <div>
                    <div className="flex items-center justify-between mb-3">
                      <h4 className="text-xs font-semibold text-text-tertiary uppercase">{t('artefacts.imagesLabel')}</h4>
                      <label className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light transition-colors cursor-pointer">
                        <Upload className="w-3 h-3" />
                        {uploading ? t('artefacts.uploading') : t('artefacts.uploadImage')}
                        <input
                          type="file"
                          className="hidden"
                          accept="image/*"
                          onChange={handleFileUpload}
                          disabled={uploading}
                        />
                      </label>
                    </div>

                    {versionData.attachments && versionData.attachments.length > 0 ? (
                      <div className="grid grid-cols-2 gap-3">
                        {versionData.attachments.map(att => (
                          <div key={att.Id} className="relative group">
                            <img
                              src={att.url}
                              alt={att.original_name}
                              className="w-full h-48 object-cover rounded-lg border border-border"
                            />
                            <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors rounded-lg flex items-center justify-center">
                              <button
                                onClick={() => setConfirmDeleteAttId(att.Id)}
                                className="opacity-0 group-hover:opacity-100 transition-opacity px-3 py-2 bg-red-600 text-white rounded-lg text-xs font-medium hover:bg-red-700"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                            <div className="mt-1 px-2 py-1 bg-surface-secondary rounded text-xs text-text-secondary truncate">
                              {att.original_name}
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="text-center py-8 bg-surface-secondary rounded-lg border-2 border-dashed border-border">
                        <ImageIcon className="w-8 h-8 text-text-tertiary mx-auto mb-2" />
                        <p className="text-sm text-text-secondary">{t('artefacts.noImages')}</p>
                      </div>
                    )}
                  </div>
                )}

                {/* VIDEO TYPE: Files and Drive links — all inline */}
                {artefact.type === 'video' && (
                  <div>
                    <h4 className="text-xs font-semibold text-text-tertiary uppercase mb-3">{t('artefacts.videosLabel')}</h4>

                    {/* Existing attachments */}
                    {versionData.attachments && versionData.attachments.length > 0 && (
                      <div className="space-y-3 mb-4">
                        {versionData.attachments.map(att => (
                          <div key={att.Id} className="bg-surface-secondary rounded-lg p-4 border border-border">
                            {att.drive_url ? (
                              <div>
                                <div className="flex items-center justify-between mb-2">
                                  <span className="text-sm font-medium text-text-primary">{t('artefacts.googleDriveVideo')}</span>
                                  <button onClick={() => setConfirmDeleteAttId(att.Id)} className="text-red-600 hover:text-red-700">
                                    <Trash2 className="w-4 h-4" />
                                  </button>
                                </div>
                                <iframe src={getDriveEmbedUrl(att.drive_url)} className="w-full h-64 rounded border border-border" allow="autoplay" />
                              </div>
                            ) : (
                              <div>
                                <div className="flex items-center justify-between mb-2">
                                  <span className="text-sm font-medium text-text-primary truncate">{att.original_name}</span>
                                  <button onClick={() => setConfirmDeleteAttId(att.Id)} className="text-red-600 hover:text-red-700">
                                    <Trash2 className="w-4 h-4" />
                                  </button>
                                </div>
                                <video src={att.url} controls className="w-full rounded border border-border" />
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    )}

                    {/* Drag-and-drop / click-to-upload zone */}
                    <label
                      className={`flex flex-col items-center gap-2 px-6 py-6 border-2 border-dashed rounded-lg cursor-pointer transition-colors ${
                        dragOver ? 'border-brand-primary bg-brand-primary/5' : 'border-border hover:border-brand-primary/30'
                      } ${uploading ? 'pointer-events-none opacity-60' : ''}`}
                      onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
                      onDragLeave={() => setDragOver(false)}
                      onDrop={handleVideoDrop}
                    >
                      {uploading ? (
                        <>
                          <div className="w-full max-w-xs bg-surface-tertiary rounded-full h-2 overflow-hidden">
                            <div className="bg-brand-primary h-full rounded-full transition-all duration-300" style={{ width: `${uploadProgress}%` }} />
                          </div>
                          <span className="text-sm text-text-secondary">{t('artefacts.uploading')} {uploadProgress}%</span>
                        </>
                      ) : (
                        <>
                          <Upload className="w-7 h-7 text-text-tertiary" />
                          <span className="text-sm font-medium text-text-primary">{t('artefacts.dropOrClickVideo')}</span>
                          <span className="text-xs text-text-tertiary">{t('artefacts.videoFormats')}</span>
                        </>
                      )}
                      <input type="file" className="hidden" accept="video/*" onChange={handleFileUpload} disabled={uploading} />
                    </label>

                    {/* Google Drive URL inline input */}
                    <div className="flex items-center gap-2 mt-3">
                      <Globe className="w-4 h-4 text-text-tertiary shrink-0" />
                      <input
                        type="text"
                        value={driveUrl}
                        onChange={e => setDriveUrl(e.target.value)}
                        placeholder="https://drive.google.com/file/d/..."
                        className="flex-1 px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20"
                        onKeyDown={e => { if (e.key === 'Enter' && driveUrl.trim()) handleAddDriveVideo() }}
                      />
                      <button
                        onClick={handleAddDriveVideo}
                        disabled={uploading || !driveUrl.trim()}
                        className="px-3 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 shrink-0"
                      >
                        {t('artefacts.addLink')}
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Discussion Tab */}
        {activeTab === 'discussion' && (
          <div className="p-6 space-y-5">
            {selectedVersion ? (
              <>
                <h4 className="text-xs font-semibold text-text-tertiary uppercase mb-3">
                  {t('artefacts.comments')} ({comments.length})
                </h4>

                <div className="space-y-3 mb-4">
                  {comments.map(comment => (
                    <div key={comment.Id} className="flex gap-3">
                      <div className="w-8 h-8 rounded-full bg-brand-primary/10 flex items-center justify-center shrink-0">
                        {comment.user_avatar ? (
                          <img src={comment.user_avatar} alt="" className="w-full h-full rounded-full object-cover" />
                        ) : (
                          <MessageSquare className="w-4 h-4 text-brand-primary" />
                        )}
                      </div>
                      <div className="flex-1 bg-surface-secondary rounded-lg p-3">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-sm font-medium text-text-primary">{comment.user_name || 'Anonymous'}</span>
                          <span className="text-xs text-text-tertiary">
                            {new Date(comment.CreatedAt).toLocaleString()}
                          </span>
                        </div>
                        <p className="text-sm text-text-secondary whitespace-pre-wrap">{comment.content}</p>
                      </div>
                    </div>
                  ))}
                </div>

                <div className="flex gap-2">
                  <input
                    type="text"
                    value={newComment}
                    onChange={e => setNewComment(e.target.value)}
                    onKeyPress={e => e.key === 'Enter' && handleAddComment()}
                    placeholder={t('artefacts.addCommentPlaceholder')}
                    className="flex-1 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"
                  />
                  <button
                    onClick={handleAddComment}
                    disabled={addingComment || !newComment.trim()}
                    className="px-4 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 transition-colors"
                  >
                    {t('artefacts.sendComment')}
                  </button>
                </div>
              </>
            ) : (
              <div className="text-center py-8 text-sm text-text-tertiary">
                {t('artefacts.selectVersionFirst') || 'Select a version first to view comments.'}
              </div>
            )}
          </div>
        )}

        {/* Review Tab */}
        {activeTab === 'review' && (
          <div className="p-6 space-y-5">
            {/* Submit for Review */}
            {['draft', 'revision_requested', 'rejected'].includes(artefact.status) && (
              <button
                onClick={handleSubmitReview}
                disabled={submitting}
                className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors font-medium disabled:opacity-50"
              >
                <ExternalLink className="w-4 h-4" />
                {submitting ? t('artefacts.submitting') : t('artefacts.submitForReview')}
              </button>
            )}

            {/* Review Link */}
            {reviewUrl && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="text-sm font-semibold text-blue-900 mb-2">{t('artefacts.reviewLinkTitle')}</div>
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={reviewUrl}
                    readOnly
                    className="flex-1 px-3 py-2 text-sm bg-surface border border-border rounded"
                  />
                  <button
                    onClick={copyReviewLink}
                    className="p-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                  >
                    {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                  </button>
                </div>
              </div>
            )}

            {/* Feedback */}
            {artefact.feedback && (
              <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
                <h4 className="text-sm font-semibold text-amber-900 mb-2">{t('artefacts.feedbackTitle')}</h4>
                <p className="text-sm text-amber-800 whitespace-pre-wrap">{artefact.feedback}</p>
              </div>
            )}

            {/* Approval Info */}
            {artefact.status === 'approved' && artefact.approved_by_name && (
              <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-4">
                <div className="font-medium text-emerald-900">{t('artefacts.approvedByLabel')} {artefact.approved_by_name}</div>
                {artefact.approved_at && (
                  <div className="text-sm text-emerald-700 mt-1">
                    {new Date(artefact.approved_at).toLocaleString()}
                  </div>
                )}
              </div>
            )}

            {/* Empty state when no review actions available */}
            {!['draft', 'revision_requested', 'rejected'].includes(artefact.status) && !reviewUrl && !artefact.feedback && !(artefact.status === 'approved' && artefact.approved_by_name) && (
              <div className="text-center py-8 text-sm text-text-tertiary">
                {artefact.status === 'pending_review'
                  ? t('artefacts.pendingReviewInfo') || 'This artefact is currently pending review.'
                  : t('artefacts.noReviewInfo') || 'No review information available.'}
              </div>
            )}
          </div>
        )}
      </TabbedModal>

      {/* Language Modal */}
      <Modal isOpen={showLanguageModal} onClose={() => setShowLanguageModal(false)} title={t('artefacts.addLanguage')} size="md">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.languageLabel')} *</label>
            <select
              value={languageForm.language_code}
              onChange={e => {
                const lang = AVAILABLE_LANGUAGES.find(l => l.code === e.target.value)
                if (lang) setLanguageForm(f => ({ ...f, language_code: lang.code, language_label: lang.label }))
                else setLanguageForm(f => ({ ...f, language_code: '', language_label: '' }))
              }}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-surface focus:outline-none focus:ring-2 focus:ring-brand-primary/20"
            >
              <option value="">{t('artefacts.selectLanguage')}</option>
              {AVAILABLE_LANGUAGES
                .filter(lang => !(versionData?.texts || []).some(t => t.language_code === lang.code))
                .map(lang => (
                  <option key={lang.code} value={lang.code}>{lang.label} ({lang.code})</option>
                ))
              }
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.contentLabel')} *</label>
            <textarea
              value={languageForm.content}
              onChange={e => setLanguageForm(f => ({ ...f, content: e.target.value }))}
              rows={8}
              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 font-sans"
              placeholder={t('artefacts.enterContent')}
            />
          </div>
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-border">
            <button
              onClick={() => setShowLanguageModal(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={handleAddLanguage}
              disabled={savingLanguage}
              className="px-5 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 shadow-sm"
            >
              {savingLanguage ? t('header.saving') : t('common.save')}
            </button>
          </div>
        </div>
      </Modal>

      {/* New Version Modal */}
      <Modal isOpen={showNewVersionModal} onClose={() => setShowNewVersionModal(false)} title={t('artefacts.createNewVersion')} size="sm">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('artefacts.versionNotes')}</label>
            <textarea
              value={newVersionNotes}
              onChange={e => setNewVersionNotes(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"
              placeholder={t('artefacts.whatChanged')}
            />
          </div>
          {artefact.type === 'copy' && versions.length > 0 && (
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={copyFromPrevious}
                onChange={e => setCopyFromPrevious(e.target.checked)}
                className="w-4 h-4 text-brand-primary border-border rounded focus:ring-brand-primary"
              />
              <span className="text-sm text-text-secondary">{t('artefacts.copyLanguages')}</span>
            </label>
          )}
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-border">
            <button
              onClick={() => setShowNewVersionModal(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={handleCreateVersion}
              disabled={creatingVersion}
              className="px-5 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 shadow-sm"
            >
              {creatingVersion ? t('artefacts.creatingVersion') : t('artefacts.createVersion')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Delete Language Confirmation */}
      <Modal
        isOpen={!!confirmDeleteLangId}
        onClose={() => setConfirmDeleteLangId(null)}
        title={t('artefacts.deleteLanguage')}
        isConfirm
        danger
        onConfirm={() => handleDeleteLanguage(confirmDeleteLangId)}
        confirmText={t('common.delete')}
      >
        {t('artefacts.deleteLanguageDesc')}
      </Modal>

      {/* Delete Attachment Confirmation */}
      <Modal
        isOpen={!!confirmDeleteAttId}
        onClose={() => setConfirmDeleteAttId(null)}
        title={t('artefacts.deleteAttachment')}
        isConfirm
        danger
        onConfirm={() => handleDeleteAttachment(confirmDeleteAttId)}
        confirmText={t('common.delete')}
      >
        {t('artefacts.deleteAttachmentDesc')}
      </Modal>

      {/* Delete Artefact Confirmation */}
      <Modal
        isOpen={showDeleteArtefactConfirm}
        onClose={() => setShowDeleteArtefactConfirm(false)}
        title={t('artefacts.deleteArtefact')}
        isConfirm
        danger
        onConfirm={handleDeleteArtefact}
        confirmText={t('common.delete')}
      >
        {t('artefacts.deleteArtefactDesc')}
      </Modal>
    </>
  )
}
