import { useState, useEffect, useRef, useLayoutEffect } from 'react'
import { createPortal } from 'react-dom'
import { Save, Loader2, Plus, Sparkles, Building2, AlertTriangle, Trash2, Table2, GripVertical } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { apiClient } from '@/api/client'
import { useLanguage } from '@/contexts/LanguageContext'
import { t, sprintf } from '@/lib/i18n'

// Legacy type — kept for migration from old format
type BrandCardServiceRow = {
  name: string
  description: string
  page_post_id: number
  page_url: string
}

// --- Custom Tables data model ---
type BrandCardColumn = {
  id: string        // unique key, e.g. "col_1"
  header: string    // user-defined header, e.g. "שם המוצר"
  type: 'text' | 'page_select'
}

type BrandCardTable = {
  id: string        // unique key, e.g. "tbl_1"
  title: string     // table name, e.g. "מוצרי חלב"
  columns: BrandCardColumn[]
  rows: Array<Record<string, string | number>>
}

type BrandCardShape = {
  company_name: string
  one_liner: string
  about_summary: string
  phone: string
  whatsapp_number: string
  primary_cta_text?: string
  primary_cta_url?: string
  about_source_mode?: string
  about_source_post_id?: number
  services?: BrandCardServiceRow[]  // legacy — migrated to tables on load
  tables?: BrandCardTable[]
}

/** Generate a unique id */
let _idCounter = 0
function uid(prefix: string) {
  return `${prefix}_${Date.now()}_${++_idCounter}`
}

/** Migrate legacy services array to tables format */
function migrateServicesToTables(services: BrandCardServiceRow[]): BrandCardTable {
  return {
    id: uid('tbl'),
    title: t('Services'),
    columns: [
      { id: 'col_name', header: t('Service Name'), type: 'text' },
      { id: 'col_desc', header: t('Description'), type: 'text' },
      { id: 'col_page', header: t('Page'), type: 'page_select' },
    ],
    rows: services.map((s) => ({
      col_name: s.name || '',
      col_desc: s.description || '',
      col_page: s.page_post_id || 0,
    })),
  }
}

/** Create a new empty table with defaults */
function createEmptyTable(): BrandCardTable {
  const colA = uid('col')
  const colB = uid('col')
  return {
    id: uid('tbl'),
    title: '',
    columns: [
      { id: colA, header: '', type: 'text' },
      { id: colB, header: '', type: 'text' },
    ],
    rows: [
      { [colA]: '', [colB]: '' },
      { [colA]: '', [colB]: '' },
    ],
  }
}

type ComboItem = { id: number; title: string }

/**
 * Single-select dropdown that reuses the SAME portal + styling approach as Display Conditions.
 * Declared at module scope so its component identity stays stable across BrandCard re-renders
 * (a nested declaration would remount and lose its local state on every parent render).
 */
