import { useState, useEffect, useCallback } from 'react'

const API = '/api'

function useFetch(url) {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)
  const reload = useCallback(() => {
    setLoading(true)
    fetch(url).then(r => r.json()).then(d => { setData(d); setLoading(false) })
      .catch(() => setLoading(false))
  }, [url])
  useEffect(() => { reload() }, [reload])
  return { data, loading, reload }
}

// --- Icon helper ---
function Icon({ name, className = '' }) {
  return <span className={`material-symbols-outlined ${className}`}>{name}</span>
}

// --- Stats Cards ---
function StatsBar() {
  const { data } = useFetch(`${API}/stats`)
  if (!data) return null
  const items = [
    { label: 'הרחבות פעילות', value: data.total_extensions, icon: 'extension', color: 'blue' },
    { label: 'לקוחות', value: data.total_customers, icon: 'group', color: 'slate' },
    { label: 'רישיונות', value: data.total_licenses, icon: 'key', color: 'slate' },
    { label: 'פריסות מוצלחות', value: data.successful_deploys, icon: 'check_circle', color: 'emerald', border: true },
    { label: 'כשלונות', value: data.failed_deploys, icon: 'error', color: 'red', border: true },
  ]
  return (
    <section className="grid grid-cols-1 md:grid-cols-5 gap-6">
      {items.map(s => (
        <div key={s.label} className={`bg-white p-6 rounded-xl flex flex-col justify-between text-right
          hover:bg-${s.color}-50/30 transition-colors ${s.border ? `border-b-4 border-${s.color}-500/20` : ''}`}>
          <div className="flex justify-between items-start mb-4">
            <div className={`w-10 h-10 rounded-xl bg-${s.color}-100 flex items-center justify-center text-${s.color}-700`}>
              <Icon name={s.icon} />
            </div>
          </div>
          <div>
            <h3 className={`text-3xl font-black ${s.color === 'red' ? 'text-red-600' : 'text-slate-900'}`}>{s.value}</h3>
            <p className={`text-sm mt-1 ${s.color === 'emerald' ? 'text-emerald-600 font-medium' : s.color === 'red' ? 'text-red-600/70 font-bold' : 'text-slate-500'}`}>{s.label}</p>
          </div>
        </div>
      ))}
    </section>
  )
}

