import { useState, useEffect, useRef } from 'react'
import { X, Trash2, Upload, FileText, Link2, ExternalLink, FolderOpen, Image as ImageIcon, Music, Film, Send, CheckCircle2, XCircle, Copy, Check, Plus, Globe, Clock, User, FileEdit, Layers, Share2, ShieldCheck, MessageSquare } from 'lucide-react'
import { useLanguage } from '../i18n/LanguageContext'
import { api, PLATFORMS, getBrandColor } from '../utils/api'
import ApproverMultiSelect from './ApproverMultiSelect'
import CommentsSection from './CommentsSection'
import Modal from './Modal'
import TabbedModal from './TabbedModal'
import { useToast } from './ToastContainer'

const AVAILABLE_LANGUAGES = [
  { code: 'ar', label: 'Arabic' },
  { code: 'en', label: 'English' },
  { code: 'fr', label: 'French' },
  { code: 'id', label: 'Bahasa Indonesia' },
]

const TABS = ['details', 'versions', 'platforms', 'approval', 'discussion']

export default function PostDetailPanel({ post, onClose, onSave, onDelete, brands, teamMembers, campaigns }) {
  const { t, lang } = useLanguage()
  const toast = useToast()
  const imageInputRef = useRef(null)
  const audioInputRef = useRef(null)
  const videoInputRef = useRef(null)
  const versionFileInputRef = useRef(null)
  const [activeTab, setActiveTab] = useState('details')
  const [form, setForm] = useState({})
  const [dirty, setDirty] = useState(false)
  const [saving, setSaving] = useState(false)
  const [publishError, setPublishError] = useState('')
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)

  // Review state
  const [submittingReview, setSubmittingReview] = useState(false)
  const [copied, setCopied] = useState(false)

  // Attachments state (non-versioned, legacy)
  const [attachments, setAttachments] = useState([])
  const [uploading, setUploading] = useState(false)
  const [dragActive, setDragActive] = useState(false)
  const [showAssetPicker, setShowAssetPicker] = useState(false)
  const [availableAssets, setAvailableAssets] = useState([])
  const [assetSearch, setAssetSearch] = useState('')

  // Versions state
  const [versions, setVersions] = useState([])
  const [selectedVersion, setSelectedVersion] = useState(null)
  const [versionData, setVersionData] = useState(null)
  const [showNewVersionModal, setShowNewVersionModal] = useState(false)
  const [newVersionNotes, setNewVersionNotes] = useState('')
  const [copyFromPrevious, setCopyFromPrevious] = useState(false)
  const [creatingVersion, setCreatingVersion] = useState(false)
  const [showLanguageModal, setShowLanguageModal] = useState(false)
  const [languageForm, setLanguageForm] = useState({ language_code: '', language_label: '', content: '' })
  const [savingLanguage, setSavingLanguage] = useState(false)
  const [confirmDeleteLangId, setConfirmDeleteLangId] = useState(null)
  const [confirmDeleteAttId, setConfirmDeleteAttId] = useState(null)
  const [uploadingVersionFile, setUploadingVersionFile] = useState(false)

  const postId = post?._id || post?.id
  const isCreateMode = !postId
  const reviewUrl = post?.approval_token ? `${window.location.origin}/review-post/${post.approval_token}` : ''

  useEffect(() => {
    if (post) {
      setForm({
        title: post.title || '',
        description: post.description || '',
        brand_id: post.brandId || post.brand_id || '',
        platforms: post.platforms || (post.platform ? [post.platform] : []),
        status: post.status || 'draft',
        assigned_to: post.assignedTo || post.assigned_to || '',
        scheduled_date: post.scheduledDate ? new Date(post.scheduledDate).toISOString().slice(0, 10) : (post.scheduled_date ? new Date(post.scheduled_date).toISOString().slice(0, 10) : ''),
        notes: post.notes || '',
        campaign_id: post.campaignId || post.campaign_id || '',
        publication_links: post.publication_links || post.publicationLinks || [],
        approver_ids: post.approvers?.map(a => String(a.id)) || (post.approver_ids ? post.approver_ids.split(',').map(s => s.trim()).filter(Boolean) : []),
      })
      setDirty(isCreateMode)
      setPublishError('')
      setActiveTab('details')
      if (!isCreateMode) {
        loadAttachments()
        loadVersions()
      }
    }
  }, [post])

  if (!post) return null

  const statusOptions = [
    { value: 'draft', label: t('posts.status.draft') },
    { value: 'in_review', label: t('posts.status.in_review') },
    { value: 'approved', label: t('posts.status.approved') },
    { value: 'rejected', label: t('posts.status.rejected') },
    { value: 'scheduled', label: t('posts.status.scheduled') },
    { value: 'published', label: t('posts.status.published') },
  ]

  const update = (field, value) => {
    setForm(f => ({ ...f, [field]: value }))
    setDirty(true)
  }

  const updatePublicationLink = (platform, url) => {
    setForm(f => {
      const links = [...(f.publication_links || [])]
      const idx = links.findIndex(l => l.platform === platform)
      if (idx >= 0) {
        links[idx] = { ...links[idx], url }
      } else {
        links.push({ platform, url })
      }
      return { ...f, publication_links: links }
    })
    setDirty(true)
  }

  const handleSave = async () => {
    setPublishError('')
    setSaving(true)
    try {
      const data = {
        title: form.title,
        description: form.description,
        brand_id: form.brand_id ? Number(form.brand_id) : null,
        assigned_to: form.assigned_to ? Number(form.assigned_to) : null,
        status: form.status,
        platforms: form.platforms || [],
        scheduled_date: form.scheduled_date || null,
        notes: form.notes,
        campaign_id: form.campaign_id ? Number(form.campaign_id) : null,
        publication_links: form.publication_links || [],
        approver_ids: (form.approver_ids || []).length > 0 ? form.approver_ids.join(',') : null,
      }

      if (data.status === 'published' && data.platforms.length > 0) {
        const missingPlatforms = data.platforms.filter(platform => {
          const link = (data.publication_links || []).find(l => l.platform === platform)
          return !link || !link.url || !link.url.trim()
        })
        if (missingPlatforms.length > 0) {
          const names = missingPlatforms.map(p => PLATFORMS[p]?.label || p).join(', ')
          setPublishError(`${t('posts.publishMissing')} ${names}`)
          setSaving(false)
          return
        }
      }

      await onSave(isCreateMode ? null : postId, data)
      setDirty(false)
      if (isCreateMode) onClose()
    } catch (err) {
      if (err.message?.includes('Cannot publish')) {
        setPublishError(err.message.replace(/.*: /, ''))
      }
    } finally {
      setSaving(false)
    }
  }

  const handleStatusAction = async (newStatus) => {
    if (!postId || saving) return
    setSaving(true)
    try {
      await onSave(postId, { ...form, status: newStatus, approver_ids: (form.approver_ids || []).length > 0 ? form.approver_ids.join(',') : null })
      setForm(f => ({ ...f, status: newStatus }))
      setDirty(false)
    } finally {
      setSaving(false)
    }
  }

  const handleSubmitReview = async () => {
    if (!postId || submittingReview) return
    if (dirty) await handleSave()
    setSubmittingReview(true)
    try {
      await api.post(`/posts/${postId}/submit-review`)
      setForm(f => ({ ...f, status: 'in_review' }))
      toast.success(t('posts.submittedForReview'))
      onSave(postId, {})
    } catch (err) {
      toast.error(err.message || t('posts.failedSubmitReview'))
    } finally {
      setSubmittingReview(false)
    }
  }

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

  const confirmDelete = async () => {
    setShowDeleteConfirm(false)
    await onDelete(postId)
    onClose()
  }

  // ─── Legacy Attachments ──────────────────────────
  async function loadAttachments() {
    if (!postId) return
    try {
      const data = await api.get(`/posts/${postId}/attachments`)
      setAttachments(Array.isArray(data) ? data : [])
    } catch {
      setAttachments([])
    }
  }

  const handleFileUpload = async (files) => {
    if (!postId || !files?.length) return
    setUploading(true)
    for (const file of files) {
      const fd = new FormData()
      fd.append('file', file)
      try {
        await api.upload(`/posts/${postId}/attachments`, fd)
      } catch (err) {
        console.error('Upload failed:', err)
      }
    }
    setUploading(false)
    loadAttachments()
  }

  const handleDeleteAttachment = async (attId) => {
    try {
      await api.delete(`/attachments/${attId}`)
      loadAttachments()
    } catch (err) {
      console.error('Delete attachment failed:', err)
    }
  }

  const openAssetPicker = async () => {
    try {
      const data = await api.get('/assets')
      setAvailableAssets(Array.isArray(data) ? data : [])
    } catch {
      setAvailableAssets([])
    }
    setAssetSearch('')
    setShowAssetPicker(true)
  }

  const handleAttachAsset = async (assetId) => {
    if (!postId) return
    try {
      await api.post(`/posts/${postId}/attachments/from-asset`, { asset_id: assetId })
      loadAttachments()
      setShowAssetPicker(false)
    } catch (err) {
      console.error('Attach asset failed:', err)
    }
  }

  const handleDrop = (e) => {
    e.preventDefault(); e.stopPropagation(); setDragActive(false)
    if (e.dataTransfer.files?.length) handleFileUpload(e.dataTransfer.files)
  }

  // ─── Versions ──────────────────────────
  async function loadVersions() {
    if (!postId) return
    try {
      const data = await api.get(`/posts/${postId}/versions`)
      const vList = Array.isArray(data) ? data : []
      setVersions(vList)
      if (vList.length > 0) {
        const latest = vList[vList.length - 1]
        setSelectedVersion(latest)
        loadVersionData(latest.Id || latest.id || latest._id)
      } else {
        setSelectedVersion(null)
        setVersionData(null)
      }
    } catch {
      setVersions([])
    }
  }

  async function loadVersionData(versionId) {
    if (!postId || !versionId) return
    try {
      const data = await api.get(`/posts/${postId}/versions/${versionId}`)
      setVersionData(data)
    } catch {
      setVersionData(null)
    }
  }

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

  const handleCreateVersion = async () => {
    setCreatingVersion(true)
    try {
      await api.post(`/posts/${postId}/versions`, {
        notes: newVersionNotes || undefined,
        copy_from_previous: copyFromPrevious,
      })
      setShowNewVersionModal(false)
      setNewVersionNotes('')
      setCopyFromPrevious(false)
      loadVersions()
    } catch (err) {
      console.error('Create version failed:', err)
    } finally {
      setCreatingVersion(false)
    }
  }

  const handleAddLanguage = async () => {
    if (!selectedVersion || !languageForm.language_code || !languageForm.content) return
    setSavingLanguage(true)
    try {
      const vId = selectedVersion.Id || selectedVersion.id || selectedVersion._id
      await api.post(`/posts/${postId}/versions/${vId}/texts`, languageForm)
      setShowLanguageModal(false)
      setLanguageForm({ language_code: '', language_label: '', content: '' })
      loadVersionData(vId)
    } catch (err) {
      console.error('Add language failed:', err)
    } finally {
      setSavingLanguage(false)
    }
  }

  const handleDeleteLanguage = async (textId) => {
    try {
      await api.delete(`/post-version-texts/${textId}`)
      setConfirmDeleteLangId(null)
      const vId = selectedVersion.Id || selectedVersion.id || selectedVersion._id
      loadVersionData(vId)
    } catch (err) {
      console.error('Delete language failed:', err)
    }
  }

  const handleVersionFileUpload = async (files) => {
    if (!selectedVersion || !files?.length) return
    setUploadingVersionFile(true)
    const vId = selectedVersion.Id || selectedVersion.id || selectedVersion._id
    for (const file of files) {
      const fd = new FormData()
      fd.append('file', file)
      try {
        await api.upload(`/posts/${postId}/versions/${vId}/attachments`, fd)
      } catch (err) {
        console.error('Version upload failed:', err)
      }
    }
    setUploadingVersionFile(false)
    loadVersionData(vId)
  }

  const handleDeleteVersionAttachment = async (attId) => {
    try {
      await api.delete(`/attachments/${attId}`)
      setConfirmDeleteAttId(null)
      const vId = selectedVersion.Id || selectedVersion.id || selectedVersion._id
      loadVersionData(vId)
    } catch (err) {
      console.error('Delete version attachment failed:', err)
    }
  }

  const brandName = (() => {
    if (form.brand_id) {
      const b = brands?.find(b => String(b._id || b.id) === String(form.brand_id))
      return b ? (lang === 'ar' && b.name_ar ? b.name_ar : b.name) : null
    }
    return post.brand_name || post.brandName || null
  })()

  const tabConfig = {
    details:    { label: t('posts.details'),        icon: FileEdit },
    versions:   { label: t('posts.versions'),       icon: Layers, badge: versions.length || null },
    platforms:  { label: t('posts.platformsLinks'),  icon: Share2 },
    approval:   { label: t('posts.approval'),       icon: ShieldCheck },
    discussion: { label: t('posts.discussion'),     icon: MessageSquare },
  }

  // Filter tabs: hide some in create mode
  const visibleTabs = isCreateMode
    ? ['details', 'platforms']
    : TABS

  const modalHeader = (
    <>
      <input
        type="text"
        value={form.title}
        onChange={e => update('title', e.target.value)}
        className="w-full text-lg font-semibold text-text-primary bg-transparent border-0 p-0 focus:outline-none focus:ring-0"
        placeholder={t('posts.postTitlePlaceholder')}
      />
      <div className="flex items-center gap-2 mt-2 flex-wrap">
        <span className={`text-[11px] px-2.5 py-0.5 rounded-full font-medium ${
          form.status === 'published' ? 'bg-emerald-100 text-emerald-700' :
          form.status === 'scheduled' ? 'bg-purple-100 text-purple-700' :
          form.status === 'approved' ? 'bg-blue-100 text-blue-700' :
          form.status === 'in_review' ? 'bg-amber-100 text-amber-700' :
          form.status === 'rejected' ? 'bg-red-100 text-red-700' :
          'bg-gray-100 text-gray-600'
        }`}>
          {statusOptions.find(s => s.value === form.status)?.label}
        </span>
        {brandName && (
          <span className={`text-[11px] px-2 py-0.5 rounded-full ${getBrandColor(brandName).bg} ${getBrandColor(brandName).text}`}>
            {brandName}
          </span>
        )}
        {post.current_version && (
          <span className="text-[11px] px-2 py-0.5 rounded-full bg-indigo-50 text-indigo-600 font-medium">
            v{post.current_version}
          </span>
        )}
        {post.creator_user_name && (
          <span className="text-[11px] text-text-tertiary">
            {t('review.createdBy')} <span className="text-text-secondary font-medium">{post.creator_user_name}</span>
          </span>
        )}
      </div>
    </>
  )

  const modalFooter = (
    <>
      <div className="flex items-center gap-2">
        {onDelete && !isCreateMode && (
          <button
            onClick={() => setShowDeleteConfirm(true)}
            className="px-3 py-2 text-sm font-medium text-red-600 hover:bg-red-50 rounded-lg transition-colors"
          >
            <Trash2 className="w-4 h-4" />
          </button>
        )}
      </div>
      <div className="flex items-center gap-2.5">
        {dirty ? (
          <>
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-text-secondary hover:bg-surface-tertiary rounded-lg transition-colors"
            >
              {t('common.cancel')}
            </button>
            <button
              onClick={handleSave}
              disabled={!form.title || saving}
              className={`px-6 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 transition-colors ${saving ? 'btn-loading' : ''}`}
            >
              {isCreateMode ? t('posts.createPost') : t('posts.saveChanges')}
            </button>
          </>
        ) : (
          <button
            onClick={onClose}
            className="px-5 py-2 text-sm font-medium text-text-secondary border border-border rounded-lg hover:bg-surface-tertiary transition-colors"
          >
            {t('common.close')}
          </button>
        )}
      </div>
    </>
  )

  return (
    <>
      <TabbedModal
        onClose={onClose}
        size="xl"
        header={modalHeader}
        tabs={visibleTabs.map(tab => ({ key: tab, ...tabConfig[tab] }))}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        footer={modalFooter}
      >
            {/* ─── Details Tab ─── */}
            {activeTab === 'details' && (
              <div className="p-6 space-y-5">
                {/* Two-column layout for details */}
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
                  {/* Main content — left column */}
                  <div className="lg:col-span-2 space-y-4">
                    <div className="bg-surface-secondary rounded-xl p-4 space-y-4">
                      <div>
                        <label className="block text-xs font-medium text-text-primary mb-1.5">{t('posts.description')}</label>
                        <textarea
                          value={form.description}
                          onChange={e => update('description', e.target.value)}
                          rows={4}
                          className="w-full px-3 py-2.5 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary resize-none"
                          placeholder={t('posts.postDescPlaceholder')}
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-text-primary mb-1.5">{t('posts.notes')}</label>
                        <input
                          type="text"
                          value={form.notes}
                          onChange={e => update('notes', e.target.value)}
                          className="w-full px-3 py-2.5 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                          placeholder={t('posts.additionalNotes')}
                        />
                      </div>
                    </div>

                    {publishError && (
                      <div className="p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700 flex items-center gap-2">
                        <XCircle className="w-4 h-4 shrink-0" />
                        {publishError}
                      </div>
                    )}

                    {/* Legacy Attachments (non-versioned) */}
                    {!isCreateMode && (
                      <div>
                        <div className="flex items-center justify-between mb-3">
                          <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wide">{t('posts.attachments')}</h4>
                          {attachments.length > 0 && (
                            <span className="text-[10px] font-medium text-text-tertiary bg-surface-tertiary px-1.5 py-0.5 rounded-full">
                              {attachments.length}
                            </span>
                          )}
                        </div>
                        {renderAttachments()}
                      </div>
                    )}
                  </div>

                  {/* Sidebar — right column */}
                  <div className="space-y-4">
                    <div className="bg-surface-secondary rounded-xl p-4 space-y-3">
                      <div>
                        <label className="block text-xs font-medium text-text-primary mb-1.5">{t('posts.status')}</label>
                        <select
                          value={form.status}
                          onChange={e => update('status', e.target.value)}
                          className="w-full px-3 py-2.5 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                        >
                          {statusOptions.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-text-primary mb-1.5">{t('posts.scheduledDate')}</label>
                        <input
                          type="date"
                          value={form.scheduled_date}
                          onChange={e => update('scheduled_date', e.target.value)}
                          className="w-full px-3 py-2.5 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-text-primary mb-1.5">{t('posts.assignTo')}</label>
                        <select
                          value={form.assigned_to}
                          onChange={e => update('assigned_to', e.target.value)}
                          className="w-full px-3 py-2.5 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                        >
                          <option value="">{t('common.unassigned')}</option>
                          {(teamMembers || []).map(m => <option key={m._id || m.id} value={m._id || m.id}>{m.name}</option>)}
                        </select>
                      </div>
                    </div>

                    <div className="bg-surface-secondary rounded-xl p-4 space-y-3">
                      <div>
                        <label className="block text-xs font-medium text-text-primary mb-1.5">{t('posts.brand')}</label>
                        <select
                          value={form.brand_id}
                          onChange={e => update('brand_id', e.target.value)}
                          className="w-full px-3 py-2.5 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                        >
                          <option value="">{t('posts.selectBrand')}</option>
                          {(brands || []).map(b => <option key={b._id || b.id} value={b._id || b.id}>{b.icon} {lang === 'ar' && b.name_ar ? b.name_ar : b.name}</option>)}
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-text-primary mb-1.5">{t('posts.campaign')}</label>
                        <select
                          value={form.campaign_id}
                          onChange={e => update('campaign_id', e.target.value)}
                          className="w-full px-3 py-2.5 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                        >
                          <option value="">{t('posts.noCampaign')}</option>
                          {(campaigns || []).map(c => <option key={c._id || c.id} value={c._id || c.id}>{c.name}</option>)}
                        </select>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* ─── Versions Tab ─── */}
            {activeTab === 'versions' && !isCreateMode && (
              <div className="flex h-full">
                {/* Version Timeline (left sidebar) */}
                <div className="w-64 shrink-0 border-e border-border p-4 overflow-y-auto bg-surface-secondary/50">
                  <div className="flex items-center justify-between mb-4">
                    <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wide">{t('posts.versions')}</h4>
                    <button
                      onClick={() => setShowNewVersionModal(true)}
                      className="flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light transition-colors shadow-sm"
                    >
                      <Plus className="w-3 h-3" />
                      {t('posts.newVersion')}
                    </button>
                  </div>

                  {versions.length === 0 ? (
                    <div className="text-center py-10">
                      <div className="w-12 h-12 rounded-full bg-surface-tertiary flex items-center justify-center mx-auto mb-3">
                        <Layers className="w-6 h-6 text-text-quaternary" />
                      </div>
                      <p className="text-xs text-text-tertiary leading-relaxed px-2">{t('posts.noVersions')}</p>
                    </div>
                  ) : (
                    <div className="space-y-1.5">
                      {versions.map((version, idx) => {
                        const vId = version.Id || version.id || version._id
                        const isActive = vId === (selectedVersion?.Id || selectedVersion?.id || selectedVersion?._id)
                        const isLatest = idx === versions.length - 1
                        return (
                          <button
                            key={vId}
                            onClick={() => handleSelectVersion(version)}
                            className={`w-full text-start p-3 rounded-xl border transition-all ${
                              isActive
                                ? 'border-brand-primary bg-white shadow-sm ring-1 ring-brand-primary/20'
                                : 'border-transparent hover:bg-white hover:border-border'
                            }`}
                          >
                            <div className="flex items-center gap-2.5">
                              <div className={`flex-shrink-0 w-7 h-7 rounded-lg flex items-center justify-center text-[11px] font-bold ${
                                isActive ? 'bg-brand-primary text-white' : 'bg-surface-tertiary text-text-secondary'
                              }`}>
                                {version.version_number}
                              </div>
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-1.5">
                                  <span className={`text-sm font-medium ${isActive ? 'text-brand-primary' : 'text-text-primary'}`}>
                                    v{version.version_number}
                                  </span>
                                  {isLatest && (
                                    <span className="text-[9px] px-1.5 py-px bg-emerald-100 text-emerald-700 rounded font-semibold uppercase">
                                      Latest
                                    </span>
                                  )}
                                </div>
                                {version.notes && (
                                  <p className="text-[11px] text-text-tertiary line-clamp-1 mt-0.5">{version.notes}</p>
                                )}
                              </div>
                            </div>
                            {(version.creator_name || version.created_at) && (
                              <div className="flex items-center gap-2 mt-2 ms-[38px] text-[10px] text-text-quaternary">
                                {version.creator_name && <span>{version.creator_name}</span>}
                                {version.creator_name && version.created_at && <span>·</span>}
                                {version.created_at && <span>{new Date(version.created_at).toLocaleDateString()}</span>}
                              </div>
                            )}
                          </button>
                        )
                      })}
                    </div>
                  )}
                </div>

                {/* Version Content (right side) */}
                <div className="flex-1 min-w-0 overflow-y-auto p-6">
                  {selectedVersion && versionData ? (
                    <div className="space-y-6 w-full">
                      {/* Languages */}
                      <div>
                        <div className="flex items-center justify-between mb-3">
                          <div className="flex items-center gap-2">
                            <Globe className="w-4 h-4 text-text-tertiary" />
                            <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wide">{t('posts.languages')}</h4>
                            {versionData.texts?.length > 0 && (
                              <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-surface-tertiary text-text-tertiary font-medium">
                                {versionData.texts.length}
                              </span>
                            )}
                          </div>
                          <button
                            onClick={() => setShowLanguageModal(true)}
                            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-brand-primary border border-brand-primary/30 hover:bg-brand-primary/5 rounded-lg transition-colors"
                          >
                            <Plus className="w-3 h-3" />
                            {t('posts.addLanguage')}
                          </button>
                        </div>

                        {versionData.texts && versionData.texts.length > 0 ? (
                          <div className="space-y-3">
                            {versionData.texts.map(text => {
                              const tId = text.Id || text.id || text._id
                              return (
                                <div key={tId} className="rounded-xl border border-border overflow-hidden">
                                  <div className="flex items-center justify-between px-4 py-2.5 bg-surface-secondary">
                                    <div className="flex items-center gap-2">
                                      <span className="px-2 py-0.5 bg-white border border-border rounded text-[11px] font-semibold uppercase text-text-secondary">{text.language_code}</span>
                                      <span className="text-sm font-medium text-text-primary">{text.language_label}</span>
                                    </div>
                                    <button
                                      onClick={() => setConfirmDeleteLangId(tId)}
                                      className="p-1.5 text-text-quaternary hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                    >
                                      <Trash2 className="w-3.5 h-3.5" />
                                    </button>
                                  </div>
                                  <div className="px-4 py-3 text-sm whitespace-pre-wrap text-text-primary leading-relaxed" dir={text.language_code === 'ar' ? 'rtl' : 'ltr'}>
                                    {text.content}
                                  </div>
                                </div>
                              )
                            })}
                          </div>
                        ) : (
                          <div className="text-center py-8 rounded-xl border-2 border-dashed border-border">
                            <Globe className="w-8 h-8 text-text-quaternary mx-auto mb-2" />
                            <p className="text-sm text-text-tertiary">{t('posts.noLanguages')}</p>
                            <button
                              onClick={() => setShowLanguageModal(true)}
                              className="mt-3 text-xs font-medium text-brand-primary hover:underline"
                            >
                              {t('posts.addLanguage')}
                            </button>
                          </div>
                        )}
                      </div>

                      {/* Media / Attachments for this version */}
                      <div>
                        <div className="flex items-center justify-between mb-3">
                          <div className="flex items-center gap-2">
                            <ImageIcon className="w-4 h-4 text-text-tertiary" />
                            <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wide">{t('posts.media')}</h4>
                            {versionData.attachments?.length > 0 && (
                              <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-surface-tertiary text-text-tertiary font-medium">
                                {versionData.attachments.length}
                              </span>
                            )}
                          </div>
                          <label className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-brand-primary border border-brand-primary/30 hover:bg-brand-primary/5 rounded-lg cursor-pointer transition-colors">
                            <Upload className="w-3 h-3" />
                            {uploadingVersionFile ? t('posts.uploading') : t('posts.addImage')}
                            <input
                              ref={versionFileInputRef}
                              type="file"
                              multiple
                              className="hidden"
                              onChange={e => { handleVersionFileUpload(e.target.files); e.target.value = '' }}
                              disabled={uploadingVersionFile}
                            />
                          </label>
                        </div>

                        {versionData.attachments && versionData.attachments.length > 0 ? (
                          <div className="grid grid-cols-2 gap-3">
                            {versionData.attachments.map(att => {
                              const attId = att.Id || att.id || att._id
                              const attUrl = att.url || `/api/uploads/${att.filename}`
                              const name = att.original_name || att.filename
                              const mime = att.mime_type || ''
                              const isImage = mime.startsWith('image/')
                              const isVideo = mime.startsWith('video/')
                              return (
                                <div key={attId} className="relative group rounded-xl border border-border overflow-hidden bg-white hover:shadow-md transition-shadow">
                                  {isImage ? (
                                    <a href={attUrl} target="_blank" rel="noopener noreferrer">
                                      <img src={attUrl} alt={name} className="w-full h-44 object-cover" />
                                    </a>
                                  ) : isVideo ? (
                                    <video src={attUrl} controls className="w-full h-44 object-cover" />
                                  ) : (
                                    <a href={attUrl} target="_blank" rel="noopener noreferrer" className="flex items-center justify-center h-44 bg-surface-tertiary">
                                      <FileText className="w-10 h-10 text-text-quaternary" />
                                    </a>
                                  )}
                                  <div className="flex items-center justify-between px-3 py-2 border-t border-border bg-surface-secondary/50">
                                    <span className="text-[11px] text-text-secondary truncate">{name}</span>
                                    <button
                                      onClick={() => setConfirmDeleteAttId(attId)}
                                      className="p-1 text-text-quaternary hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all"
                                    >
                                      <Trash2 className="w-3.5 h-3.5" />
                                    </button>
                                  </div>
                                </div>
                              )
                            })}
                          </div>
                        ) : (
                          <div className="text-center py-8 rounded-xl border-2 border-dashed border-border">
                            <ImageIcon className="w-8 h-8 text-text-quaternary mx-auto mb-2" />
                            <p className="text-sm text-text-tertiary">{t('posts.noMedia')}</p>
                          </div>
                        )}
                      </div>
                    </div>
                  ) : versions.length > 0 ? (
                    <div className="flex items-center justify-center h-40">
                      <div className="w-6 h-6 border-2 border-brand-primary border-t-transparent rounded-full animate-spin" />
                    </div>
                  ) : null}
                </div>
              </div>
            )}

            {/* ─── Platforms & Links Tab ─── */}
            {activeTab === 'platforms' && (
              <div className="p-6 space-y-6 w-full">
                <div>
                  <div className="flex items-center gap-2 mb-3">
                    <Share2 className="w-4 h-4 text-text-tertiary" />
                    <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wide">{t('posts.platforms')}</h4>
                  </div>
                  <div className="flex flex-wrap gap-2 p-3 rounded-xl bg-surface-secondary min-h-[44px]">
                    {Object.entries(PLATFORMS).map(([k, v]) => {
                      const checked = (form.platforms || []).includes(k)
                      return (
                        <label
                          key={k}
                          className={`flex items-center gap-1.5 text-xs px-3 py-2 rounded-lg cursor-pointer border transition-all ${
                            checked
                              ? 'bg-white border-brand-primary/30 text-brand-primary font-medium shadow-sm'
                              : 'bg-white/50 border-transparent text-text-secondary hover:bg-white hover:shadow-sm'
                          }`}
                        >
                          <input
                            type="checkbox"
                            checked={checked}
                            onChange={() => {
                              update('platforms', checked
                                ? form.platforms.filter(p => p !== k)
                                : [...(form.platforms || []), k]
                              )
                            }}
                            className="sr-only"
                          />
                          <span className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: v.color || '#888' }} />
                          {v.label}
                        </label>
                      )
                    })}
                  </div>
                </div>

                {(form.platforms || []).length > 0 && (
                  <div>
                    <div className="flex items-center gap-2 mb-3">
                      <Link2 className="w-4 h-4 text-text-tertiary" />
                      <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wide">{t('posts.publicationLinks')}</h4>
                    </div>
                    <div className="space-y-2.5">
                      {(form.platforms || []).map(platformKey => {
                        const platformInfo = PLATFORMS[platformKey] || { label: platformKey }
                        const existingLink = (form.publication_links || []).find(l => l.platform === platformKey)
                        const linkUrl = existingLink?.url || ''
                        return (
                          <div key={platformKey} className="flex items-center gap-3 p-3 rounded-xl bg-surface-secondary">
                            <span className="text-xs font-medium text-text-primary w-28 shrink-0 flex items-center gap-2">
                              <span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ backgroundColor: platformInfo.color || '#888' }} />
                              {platformInfo.label}
                            </span>
                            <input
                              type="url"
                              value={linkUrl}
                              onChange={e => updatePublicationLink(platformKey, e.target.value)}
                              className="flex-1 px-3 py-2 text-sm border border-border rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                              placeholder="https://..."
                            />
                            {linkUrl && (
                              <a href={linkUrl} target="_blank" rel="noopener noreferrer" className="p-2 text-text-tertiary hover:text-brand-primary hover:bg-white rounded-lg transition-colors">
                                <ExternalLink className="w-4 h-4" />
                              </a>
                            )}
                          </div>
                        )
                      })}
                    </div>
                    {form.status === 'published' && (form.platforms || []).some(p => {
                      const link = (form.publication_links || []).find(l => l.platform === p)
                      return !link || !link.url?.trim()
                    }) && (
                      <p className="text-xs text-amber-600 mt-3 flex items-center gap-1.5">
                        <XCircle className="w-3.5 h-3.5" />
                        {t('posts.publishRequired')}
                      </p>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* ─── Approval Tab ─── */}
            {activeTab === 'approval' && (
              <div className="p-6 space-y-5 w-full">
                <div className="bg-surface-secondary rounded-xl p-4">
                  <label className="block text-xs font-medium text-text-primary mb-2">{t('posts.approvers')}</label>
                  <ApproverMultiSelect
                    users={teamMembers || []}
                    selected={form.approver_ids || []}
                    onChange={ids => update('approver_ids', ids)}
                  />
                </div>

                {!isCreateMode && (
                  <div className="space-y-4">
                    {/* Approval status cards */}
                    {form.status === 'approved' && post.approved_by_name && (
                      <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4 flex items-start gap-3">
                        <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                          <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-emerald-800">{t('posts.approvedBy')} {post.approved_by_name}</p>
                          {post.feedback && <p className="text-xs text-emerald-700 mt-1.5 leading-relaxed">{post.feedback}</p>}
                        </div>
                      </div>
                    )}

                    {form.status === 'rejected' && post.approved_by_name && (
                      <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-start gap-3">
                        <div className="w-8 h-8 rounded-full bg-red-100 flex items-center justify-center shrink-0 mt-0.5">
                          <XCircle className="w-4 h-4 text-red-600" />
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-red-800">{t('posts.rejectedBy')} {post.approved_by_name}</p>
                          {post.feedback && <p className="text-xs text-red-700 mt-1.5 leading-relaxed">{post.feedback}</p>}
                        </div>
                      </div>
                    )}

                    {form.status === 'in_review' && (
                      <div className="bg-amber-50 border border-amber-200 rounded-xl p-4 text-center">
                        <div className="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center mx-auto mb-2">
                          <Clock className="w-5 h-5 text-amber-600" />
                        </div>
                        <p className="text-sm font-semibold text-amber-800">{t('posts.awaitingReview')}</p>
                        <p className="text-xs text-amber-600 mt-1">{t('posts.awaitingReviewDesc')}</p>
                      </div>
                    )}

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

                    {/* Action buttons */}
                    <div className="flex gap-3">
                      {!reviewUrl && (
                        <button
                          onClick={handleSubmitReview}
                          disabled={submittingReview}
                          className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-amber-500 text-white rounded-xl hover:bg-amber-600 transition-colors font-medium text-sm disabled:opacity-50 shadow-sm"
                        >
                          <Send className="w-4 h-4" />
                          {submittingReview ? t('posts.submitting') : t('posts.sendToReview')}
                        </button>
                      )}

                      {form.status === 'approved' && (
                        <button
                          onClick={() => handleStatusAction('scheduled')}
                          disabled={saving}
                          className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-colors font-medium text-sm disabled:opacity-50 shadow-sm"
                        >
                          {t('posts.schedule')}
                        </button>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* ─── Discussion Tab ─── */}
            {activeTab === 'discussion' && !isCreateMode && (
              <div className="p-6 w-full">
                <CommentsSection entityType="post" entityId={postId} />
              </div>
            )}
      </TabbedModal>

      {/* Delete Confirmation */}
      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(false)}
        title={t('posts.deletePost')}
        isConfirm
        danger
        confirmText={t('posts.deletePost')}
        onConfirm={confirmDelete}
      >
        {t('posts.deleteConfirm')}
      </Modal>

      {/* New Version Modal */}
      <Modal
        isOpen={showNewVersionModal}
        onClose={() => { setShowNewVersionModal(false); setNewVersionNotes(''); setCopyFromPrevious(false) }}
        title={t('posts.createNewVersion')}
        size="sm"
      >
        <div className="space-y-4">
          <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 focus:border-brand-primary resize-none"
            placeholder={t('posts.whatChanged')}
          />
          {versions.length > 0 && (
            <label className="flex items-center gap-2 text-sm text-text-secondary cursor-pointer">
              <input
                type="checkbox"
                checked={copyFromPrevious}
                onChange={e => setCopyFromPrevious(e.target.checked)}
                className="rounded border-border text-brand-primary focus:ring-brand-primary/20"
              />
              {t('posts.copyLanguages')}
            </label>
          )}
          <button
            onClick={handleCreateVersion}
            disabled={creatingVersion}
            className="w-full px-4 py-2.5 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 shadow-sm"
          >
            {creatingVersion ? t('posts.creatingVersion') : t('posts.createVersion')}
          </button>
        </div>
      </Modal>

      {/* Add Language Modal */}
      <Modal
        isOpen={showLanguageModal}
        onClose={() => { setShowLanguageModal(false); setLanguageForm({ language_code: '', language_label: '', content: '' }) }}
        title={t('posts.addLanguage')}
        size="md"
      >
        <div className="space-y-4">
          <select
            value={languageForm.language_code}
            onChange={e => {
              const lang = AVAILABLE_LANGUAGES.find(l => l.code === e.target.value)
              setLanguageForm(f => ({ ...f, language_code: e.target.value, language_label: lang?.label || 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="">{t('posts.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.toUpperCase()})</option>
              ))}
          </select>
          <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 focus:border-brand-primary resize-none"
            placeholder={t('posts.enterContent')}
            dir={languageForm.language_code === 'ar' ? 'rtl' : 'ltr'}
          />
          <button
            onClick={handleAddLanguage}
            disabled={savingLanguage || !languageForm.language_code || !languageForm.content}
            className="w-full px-4 py-2.5 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 shadow-sm"
          >
            {savingLanguage ? t('common.loading') : t('common.save')}
          </button>
        </div>
      </Modal>

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

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

  // ─── Render legacy attachments helper ──────────────────────────
  function renderAttachments() {
    const images = attachments.filter(a => (a.mime_type || a.mimeType || '').startsWith('image/'))
    const audio = attachments.filter(a => (a.mime_type || a.mimeType || '').startsWith('audio/'))
    const videos = attachments.filter(a => (a.mime_type || a.mimeType || '').startsWith('video/'))
    const others = attachments.filter(a => {
      const mime = a.mime_type || a.mimeType || ''
      return !mime.startsWith('image/') && !mime.startsWith('audio/') && !mime.startsWith('video/')
    })

    return (
      <div className="space-y-4">
        {/* Images */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-1.5 text-xs font-medium text-text-secondary">
              <ImageIcon className="w-3.5 h-3.5" />
              {t('posts.images')}
              {images.length > 0 && <span className="text-text-tertiary">({images.length})</span>}
            </div>
            <label className="flex items-center gap-1 px-2 py-1 text-[11px] font-medium text-brand-primary hover:bg-brand-primary/5 rounded cursor-pointer transition-colors">
              <Upload className="w-3 h-3" />
              {t('posts.addImage')}
              <input ref={imageInputRef} type="file" multiple accept="image/*" className="hidden"
                onChange={e => { handleFileUpload(e.target.files); e.target.value = '' }} />
            </label>
          </div>
          {images.length > 0 && (
            <div className="grid grid-cols-3 gap-2">
              {images.map(att => {
                const attUrl = att.url || `/api/uploads/${att.filename}`
                const name = att.original_name || att.originalName || att.filename
                const attId = att.id || att._id
                return (
                  <div key={attId} className="relative group/att border border-border rounded-lg overflow-hidden bg-white">
                    <div className="h-20 relative">
                      <a href={attUrl} target="_blank" rel="noopener noreferrer" className="block h-full">
                        <img src={attUrl} alt={name} className="absolute inset-0 w-full h-full object-cover" />
                      </a>
                      <button onClick={() => handleDeleteAttachment(attId)}
                        className="absolute top-1 right-1 p-1 bg-black/50 hover:bg-red-500 rounded-full text-white opacity-0 group-hover/att:opacity-100 transition-opacity"
                        title={t('common.delete')}><X className="w-2.5 h-2.5" /></button>
                    </div>
                    <div className="px-2 py-1 text-[10px] text-text-tertiary truncate border-t border-border-light">{name}</div>
                  </div>
                )
              })}
            </div>
          )}
        </div>

        {/* Audio */}
        {audio.length > 0 && (
          <div>
            <div className="flex items-center gap-1.5 text-xs font-medium text-text-secondary mb-2">
              <Music className="w-3.5 h-3.5" />
              {t('posts.audio')} <span className="text-text-tertiary">({audio.length})</span>
            </div>
            <div className="space-y-2">
              {audio.map(att => {
                const attUrl = att.url || `/api/uploads/${att.filename}`
                const name = att.original_name || att.originalName || att.filename
                const attId = att.id || att._id
                return (
                  <div key={attId} className="flex items-center gap-2 border border-border rounded-lg p-2 bg-white group/att">
                    <Music className="w-4 h-4 text-text-tertiary shrink-0" />
                    <span className="text-xs text-text-secondary truncate flex-1">{name}</span>
                    <audio src={attUrl} controls className="h-7 max-w-[160px]" />
                    <button onClick={() => handleDeleteAttachment(attId)}
                      className="p-1 text-text-tertiary hover:text-red-500 opacity-0 group-hover/att:opacity-100 transition-opacity"
                      title={t('common.delete')}><X className="w-3 h-3" /></button>
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {/* Videos */}
        {videos.length > 0 && (
          <div>
            <div className="flex items-center gap-1.5 text-xs font-medium text-text-secondary mb-2">
              <Film className="w-3.5 h-3.5" />
              {t('posts.videos')} <span className="text-text-tertiary">({videos.length})</span>
            </div>
            <div className="space-y-2">
              {videos.map(att => {
                const attUrl = att.url || `/api/uploads/${att.filename}`
                const name = att.original_name || att.originalName || att.filename
                const attId = att.id || att._id
                return (
                  <div key={attId} className="border border-border rounded-lg overflow-hidden bg-white group/att">
                    <video src={attUrl} controls className="w-full max-h-40" />
                    <div className="flex items-center justify-between px-2 py-1 border-t border-border-light">
                      <span className="text-[10px] text-text-tertiary truncate">{name}</span>
                      <button onClick={() => handleDeleteAttachment(attId)}
                        className="p-1 text-text-tertiary hover:text-red-500 opacity-0 group-hover/att:opacity-100 transition-opacity"
                        title={t('common.delete')}><X className="w-3 h-3" /></button>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {/* Other files */}
        {others.length > 0 && (
          <div>
            <div className="flex items-center gap-1.5 text-xs font-medium text-text-secondary mb-2">
              <FileText className="w-3.5 h-3.5" />
              {t('posts.otherFiles')} <span className="text-text-tertiary">({others.length})</span>
            </div>
            <div className="grid grid-cols-3 gap-2">
              {others.map(att => {
                const attUrl = att.url || `/api/uploads/${att.filename}`
                const name = att.original_name || att.originalName || att.filename
                const attId = att.id || att._id
                return (
                  <div key={attId} className="relative group/att border border-border rounded-lg overflow-hidden bg-white">
                    <a href={attUrl} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 p-3 h-16">
                      <FileText className="w-6 h-6 text-text-tertiary shrink-0" />
                      <span className="text-xs text-text-secondary truncate">{name}</span>
                    </a>
                    <button onClick={() => handleDeleteAttachment(attId)}
                      className="absolute top-1 right-1 p-1 bg-black/50 hover:bg-red-500 rounded-full text-white opacity-0 group-hover/att:opacity-100 transition-opacity"
                      title={t('common.delete')}><X className="w-2.5 h-2.5" /></button>
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {/* Drag and drop zone */}
        <div
          className={`border-2 border-dashed rounded-lg p-3 text-center cursor-pointer transition-colors ${
            dragActive ? 'border-brand-primary bg-brand-primary/5' : 'border-border hover:border-brand-primary/40'
          }`}
          onDragEnter={e => { e.preventDefault(); setDragActive(true) }}
          onDragLeave={e => { e.preventDefault(); setDragActive(false) }}
          onDragOver={e => e.preventDefault()}
          onDrop={handleDrop}
        >
          <Upload className={`w-4 h-4 text-text-tertiary mx-auto mb-1 ${uploading ? 'animate-pulse' : ''}`} />
          <p className="text-[11px] text-text-secondary">
            {dragActive ? t('posts.dropFiles') : t('posts.dragToUpload')}
          </p>
        </div>

        <button
          type="button"
          onClick={openAssetPicker}
          className="flex items-center gap-2 px-3 py-2 text-sm text-text-secondary border border-border rounded-lg hover:bg-surface-tertiary transition-colors w-full justify-center"
        >
          <FolderOpen className="w-4 h-4" />
          {t('posts.attachFromAssets')}
        </button>

        {showAssetPicker && (
          <div className="border border-border rounded-lg p-3 bg-surface-secondary">
            <div className="flex items-center justify-between mb-2">
              <p className="text-xs font-medium text-text-secondary">{t('posts.selectAssets')}</p>
              <button onClick={() => setShowAssetPicker(false)} className="p-1 text-text-tertiary hover:text-text-primary">
                <X className="w-3.5 h-3.5" />
              </button>
            </div>
            <input
              type="text"
              value={assetSearch}
              onChange={e => setAssetSearch(e.target.value)}
              placeholder={t('common.search')}
              className="w-full px-3 py-1.5 text-xs border border-border rounded-lg mb-2 focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
            />
            <div className="grid grid-cols-4 gap-2 max-h-48 overflow-y-auto">
              {availableAssets
                .filter(a => !assetSearch || (a.original_name || a.filename || '').toLowerCase().includes(assetSearch.toLowerCase()))
                .map(asset => {
                  const isImage = asset.mime_type?.startsWith('image/')
                  const assetUrl = `/api/uploads/${asset.filename}`
                  const name = asset.original_name || asset.filename
                  return (
                    <button
                      key={asset.id || asset._id}
                      onClick={() => handleAttachAsset(asset.id || asset._id)}
                      className="block w-full border border-border rounded-lg overflow-hidden bg-white hover:border-brand-primary hover:ring-2 hover:ring-brand-primary/20 transition-all text-left"
                    >
                      <div className="aspect-square relative">
                        {isImage ? (
                          <img src={assetUrl} alt={name} className="absolute inset-0 w-full h-full object-cover" />
                        ) : (
                          <div className="absolute inset-0 flex items-center justify-center bg-surface-tertiary">
                            <FileText className="w-6 h-6 text-text-tertiary" />
                          </div>
                        )}
                      </div>
                      <div className="px-1.5 py-1 text-[10px] text-text-tertiary truncate border-t border-border-light">{name}</div>
                    </button>
                  )
                })}
            </div>
            {availableAssets.filter(a => !assetSearch || (a.original_name || a.filename || '').toLowerCase().includes(assetSearch.toLowerCase())).length === 0 && (
              <p className="text-xs text-text-tertiary text-center py-4">{t('posts.noAssetsFound')}</p>
            )}
          </div>
        )}
      </div>
    )
  }
}