function ContentItemsDropdown({
  valueId,
  valueTitle,
  placeholder,
  defaultItems,
  noneLabel,
  onSelect,
}: {
  valueId: number
  valueTitle: string
  placeholder: string
  defaultItems: ComboItem[]
  noneLabel: string
  onSelect: (id: number, title: string) => void
}) {
  const dropdownRef = useRef<HTMLDivElement>(null)
  const menuRef = useRef<HTMLDivElement>(null)

  const [isDropdownOpen, setIsDropdownOpen] = useState(false)
  const [menuPos, setMenuPos] = useState<{ top: number; left: number; width: number } | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [isSearching, setIsSearching] = useState(false)
  const [items, setItems] = useState<ComboItem[]>(defaultItems)
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  const updateMenuPos = () => {
    const el = dropdownRef.current
    if (!el) return
    const rect = el.getBoundingClientRect()
    setMenuPos({
      top: rect.bottom + 4,
      left: rect.left,
      width: rect.width,
    })
  }

  useLayoutEffect(() => {
    if (!isDropdownOpen) return
    updateMenuPos()

    const onScrollOrResize = () => updateMenuPos()
    window.addEventListener('resize', onScrollOrResize)
    window.addEventListener('scroll', onScrollOrResize, true)
    return () => {
      window.removeEventListener('resize', onScrollOrResize)
      window.removeEventListener('scroll', onScrollOrResize, true)
    }
  }, [isDropdownOpen])

  // Close when clicking outside
  useEffect(() => {
    if (!isDropdownOpen) return
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node
      const clickedTrigger = dropdownRef.current && dropdownRef.current.contains(target)
      const clickedMenu = menuRef.current && menuRef.current.contains(target)
      if (!clickedTrigger && !clickedMenu) {
        setIsDropdownOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [isDropdownOpen])

  // Debounced search (same behavior as Display Conditions).
  useEffect(() => {
    if (!isDropdownOpen) return
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current)
    }

    searchTimeoutRef.current = setTimeout(async () => {
      const q = searchQuery.trim()
      if (!q) {
        setItems(defaultItems)
        setIsSearching(false)
        return
      }

      setIsSearching(true)
      try {
        const res = await apiClient.get<any>(`content-items?post_type=page&search=${encodeURIComponent(q)}`)
        const arr = Array.isArray(res?.data?.items) ? res.data.items : []
        const mapped = arr
          .map((it: any) => ({ id: Number(it.id || 0), title: String(it.title || '') }))
          .filter((x: any) => x.id > 0 && x.title)
        setItems(mapped)
      } catch {
        setItems([])
      } finally {
        setIsSearching(false)
      }
    }, 300)

    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current)
      }
    }
  }, [searchQuery, isDropdownOpen, defaultItems])

  const label = valueId ? valueTitle || `#${valueId}` : ''

  return (
    <div className="flex-1 relative" ref={dropdownRef}>
      <div
        onClick={() => setIsDropdownOpen(!isDropdownOpen)}
        className="min-h-[38px] px-2 py-1.5 text-sm rounded-lg border border-gray-200 bg-white cursor-pointer flex flex-wrap gap-1 items-center"
      >
        {label ? <span className="text-gray-900">{label}</span> : <span className="text-gray-400">{placeholder}</span>}
      </div>

      {isDropdownOpen && menuPos
        ? createPortal(
            <div
              ref={menuRef}
              className="bg-white border border-gray-200 rounded-lg shadow-lg max-h-72 overflow-hidden"
              style={{
                position: 'fixed',
                top: menuPos.top,
                left: menuPos.left,
                width: menuPos.width,
                zIndex: 1000000,
                backgroundColor: '#ffffff',
                border: '1px solid #e5e7eb',
                borderRadius: '12px',
                boxShadow: '0 10px 40px rgba(0, 0, 0, 0.15)',
                overflow: 'hidden',
                direction: 'rtl',
                fontFamily: 'inherit',
              }}
              onMouseDown={(e) => e.stopPropagation()}
            >
              <div
                className="sticky top-0 p-2 bg-white border-b"
                style={{ backgroundColor: '#ffffff', borderBottom: '1px solid #e5e7eb' }}
              >
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder={`🔍 ${t('Search')}...`}
                  className="w-full px-3 py-1.5 text-sm border border-gray-200 rounded-lg"
                  style={{
                    width: '100%',
                    border: '1px solid #e5e7eb',
                    borderRadius: '10px',
                    padding: '8px 12px',
                    fontSize: '14px',
                    outline: 'none',
                  }}
                  autoFocus
                />
              </div>

              <button
                type="button"
                onClick={() => {
                  onSelect(0, '')
                  setIsDropdownOpen(false)
                }}
                className={`w-full px-3 py-2 text-sm text-right hover:bg-gray-100 flex items-center gap-2 ${
                  valueId === 0 ? 'bg-primary-50 text-primary-700 font-medium' : ''
                }`}
                style={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  padding: '10px 12px',
                  fontSize: '14px',
                  backgroundColor: valueId === 0 ? '#eff6ff' : '#ffffff',
                  color: valueId === 0 ? '#1d4ed8' : '#111827',
                  border: 'none',
                  cursor: 'pointer',
                  textAlign: 'right',
                }}
              >
                <span className="w-4 h-4 flex items-center justify-center">{valueId === 0 && '✓'}</span>
                {noneLabel}
              </button>

              <div className="border-t border-gray-200" style={{ borderTop: '1px solid #e5e7eb' }} />

              <div className="max-h-48 overflow-y-auto" style={{ maxHeight: '260px', overflowY: 'auto' }}>
                {isSearching ? (
                  <div
                    className="px-3 py-2 text-sm text-gray-500 text-center"
                    style={{ padding: '10px 12px', fontSize: '14px', color: '#6b7280' }}
                  >
                    {t('Searching...')}
                  </div>
                ) : items.length === 0 ? (
                  <div
                    className="px-3 py-2 text-sm text-gray-500 text-center"
                    style={{ padding: '10px 12px', fontSize: '14px', color: '#6b7280' }}
                  >
                    {searchQuery ? t('No results found') : t('No items')}
                  </div>
                ) : (
                  items.map((it) => {
                    const isSelected = valueId === it.id
                    return (
                      <button
                        key={it.id}
                        type="button"
                        onClick={() => {
                          onSelect(it.id, it.title)
                          setIsDropdownOpen(false)
                        }}
                        className={`flex items-center gap-3 px-3 py-2 text-sm cursor-pointer hover:bg-gray-50 ${
                          isSelected ? 'bg-primary-50' : ''
                        }`}
                        style={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          gap: '10px',
                          padding: '10px 12px',
                          cursor: 'pointer',
                          backgroundColor: isSelected ? '#eff6ff' : '#ffffff',
                          color: '#111827',
                          borderBottom: '1px solid rgba(229,231,235,0.6)',
                          width: '100%',
                          textAlign: 'right',
                        }}
                      >
                        <span
                          className="w-4 h-4 flex items-center justify-center"
                          style={{ width: '16px', height: '16px', marginTop: '2px', color: '#1d4ed8' }}
                        >
                          {isSelected ? '✓' : ''}
                        </span>
                        <span
                          className={`flex-1 ${isSelected ? 'text-primary-700 font-medium' : ''}`}
                          style={{
                            flex: 1,
                            whiteSpace: 'normal',
                            overflowWrap: 'anywhere',
                            lineHeight: 1.35,
                          }}
                        >
                          {it.title}
                        </span>
                      </button>
                    )
                  })
                )}
              </div>
            </div>,
            document.body
          )
        : null}
    </div>
  )
}