// --- Extensions Table ---
function ExtensionsTab() {
  const { data: extensions } = useFetch(`${API}/extensions`)
  if (!extensions) return <Loader />
  return (
    <section className="bg-white rounded-xl overflow-hidden">
      <div className="p-8 flex justify-between items-center">
        <div className="text-right">
          <h2 className="text-xl font-black text-slate-900">רשימת הרחבות</h2>
          <p className="text-sm text-slate-500 mt-1">כל ההרחבות הזמינות במערכת</p>
        </div>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-right border-collapse">
          <thead>
            <tr className="bg-slate-50/50">
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">שם ההרחבה</th>
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">Composer</th>
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">גרסה אחרונה</th>
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">לקוחות</th>
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">גרסאות</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50">
            {extensions.map(e => (
              <tr key={e.id} className="hover:bg-slate-50/80 transition-all">
                <td className="px-8 py-5">
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center text-blue-700">
                      <Icon name="extension" className="text-base" />
                    </div>
                    <span className="font-bold text-slate-900">{e.name}</span>
                  </div>
                </td>
                <td className="px-8 py-5">
                  <span className="font-mono text-xs bg-slate-100 px-2 py-1 rounded text-slate-600" dir="ltr">{e.composer_name}</span>
                </td>
                <td className="px-8 py-5">
                  <VersionBadge>{e.latest_version || '—'}</VersionBadge>
                </td>
                <td className="px-8 py-5 text-slate-500 font-medium">{e.customer_count}</td>
                <td className="px-8 py-5 text-slate-500 font-medium">{e.version_count}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  )
}

// --- Customers Tab ---
function CustomersTab() {
  const { data: customers, reload } = useFetch(`${API}/customers`)
  const [selected, setSelected] = useState(null)
  const [showForm, setShowForm] = useState(false)

  const deleteCustomer = async (id) => {
    await fetch(`${API}/customers/${id}`, { method: 'DELETE' })
    if (selected === id) setSelected(null)
    reload()
  }

  if (!customers) return <Loader />
  return (
    <div className="flex gap-6">
      <div className="w-80 shrink-0">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-lg font-black text-slate-900">לקוחות ({customers.length})</h3>
          <button onClick={() => setShowForm(!showForm)}
            className="deep-action-gradient text-white px-4 py-2 rounded-xl font-bold text-sm flex items-center gap-2 shadow-lg shadow-blue-500/20 active:scale-95 transition-all">
            <Icon name="add" className="text-sm" />
            <span>חדש</span>
          </button>
        </div>
        {showForm && <CustomerForm onDone={() => { setShowForm(false); reload() }} onCancel={() => setShowForm(false)} />}
        <div className="space-y-2">
          {customers.map(c => (
            <div key={c.id} onClick={() => setSelected(c.id)}
              className={`bg-white p-4 rounded-xl cursor-pointer transition-all ${selected === c.id ? 'ring-2 ring-blue-500 bg-blue-50/30' : 'hover:bg-slate-50'}`}>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-slate-100 flex items-center justify-center text-slate-600">
                  <Icon name="domain" />
                </div>
                <div className="text-right flex-1">
                  <p className="font-bold text-slate-900">{c.name}</p>
                  <p className="text-xs text-slate-500 mt-0.5" dir="ltr">{c.espocrm_url}</p>
                </div>
              </div>
              <div className="flex items-center gap-3 mt-3 text-xs text-slate-400">
                <span>{c.installed_count || 0}/{c.extension_count} מותקנות</span>
                <span>•</span>
                <span className={c.is_active ? 'text-emerald-600' : 'text-red-500'}>{c.is_active ? 'פעיל' : 'לא פעיל'}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="flex-1 min-w-0">
        {selected ? <CustomerDetail customerId={selected} onDelete={() => deleteCustomer(selected)} /> : (
          <div className="bg-white rounded-xl p-12 text-center text-slate-400">
            <Icon name="touch_app" className="text-5xl mb-4 block" />
            <p className="font-medium">בחר לקוח מהרשימה</p>
          </div>
        )}
      </div>
    </div>
  )
}

function CustomerForm({ onDone, onCancel, customer }) {
  const isEdit = !!customer
  const [form, setForm] = useState({
    name: customer?.name || '', email: customer?.email || '',
    espocrm_url: customer?.espocrm_url || '', espocrm_api_key: ''
  })
  const [authUser, setAuthUser] = useState('')
  const [authPass, setAuthPass] = useState('')

  const updateAuthFromCredentials = (user, pass) => {
    setAuthUser(user)
    setAuthPass(pass)
    if (user && pass) {
      setForm(f => ({ ...f, espocrm_api_key: btoa(user + ':' + pass) }))
    } else {
      setForm(f => ({ ...f, espocrm_api_key: '' }))
    }
  }

  const [error, setError] = useState('')

  const submit = async () => {
    if (!form.name.trim()) { setError('שם לקוח הוא שדה חובה'); return }
    if (!form.espocrm_url.trim()) { setError('EspoCRM URL הוא שדה חובה'); return }
    if (!isEdit && !form.espocrm_api_key) { setError('יש להזין שם משתמש וסיסמה'); return }
    setError('')
    const payload = { ...form }
    if (!payload.espocrm_api_key) delete payload.espocrm_api_key
    const url = isEdit ? `${API}/customers/${customer.id}` : `${API}/customers`
    await fetch(url, {
      method: isEdit ? 'PUT' : 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    })
    onDone()
  }
  const inputClass = "w-full bg-slate-50 border-none rounded-xl px-4 py-2.5 text-sm focus:ring-2 focus:ring-blue-500"
  return (
    <div className="bg-white rounded-xl p-5 mb-4 space-y-3">
      <input placeholder="שם לקוח" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })}
        className={`${inputClass} text-right`} />
      <input placeholder="אימייל" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })}
        className={inputClass} dir="ltr" />
      <input placeholder="EspoCRM URL" value={form.espocrm_url} onChange={e => setForm({ ...form, espocrm_url: e.target.value })}
        className={inputClass} dir="ltr" />
      <div className="bg-slate-100/60 rounded-xl p-4 space-y-3">
        <div className="flex items-center gap-2 justify-end">
          <p className="text-xs font-bold text-slate-500">פרטי התחברות ל-EspoCRM</p>
          <Icon name="key" className="text-sm text-slate-400" />
        </div>
        <div className="grid grid-cols-2 gap-3" dir="ltr">
          <input placeholder="Username" value={authUser}
            onChange={e => updateAuthFromCredentials(e.target.value, authPass)}
            className="bg-white border border-slate-200 rounded-xl px-4 py-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
          <input placeholder="Password" value={authPass} type="password"
            onChange={e => updateAuthFromCredentials(authUser, e.target.value)}
            className="bg-white border border-slate-200 rounded-xl px-4 py-2.5 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
        </div>
        {form.espocrm_api_key && (
          <div className="bg-white rounded-lg px-3 py-2 border border-slate-200/60">
            <p className="text-[10px] text-slate-400 font-mono truncate" dir="ltr">
              Espo-Authorization: {form.espocrm_api_key}
            </p>
          </div>
        )}
        {isEdit && !form.espocrm_api_key && (
          <p className="text-[10px] text-slate-400 text-right">השאר ריק כדי לא לשנות</p>
        )}
      </div>
      {error && <p className="text-xs text-red-600 font-bold text-right">{error}</p>}
      <div className="flex gap-2">
        <button onClick={submit}
          className="deep-action-gradient text-white px-4 py-2.5 rounded-xl font-bold flex-1 shadow-lg shadow-blue-500/20 active:scale-95 transition-all">
          {isEdit ? 'עדכון' : 'שמור'}
        </button>
        <button onClick={onCancel}
          className="px-4 py-2.5 rounded-xl font-bold text-slate-500 hover:bg-slate-100 transition-all">
          ביטול
        </button>
      </div>
    </div>
  )
}