export function BrandCard() {
  const { currentLanguage } = useLanguage()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [version, setVersion] = useState<number | null>(null)
  const [isDataLoaded, setIsDataLoaded] = useState(false)
  const [isSaving, setIsSaving] = useState(false)
  const [showSavedAnimation, setShowSavedAnimation] = useState(false)

  const [brandCard, setBrandCard] = useState<BrandCardShape>({
    company_name: '',
    one_liner: '',
    about_summary: '',
    phone: '',
    whatsapp_number: '',
    about_source_mode: 'auto',
    about_source_post_id: 0,
    tables: [],
  })

  const [pageCandidates, setPageCandidates] = useState<Array<{ post_id: number; title: string; url: string }>>([])
  const [aboutPostId, setAboutPostId] = useState<number>(0)

  const [autofillLoading, setAutofillLoading] = useState(false)
  const [tableAutofillLoading, setTableAutofillLoading] = useState<Record<string, boolean>>({})
  const [autofillMeta, setAutofillMeta] = useState<{ delta_chunks?: number; pages_used?: number } | null>(null)

  // Track selected page titles for page_select columns (by "tblId:rowIdx:colId")
  const [pageSelectedTitles, setPageSelectedTitles] = useState<Record<string, string>>({})

  const load = async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await apiClient.get<any>(`brand-card${currentLanguage ? `?language=${currentLanguage}` : ''}`)
      const bc = res?.data?.brand_card || {}
      const ver = typeof res?.data?.version === 'number' ? res.data.version : null
      setVersion(ver)
      // Migrate legacy services to tables if needed
      let tables: BrandCardTable[] = Array.isArray(bc.tables) ? bc.tables : []
      if (tables.length === 0 && Array.isArray(bc.services) && bc.services.length > 0) {
        tables = [migrateServicesToTables(bc.services)]
      }

      setBrandCard({
        company_name: bc.company_name || '',
        one_liner: bc.one_liner || '',
        about_summary: bc.about_summary || '',
        phone: bc.phone || '',
        whatsapp_number: bc.whatsapp_number || '',
        primary_cta_text: bc.primary_cta_text || '',
        primary_cta_url: bc.primary_cta_url || '',
        about_source_mode: bc.about_source_mode || 'auto',
        about_source_post_id: Number(bc.about_source_post_id || 0),
        tables,
      })
      setAboutPostId(Number(bc.about_source_post_id || 0))
      setPageSelectedTitles({})
      setIsDataLoaded(true)
    } catch (e: any) {
      setError(e?.message || t('Error loading business card'))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    ;(async () => {
      await load()
      try {
        const pages = await apiClient.get<any>('brand-card/page-candidates')
        const items = Array.isArray(pages?.data?.items) ? pages.data.items : []
        setPageCandidates(items)
      } catch {
        // best-effort
      }
    })()
  }, [currentLanguage])

  const pageTitleById = (id: number): string => {
    if (!id) return ''
    const hitP = pageCandidates.find((p) => p.post_id === id)
    if (hitP?.title) return hitP.title
    return `#${id}`
  }

  // --- Table CRUD helpers ---
  const addTable = () => {
    setBrandCard((prev) => ({
      ...prev,
      tables: [...(prev.tables || []), createEmptyTable()],
    }))
  }

  const removeTable = (tblIdx: number) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      tables.splice(tblIdx, 1)
      return { ...prev, tables }
    })
  }

  const updateTableTitle = (tblIdx: number, title: string) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      tables[tblIdx] = { ...tables[tblIdx], title }
      return { ...prev, tables }
    })
  }

  const addColumn = (tblIdx: number) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      const tbl = { ...tables[tblIdx] }
      const newColId = uid('col')
      tbl.columns = [...tbl.columns, { id: newColId, header: '', type: 'text' }]
      tbl.rows = tbl.rows.map((row) => ({ ...row, [newColId]: '' }))
      tables[tblIdx] = tbl
      return { ...prev, tables }
    })
  }

  const removeColumn = (tblIdx: number, colIdx: number) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      const tbl = { ...tables[tblIdx] }
      const removedColId = tbl.columns[colIdx].id
      tbl.columns = tbl.columns.filter((_, i) => i !== colIdx)
      tbl.rows = tbl.rows.map((row) => {
        const next = { ...row }
        delete next[removedColId]
        return next
      })
      tables[tblIdx] = tbl
      return { ...prev, tables }
    })
  }

  const updateColumnHeader = (tblIdx: number, colIdx: number, header: string) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      const tbl = { ...tables[tblIdx] }
      tbl.columns = [...tbl.columns]
      tbl.columns[colIdx] = { ...tbl.columns[colIdx], header }
      tables[tblIdx] = tbl
      return { ...prev, tables }
    })
  }

  const updateColumnType = (tblIdx: number, colIdx: number, type: 'text' | 'page_select') => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      const tbl = { ...tables[tblIdx] }
      tbl.columns = [...tbl.columns]
      tbl.columns[colIdx] = { ...tbl.columns[colIdx], type }
      tables[tblIdx] = tbl
      return { ...prev, tables }
    })
  }

  const addRow = (tblIdx: number) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      const tbl = { ...tables[tblIdx] }
      const emptyRow: Record<string, string | number> = {}
      tbl.columns.forEach((col) => { emptyRow[col.id] = col.type === 'page_select' ? 0 : '' })
      tbl.rows = [...tbl.rows, emptyRow]
      tables[tblIdx] = tbl
      return { ...prev, tables }
    })
  }

  const removeRow = (tblIdx: number, rowIdx: number) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      const tbl = { ...tables[tblIdx] }
      tbl.rows = tbl.rows.filter((_, i) => i !== rowIdx)
      tables[tblIdx] = tbl
      return { ...prev, tables }
    })
  }

  const updateCell = (tblIdx: number, rowIdx: number, colId: string, value: string | number) => {
    setBrandCard((prev) => {
      const tables = [...(prev.tables || [])]
      const tbl = { ...tables[tblIdx] }
      tbl.rows = [...tbl.rows]
      tbl.rows[rowIdx] = { ...tbl.rows[rowIdx], [colId]: value }
      tables[tblIdx] = tbl
      return { ...prev, tables }
    })
  }

  const runTableAutofill = async (tblIdx: number) => {
    const tbl = (brandCard.tables || [])[tblIdx]
    if (!tbl) return

    setTableAutofillLoading((prev) => ({ ...prev, [tbl.id]: true }))
    setError(null)

    try {
      const res = await apiClient.post<any>('brand-card/table-autofill-preview', {
        table_title: tbl.title,
        columns: tbl.columns.map((c) => ({ id: c.id, header: c.header, type: c.type })),
        rows: tbl.rows,
        max_pages: 20,
      })

      const filledRows = Array.isArray(res?.data?.rows) ? res.data.rows : []
      if (filledRows.length > 0) {
        setBrandCard((prev) => {
          const tables = [...(prev.tables || [])]
          const t = { ...tables[tblIdx] }
          t.rows = filledRows.map((row: Record<string, string | number>) => {
            const sanitized: Record<string, string | number> = {}
            for (const col of t.columns) {
              sanitized[col.id] = row[col.id] !== undefined ? row[col.id] : ''
            }
            return sanitized
          })
          tables[tblIdx] = t
          return { ...prev, tables }
        })
        alert(sprintf(t('The list "%s" was auto-filled. Click "Save" to save changes.'), tbl.title || t('Untitled')))
      }
    } catch (e: any) {
      setError(e?.message || t('Error auto-filling the list'))
    } finally {
      setTableAutofillLoading((prev) => ({ ...prev, [tbl.id]: false }))
    }
  }

  const save = async () => {
    setError(null)
    setIsSaving(true)
    try {
      // Send tables (new format). The PHP endpoint accepts both services and tables.
      const { services: _legacyServices, ...rest } = brandCard
      await apiClient.post<any>(`brand-card${currentLanguage ? `?language=${currentLanguage}` : ''}`, {
        brand_card: {
          ...rest,
          one_liner: String(brandCard.one_liner || '').slice(0, 160),
          about_summary: String(brandCard.about_summary || '').slice(0, 900),
          about_source_post_id: aboutPostId || 0,
          tables: brandCard.tables || [],
        },
      })
      await load()
      setOriginalData()
      setShowSavedAnimation(true)
      setTimeout(() => setShowSavedAnimation(false), 2000)
    } catch (e: any) {
      setError(e?.message || t('Error saving business card'))
    } finally {
      setIsSaving(false)
    }
  }

  // Unsaved changes detection
  const {
    hasUnsavedChanges,
    setOriginalData,
    showModal: showUnsavedModal,
    saveError,
    modalActions,
  } = useUnsavedChanges({
    currentData: { brandCard, aboutPostId },
    onSave: async () => { await save() },
    onDiscard: (original) => {
      setBrandCard(original.brandCard)
      setAboutPostId(original.aboutPostId)
    },
    isLoaded: isDataLoaded,
  })

  const runAutofill = async () => {
    setAutofillLoading(true)
    setAutofillMeta(null)
    setError(null)
    try {
      const res = await apiClient.post<any>('brand-card/autofill-preview', {
        max_pages: 25,
      })
      const draft = res?.data?.draft || null
      if (draft) {
        // V2: Backend returns pre-built tables with IDs and page_select columns resolved.
        const backendTables: BrandCardTable[] | undefined = Array.isArray(draft.tables) && draft.tables.length > 0
          ? draft.tables.map((tbl: any) => ({
              id: String(tbl.id || uid('tbl')),
              title: String(tbl.title || ''),
              columns: Array.isArray(tbl.columns)
                ? tbl.columns.map((c: any) => ({
                    id: String(c.id || uid('col')),
                    header: String(c.header || ''),
                    type: c.type === 'page_select' ? 'page_select' : 'text',
                  }))
                : [],
              rows: Array.isArray(tbl.rows) ? tbl.rows : [],
            }))
          : undefined

        // Fallback to legacy services migration if no tables from backend
        let newTables: BrandCardTable[]
        if (backendTables && backendTables.length > 0) {
          newTables = backendTables
        } else {
          const services = Array.isArray(draft.services) ? draft.services : []
          const servicesTable: BrandCardTable = migrateServicesToTables(
            services.map((s: any) => ({
              name: String(s?.name || ''),
              description: String(s?.description || ''),
              page_post_id: Number(s?.page_post_id || 0),
              page_url: String(s?.page_url || ''),
            }))
          )
          newTables = [servicesTable]
        }

        setBrandCard((prev) => ({
          ...prev,
          company_name: draft.company_name || prev.company_name,
          one_liner: draft.one_liner || prev.one_liner,
          about_summary: draft.about_summary || prev.about_summary,
          phone: draft.phone || prev.phone,
          whatsapp_number: draft.whatsapp_number || prev.whatsapp_number,
          tables: newTables,
        }))
        if (typeof draft.about_source_post_id === 'number' && draft.about_source_post_id > 0) {
          setAboutPostId(Number(draft.about_source_post_id))
        }
        const tableCount = newTables.length
        const rowCount = newTables.reduce((sum, t) => sum + t.rows.length, 0)
        alert(sprintf(t('Auto-filled: %1$d lists with %2$d rows. Click "Save" to save changes.'), tableCount, rowCount))
      }
      setAutofillMeta({ delta_chunks: res?.data?.delta_chunks, pages_used: res?.data?.pages_used })
    } catch (e: any) {
      setError(e?.message || t('Error creating auto-fill draft'))
    } finally {
      setAutofillLoading(false)
    }
  }

  return (
    <div className="space-y-6" data-wizard-id="brand-card-content">
      {/* Unsaved Changes Modal */}
      <UnsavedChangesModal
        isOpen={showUnsavedModal}
        onCancel={modalActions.onCancel}
        onDiscard={modalActions.onDiscard}
        onSave={modalActions.onSave}
        onSaveAlways={modalActions.onSaveAlways}
        isSaving={isSaving}
        errorMessage={saveError}
      />

      {/* Unsaved changes indicator */}
      {hasUnsavedChanges && (
        <div className="fixed bottom-4 left-4 bg-amber-100 text-amber-800 px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 text-sm z-40">
          <AlertTriangle className="w-4 h-4" />
          {t('You have unsaved changes')}
        </div>
      )}

      <PageHeader 
        title={t('Business Card')} 
        subtitle={t('Business details, services and contact info - used by AI to build tailored responses')}
      />

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Building2 className="w-5 h-5" />
            {t('Business Card + Information Lists')}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {error && <div className="bg-red-50 border border-red-200 text-red-800 rounded-lg p-3 text-sm">{error}</div>}

          <div className="p-3 bg-blue-50 rounded-lg text-sm text-blue-800 border border-blue-200">
            <p className="font-medium mb-1">{t('Why is this important?')}</p>
            <p>{t('A detailed business card significantly improves AI response accuracy. The more information you add, the more accurate and relevant the responses will be. Long content may slightly affect costs.')}</p>
            {version !== null && <p className="mt-1 text-xs text-blue-700">Version: {version}</p>}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('Company Name')}</label>
              <input
                type="text"
                value={String(brandCard.company_name || '')}
                onChange={(e) => setBrandCard((prev) => ({ ...prev, company_name: e.target.value }))}
                disabled={loading}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500 disabled:bg-gray-100"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {t('Short Tagline')} <span className="text-xs text-gray-500">({String(brandCard.one_liner || '').length}/160)</span>
              </label>
              <input
                type="text"
                value={String(brandCard.one_liner || '')}
                onChange={(e) => setBrandCard((prev) => ({ ...prev, one_liner: e.target.value.slice(0, 160) }))}
                disabled={loading}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500 disabled:bg-gray-100"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {t('About (Summary)')} <span className="text-xs text-gray-500">({String(brandCard.about_summary || '').length}/900)</span>
            </label>
            <textarea
              rows={4}
              value={String(brandCard.about_summary || '')}
              onChange={(e) => setBrandCard((prev) => ({ ...prev, about_summary: e.target.value.slice(0, 900) }))}
              disabled={loading}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500 disabled:bg-gray-100 resize-none"
            />
          </div>

          <div className="border rounded-lg p-3 bg-gray-50">
            <div className="text-sm font-medium text-gray-800 mb-2">{t('Contact Details')}</div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t('Phone')}</label>
                <input
                  type="text"
                  value={String(brandCard.phone || '')}
                  onChange={(e) => setBrandCard((prev) => ({ ...prev, phone: e.target.value }))}
                  disabled={loading}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500 disabled:bg-gray-100"
                  placeholder={t('e.g.: 03-1234567')}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t('WhatsApp Number')}</label>
                <input
                  type="text"
                  value={String(brandCard.whatsapp_number || '')}
                  onChange={(e) => setBrandCard((prev) => ({ ...prev, whatsapp_number: e.target.value }))}
                  disabled={loading}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500 disabled:bg-gray-100"
                  placeholder={t('e.g.: 972501234567')}
                />
              </div>
            </div>
          </div>

          <div className="border-t pt-4 space-y-3">
            <div className="flex flex-wrap gap-2 items-end">
              <div className="flex gap-2">
                <Button type="button" onClick={runAutofill} disabled={autofillLoading || loading} className="flex items-center gap-2">
                  {autofillLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
                  {t('Auto-fill with AI (company + services)')}
                </Button>
                <button
                  type="button"
                  onClick={save}
                  disabled={loading || isSaving}
                  className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                    showSavedAnimation
                      ? 'bg-green-500 hover:bg-green-600'
                      : hasUnsavedChanges
                        ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                        : 'bg-primary-600 hover:bg-primary-700'
                  } text-white`}
                >
                  {isSaving ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  {isSaving ? t('Saving...') : showSavedAnimation ? t('Saved! ✓') : hasUnsavedChanges ? t('Save Changes') : t('Save')}
                </button>
              </div>
            </div>

            {autofillMeta?.delta_chunks ? (
              <div className="text-xs text-gray-600">
                {sprintf(t('Auto-fill: consumed %1$d BoostCoin • scanned %2$d pages'), autofillMeta.delta_chunks, autofillMeta.pages_used ?? '?')}
              </div>
            ) : null}

            {/* === Custom Tables === */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 text-sm font-medium text-gray-800">
                  <Table2 className="w-4 h-4" />
                  {t('Business Information Lists')}
                </div>
                <Button type="button" variant="outline" onClick={addTable} className="flex items-center gap-2 text-sm">
                  <Plus className="w-4 h-4" />
                  {t('Add New List')}
                </Button>
              </div>

              {(brandCard.tables || []).length === 0 && (
                <div className="text-center py-8 bg-gray-50 rounded-lg border border-dashed border-gray-300">
                  <Table2 className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                  <p className="text-sm text-gray-500 mb-1">{t('No lists yet')}</p>
                  <p className="text-xs text-gray-400 mb-3">{t('Add information lists such as services, products, operating hours and more')}</p>
                  <Button type="button" variant="outline" onClick={addTable} className="flex items-center gap-2 mx-auto text-sm">
                    <Plus className="w-4 h-4" />
                    {t('Add First List')}
                  </Button>
                </div>
              )}

              {(brandCard.tables || []).map((tbl, tblIdx) => (
                <div key={tbl.id} className="border border-gray-200 rounded-lg overflow-hidden">
                  {/* Table header */}
                  <div className="bg-gray-50 px-4 py-3 flex items-center gap-3">
                    <GripVertical className="w-4 h-4 text-gray-400 flex-shrink-0" />
                    <input
                      type="text"
                      value={tbl.title}
                      onChange={(e) => updateTableTitle(tblIdx, e.target.value)}
                      placeholder={t('e.g.: Company department availability hours')}
                      className="flex-1 bg-transparent border-none text-sm font-medium text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-0"
                    />
                    <button
                      type="button"
                      onClick={() => runTableAutofill(tblIdx)}
                      disabled={!!tableAutofillLoading[tbl.id]}
                      className="p-1.5 text-primary-500 hover:text-primary-700 hover:bg-primary-50 rounded-lg transition-colors disabled:opacity-50"
                      title={t('Auto-fill with AI (empty cells only)')}
                    >
                      {tableAutofillLoading[tbl.id] ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
                    </button>
                    <button
                      type="button"
                      onClick={() => removeTable(tblIdx)}
                      className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                      title={t('Delete list')}
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>

                  <div className="p-3 overflow-x-auto">
                    <table className="w-full text-sm">
                      {/* Column headers row */}
                      <thead>
                        <tr className="border-b border-gray-200">
                          {tbl.columns.map((col, colIdx) => (
                            <th key={col.id} className="px-2 py-2 text-right">
                              <div className="space-y-1">
                                <input
                                  type="text"
                                  value={col.header}
                                  onChange={(e) => updateColumnHeader(tblIdx, colIdx, e.target.value)}
                                  placeholder={colIdx === 0 ? t('e.g.: Development Dept') : t('e.g.: Operating hours')}
                                  className="w-full border border-gray-200 rounded px-2 py-1 text-xs font-medium bg-gray-50 focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
                                />
                                <div className="flex items-center gap-1">
                                  <select
                                    value={col.type}
                                    onChange={(e) => updateColumnType(tblIdx, colIdx, e.target.value as 'text' | 'page_select')}
                                    className="text-[10px] border border-gray-200 rounded px-1 py-0.5 bg-white text-gray-500"
                                  >
                                    <option value="text">{t('Text')}</option>
                                    <option value="page_select">{t('Page Select')}</option>
                                  </select>
                                  {tbl.columns.length > 1 && (
                                    <button
                                      type="button"
                                      onClick={() => removeColumn(tblIdx, colIdx)}
                                      className="text-[10px] text-red-400 hover:text-red-600 px-1"
                                      title={t('Delete column')}
                                    >
                                      ✕
                                    </button>
                                  )}
                                </div>
                              </div>
                            </th>
                          ))}
                          <th className="px-2 py-2 w-20">
                            <button
                              type="button"
                              onClick={() => addColumn(tblIdx)}
                              className="text-xs text-primary-600 hover:text-primary-700 hover:bg-primary-50 rounded px-2 py-1 transition-colors whitespace-nowrap"
                            >
                              + {t('Column')}
                            </button>
                          </th>
                        </tr>
                      </thead>

                      {/* Data rows */}
                      <tbody>
                        {tbl.rows.map((row, rowIdx) => (
                          <tr key={rowIdx} className="border-b border-gray-100 last:border-b-0">
                            {tbl.columns.map((col) => (
                              <td key={col.id} className="px-2 py-1.5">
                                {col.type === 'page_select' ? (
                                  <ContentItemsDropdown
                                    valueId={Number(row[col.id] || 0)}
                                    valueTitle={pageSelectedTitles[`${tbl.id}:${rowIdx}:${col.id}`] || pageTitleById(Number(row[col.id] || 0))}
                                    placeholder={t('Select page')}
                                    defaultItems={pageCandidates.map((p) => ({ id: p.post_id, title: p.title }))}
                                    noneLabel={t('No page')}
                                    onSelect={(id, title) => {
                                      setPageSelectedTitles((prev) => ({ ...prev, [`${tbl.id}:${rowIdx}:${col.id}`]: title }))
                                      updateCell(tblIdx, rowIdx, col.id, id || 0)
                                    }}
                                  />
                                ) : (
                                  <input
                                    type="text"
                                    value={String(row[col.id] || '')}
                                    onChange={(e) => updateCell(tblIdx, rowIdx, col.id, e.target.value)}
                                    className="w-full border border-gray-200 rounded px-2 py-1.5 text-sm focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
                                  />
                                )}
                              </td>
                            ))}
                            <td className="px-2 py-1.5 w-20">
                              <button
                                type="button"
                                onClick={() => removeRow(tblIdx, rowIdx)}
                                className="text-xs text-red-400 hover:text-red-600 px-2 py-1 rounded hover:bg-red-50 transition-colors"
                                title={t('Delete row')}
                              >
                                <Trash2 className="w-3.5 h-3.5" />
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>

                    {/* Add row button */}
                    <div className="mt-2 pt-2 border-t border-gray-100">
                      <button
                        type="button"
                        onClick={() => addRow(tblIdx)}
                        className="text-xs text-primary-600 hover:text-primary-700 hover:bg-primary-50 rounded px-3 py-1.5 transition-colors flex items-center gap-1"
                      >
                        <Plus className="w-3.5 h-3.5" />
                        {t('Add Row')}
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