function CustomerDetail({ customerId, onDelete }) {
  const { data: customer, reload } = useFetch(`${API}/customers/${customerId}`)
  const { data: allExtensions } = useFetch(`${API}/extensions`)
  const [deploying, setDeploying] = useState(null)
  const [deployResult, setDeployResult] = useState(null)
  const [editing, setEditing] = useState(false)
  const [selected, setSelected] = useState(new Set())
  const [batchDeploying, setBatchDeploying] = useState(false)
  const [batchProgress, setBatchProgress] = useState({ current: 0, total: 0, module: '' })
  const [syncing, setSyncing] = useState(false)

  const syncAndReload = async () => {
    setSyncing(true)
    setDeployResult(null)
    try {
      const r = await fetch('/sync', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ customer_id: customerId })
      })
      const result = await r.json()
      const custResult = result.results?.find(r => r.customer_id === customerId || r.status === 'error')
      if (custResult?.status === 'error') {
        setDeployResult({ module: 'סנכרון', status: 'error', message: custResult.message })
      }
    } catch (e) {
      setDeployResult({ module: 'סנכרון', status: 'error', message: `שגיאת רשת: ${e.message}` })
    }
    reload()
    setSyncing(false)
  }

  if (!customer) return <Loader />

  const assignedIds = new Set((customer.extensions || []).map(e => e.id))
  const available = (allExtensions || []).filter(e => !assignedIds.has(e.id))
  const order = customer.install_order || []
  const deps = customer.dependencies || {}
  const exts = customer.extensions || []
  const installedNames = new Set(exts.filter(e => e.installed_version).map(e => e.name))

  const sorted = [...exts].sort((a, b) => {
    const aInstalled = a.installed_version ? 0 : 1
    const bInstalled = b.installed_version ? 0 : 1
    if (aInstalled !== bInstalled) return aInstalled - bInstalled
    const ia = order.indexOf(a.name)
    const ib = order.indexOf(b.name)
    return (ia === -1 ? 999 : ia) - (ib === -1 ? 999 : ib)
  })

  const toggleSelect = (id) => {
    setSelected(prev => {
      const next = new Set(prev)
      next.has(id) ? next.delete(id) : next.add(id)
      return next
    })
  }

  const selectAll = () => {
    const installable = sorted.filter(e => {
      if (e.installed_version) return false
      const missing = (deps[e.name] || []).filter(d => !installedNames.has(d))
      return missing.length === 0
    })
    setSelected(new Set(installable.map(e => e.id)))
  }

  const deploy = async (module, version) => {
    setDeploying(module)
    setDeployResult(null)
    try {
      const r = await fetch(`${API}/deploy`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ customer_id: customerId, module, version })
      })
      const result = await r.json()
      setDeployResult({ module, ...result })
      reload()
    } catch (e) {
      setDeployResult({ module, status: 'error', message: e.message })
    }
    setDeploying(null)
  }

  const batchDeploy = async () => {
    const toDeploy = sorted.filter(e => selected.has(e.id) && !e.installed_version && e.latest_version)
    setBatchDeploying(true)
    setBatchProgress({ current: 0, total: toDeploy.length, module: '' })
    const results = []
    for (let i = 0; i < toDeploy.length; i++) {
      const e = toDeploy[i]
      setBatchProgress({ current: i + 1, total: toDeploy.length, module: e.name })
      try {
        const r = await fetch(`${API}/deploy`, {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ customer_id: customerId, module: e.name, version: e.latest_version })
        })
        const result = await r.json()
        results.push({ module: e.name, ...result })
      } catch (err) {
        results.push({ module: e.name, status: 'error', message: err.message })
      }
    }
    const ok = results.filter(r => r.status === 'ok').length
    const fail = results.filter(r => r.status !== 'ok').length
    setDeployResult({ module: `${ok} הרחבות`, status: fail === 0 ? 'ok' : 'error',
      message: fail > 0 ? `${ok} הצליחו, ${fail} נכשלו` : undefined })
    setBatchDeploying(false)
    setSelected(new Set())
    reload()
  }

  const remove = async (extId) => {
    await fetch(`${API}/customers/${customerId}/extensions/${extId}`, { method: 'DELETE' })
    reload()
  }

  const assign = async (extId) => {
    await fetch(`${API}/customers/${customerId}/extensions`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ extension_id: extId })
    })
    reload()
  }

  return (
    <div>
      {editing ? (
        <CustomerForm customer={customer} onDone={() => { setEditing(false); reload() }} onCancel={() => setEditing(false)} />
      ) : (
        <div className="flex items-center gap-4 mb-6">
          <div className="w-12 h-12 rounded-xl bg-blue-100 flex items-center justify-center text-blue-700">
            <Icon name="domain" className="text-2xl" />
          </div>
          <div className="text-right flex-1">
            <h3 className="text-xl font-black text-slate-900">{customer.name}</h3>
            <p className="text-sm text-slate-500" dir="ltr">{customer.espocrm_url}</p>
          </div>
          <button onClick={syncAndReload} disabled={syncing}
            className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all disabled:opacity-50"
            title="סנכרון מול השרת">
            <Icon name="sync" className={`text-lg ${syncing ? 'animate-spin' : ''}`} />
          </button>
          <button onClick={() => setEditing(true)}
            className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all"
            title="עריכת לקוח">
            <Icon name="edit" className="text-lg" />
          </button>
          <button onClick={() => { if (confirm('למחוק את הלקוח לצמיתות?')) onDelete() }}
            className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
            title="מחיקת לקוח">
            <Icon name="delete" className="text-lg" />
          </button>
        </div>
      )}

      {deployResult && (
        <div className={`p-4 rounded-xl mb-6 text-sm font-medium ${deployResult.status === 'ok' ? 'bg-emerald-50 text-emerald-800' : 'bg-red-50 text-red-800'}`}>
          <div className="flex items-center gap-3">
            <Icon name={deployResult.status === 'ok' ? 'check_circle' : 'error'} />
            <span className="font-bold">{deployResult.module}: {deployResult.status === 'ok' ? 'הותקן בהצלחה!' : 'נכשל'}</span>
          </div>
          {deployResult.status !== 'ok' && deployResult.message && (
            <div className="mt-2 mr-8 text-xs space-y-1">
              <div>{deployResult.message}</div>
              {deployResult.step && <div className="text-red-400">שלב: {({find_release:'חיפוש גרסה',find_zip:'חיפוש קובץ ZIP',download_zip:'הורדת ZIP',upload:'העלאה ל-EspoCRM',install:'התקנה',rebuild:'בנייה מחדש'})[deployResult.step] || deployResult.step}</div>}
              {deployResult.code && <div className="text-red-400">קוד שגיאה: {deployResult.code}{deployResult.code === 401 ? ' (שם משתמש/סיסמה שגויים)' : deployResult.code === 403 ? ' (אין הרשאה)' : deployResult.code === 404 ? ' (לא נמצא)' : deployResult.code === 500 ? ' (שגיאת שרת)' : ''}</div>}
            </div>
          )}
        </div>
      )}

      {batchDeploying && (
        <div className="p-4 rounded-xl mb-6 bg-blue-50 text-blue-800 text-sm font-medium flex items-center gap-3">
          <Icon name="sync" className="text-base animate-spin" />
          מתקין {batchProgress.current}/{batchProgress.total}: {batchProgress.module}...
        </div>
      )}

      <section className="bg-white rounded-xl overflow-hidden">
        <div className="p-6 flex justify-between items-center">
          <div className="flex items-center gap-3">
            <h4 className="font-bold text-slate-900">הרחבות מורשות</h4>
            {selected.size > 0 && (
              <button onClick={batchDeploy} disabled={batchDeploying}
                className="deep-action-gradient text-white px-5 py-1.5 rounded-lg text-xs font-bold shadow-sm active:scale-95 transition-all disabled:opacity-50">
                {batchDeploying ? `מתקין ${batchProgress.current}/${batchProgress.total}...` : `התקן ${selected.size} הרחבות`}
              </button>
            )}
          </div>
          <div className="flex items-center gap-3">
            {sorted.some(e => !e.installed_version && (deps[e.name] || []).every(d => installedNames.has(d))) && (
              <button onClick={selectAll}
                className="text-xs text-blue-600 hover:text-blue-800 font-medium">
                בחר הכל
              </button>
            )}
            <span className="text-xs font-bold text-slate-400 uppercase tracking-widest">{exts.length} הרחבות</span>
          </div>
        </div>
        <table className="w-full text-right border-collapse">
          <thead>
            <tr className="bg-slate-50/50">
              <th className="px-3 py-4 w-10"></th>
              <th className="px-4 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">שם ההרחבה</th>
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">מותקנת</th>
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">עדכון זמין</th>
              <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest text-center">פעולות</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50">
            {sorted.map(e => {
              const installed = e.installed_version
              const semverGt = (a, b) => { const pa = a.split('.').map(Number), pb = b.split('.').map(Number); for (let i = 0; i < Math.max(pa.length, pb.length); i++) { if ((pa[i]||0) > (pb[i]||0)) return true; if ((pa[i]||0) < (pb[i]||0)) return false; } return false }
              const hasUpdate = installed && e.latest_version && semverGt(e.latest_version, installed)
              const missingDeps = (deps[e.name] || []).filter(d => !installedNames.has(d))
              const blocked = !installed && missingDeps.length > 0
              return (
                <tr key={e.id} className={`transition-all ${blocked ? 'opacity-40' : 'hover:bg-slate-50/80'}`}>
                  <td className="px-3 py-5 text-center">
                    {!installed && !blocked && (
                      <input type="checkbox" checked={selected.has(e.id)}
                        onChange={() => toggleSelect(e.id)} disabled={batchDeploying}
                        className="rounded border-slate-300 text-blue-600 focus:ring-blue-500 cursor-pointer" />
                    )}
                  </td>
                  <td className="px-4 py-5">
                    <div className="flex items-center gap-3">
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${installed ? 'bg-blue-50 text-blue-700' : blocked ? 'bg-slate-50 text-slate-300' : 'bg-slate-100 text-slate-400'}`}>
                        <Icon name={blocked ? 'lock' : 'extension'} className="text-base" />
                      </div>
                      <div>
                        <span className={`font-bold ${blocked ? 'text-slate-400' : 'text-slate-900'}`}>{e.name}</span>
                        {blocked && (
                          <p className="text-[10px] text-slate-400 mt-0.5">נדרש: {missingDeps.join(', ')}</p>
                        )}
                      </div>
                    </div>
                  </td>
                  <td className="px-8 py-5">
                    {installed
                      ? <VersionBadge>v{installed}</VersionBadge>
                      : <span className={`text-sm font-medium ${blocked ? 'text-slate-300' : 'text-red-500'}`}>לא מותקן</span>}
                  </td>
                  <td className="px-8 py-5">
                    {hasUpdate
                      ? <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-amber-100 text-amber-700">v{e.latest_version}</span>
                      : <span className="text-sm text-slate-300">—</span>}
                  </td>
                  <td className="px-8 py-5">
                    <div className="flex items-center justify-center gap-1">
                      {blocked ? (
                        <span className="text-xs text-slate-300">—</span>
                      ) : !installed && !e.latest_version ? (
                        <span className="text-xs text-slate-400">אין גרסה</span>
                      ) : !installed ? (
                        <button onClick={() => deploy(e.name, e.latest_version)}
                          disabled={deploying === e.name || batchDeploying}
                          className="deep-action-gradient text-white px-4 py-1.5 rounded-lg text-xs font-bold shadow-sm active:scale-95 transition-all disabled:opacity-50">
                          {deploying === e.name ? '...' : 'התקנה'}
                        </button>
                      ) : (
                        <>
                          {hasUpdate && (
                            <button onClick={() => deploy(e.name, e.latest_version)}
                              disabled={deploying === e.name || batchDeploying}
                              className="p-2 text-amber-500 hover:text-amber-700 hover:bg-amber-50 rounded-lg transition-all"
                              title="עדכון">
                              <Icon name="upgrade" className="text-lg" />
                            </button>
                          )}
                          <button onClick={() => remove(e.id)}
                            className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
                            title="הסרה">
                            <Icon name="delete" className="text-lg" />
                          </button>
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </section>

      {/* Extensions are auto-assigned on customer creation */}
    </div>
  )
}

// --- Deployments Tab ---
function DeploymentsTab() {
  const { data: deployments } = useFetch(`${API}/deployments?limit=50`)
  if (!deployments) return <Loader />
  return (
    <section className="bg-white rounded-xl overflow-hidden">
      <div className="p-8 flex justify-between items-center">
        <div className="text-right">
          <h2 className="text-xl font-black text-slate-900">לוג פריסות</h2>
          <p className="text-sm text-slate-500 mt-1">היסטוריית כל הפריסות במערכת</p>
        </div>
      </div>
      <table className="w-full text-right border-collapse">
        <thead>
          <tr className="bg-slate-50/50">
            <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">לקוח</th>
            <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">הרחבה</th>
            <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">גרסה</th>
            <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">סטטוס</th>
            <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">סוג</th>
            <th className="px-8 py-4 text-[11px] font-bold text-slate-400 uppercase tracking-widest">זמן</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-50">
          {deployments.map(d => (
            <tr key={d.id} className="hover:bg-slate-50/80 transition-all">
              <td className="px-8 py-5 font-medium text-slate-900">{d.customer_name}</td>
              <td className="px-8 py-5">
                <div className="flex items-center gap-2">
                  <div className="w-6 h-6 rounded bg-blue-50 flex items-center justify-center text-blue-700">
                    <Icon name="extension" className="text-sm" />
                  </div>
                  <span className="font-bold text-slate-900">{d.extension_name}</span>
                </div>
              </td>
              <td className="px-8 py-5"><VersionBadge>{d.version}</VersionBadge></td>
              <td className="px-8 py-5">
                <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-bold ${d.status === 'ok' ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700'}`} title={d.error_message || ''}>
                  <Icon name={d.status === 'ok' ? 'check' : 'close'} className="text-xs" />
                  {d.status === 'ok' ? 'הצלחה' : 'שגיאה'}
                </span>
                {d.status !== 'ok' && d.error_message && (
                  <div className="text-xs text-red-400 mt-1 max-w-xs truncate" title={d.error_message}>{d.error_message}</div>
                )}
              </td>
              <td className="px-8 py-5">
                <span className={`text-xs font-medium px-2 py-0.5 rounded ${d.trigger_type === 'auto' ? 'bg-blue-50 text-blue-600' : 'bg-slate-100 text-slate-600'}`}>
                  {d.trigger_type === 'auto' ? 'אוטומטי' : 'ידני'}
                </span>
              </td>
              <td className="px-8 py-5 text-sm text-slate-400 font-mono" dir="ltr">{d.started_at?.slice(0, 16).replace('T', ' ')}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  )
}

// --- Shared Components ---
function VersionBadge({ children }) {
  return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700" dir="ltr">{children}</span>
}

function Loader() {
  return <div className="text-center py-12 text-slate-400"><Icon name="hourglass_empty" className="text-3xl animate-spin" /></div>
}

// --- Main App ---
export default function App() {
  const [tab, setTab] = useState('customers')
  const tabs = [
    { id: 'extensions', label: 'הרחבות', icon: 'extension' },
    { id: 'customers', label: 'לקוחות', icon: 'group' },
    { id: 'deployments', label: 'פריסות', icon: 'analytics' },
  ]

  return (
    <div className="min-h-screen bg-[#f8f9fb] text-[#191c1e]" dir="rtl">
      <header className="glass-header sticky top-0 z-50 flex justify-between items-center w-full px-8 py-4">
        <div className="flex items-center gap-8">
          <span className="text-xl font-black text-blue-700 tracking-tight">Extension Platform</span>
          <nav className="hidden md:flex items-center gap-1">
            {tabs.map(t => (
              <button key={t.id} onClick={() => setTab(t.id)}
                className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold transition-all
                  ${tab === t.id ? 'text-blue-700 bg-blue-50' : 'text-slate-500 hover:bg-slate-100'}`}>
                <Icon name={t.icon} className="text-lg" />
                {t.label}
              </button>
            ))}
          </nav>
        </div>
      </header>
      <main className="p-8 max-w-[1400px] w-full mx-auto space-y-8">
        <StatsBar />
        {tab === 'extensions' && <ExtensionsTab />}
        {tab === 'customers' && <CustomersTab />}
        {tab === 'deployments' && <DeploymentsTab />}
      </main>
    </div>
  )
}