'use client';

import { useState, useEffect, useRef } from 'react';
import { Webhook, Plus, Trash2, CheckCircle, XCircle, Clock, ChevronDown, ChevronUp, Copy, Eye, EyeOff, X, Save, AlertCircle, Loader2, RefreshCw, AlertTriangle } from 'lucide-react';
import { listWebhooks, createWebhook, deleteWebhook, updateWebhook, listDeliveryLogs, listDeliveryAttempts, resendDeliveryAttempt, Webhook as WebhookType, DeliveryLog, DeliveryAttempt } from '@client/api/webhooks';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

const allEvents = [
  'order.created', 'order.updated', 'order.cancelled', 'order.completed',
  'booking.created', 'booking.updated', 'booking.cancelled',
  'ai.escalation', 'ai.conversation.ended',
  'customer.created', 'customer.updated',
  'staff.login', 'staff.created',
];

const deliveryStatusConfig: Record<string, { color: string; bg: string; icon: React.ReactNode }> = {
  success: { color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)', icon: <CheckCircle size={12} /> },
  failed: { color: 'hsl(0, 84%, 44%)', bg: 'hsl(0, 84%, 97%)', icon: <XCircle size={12} /> },
  pending: { color: 'hsl(38, 92%, 40%)', bg: 'hsl(38, 100%, 96%)', icon: <Clock size={12} /> },
  processing: { color: 'hsl(210, 100%, 40%)', bg: 'hsl(210, 100%, 96%)', icon: <Loader2 size={12} className="animate-spin" /> },
  succeeded: { color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)', icon: <CheckCircle size={12} /> },
  exhausted: { color: 'hsl(0, 84%, 44%)', bg: 'hsl(0, 84%, 97%)', icon: <AlertTriangle size={12} /> },
};

export default function WebhooksPage() {
  const { t } = useLanguage();
  usePageHeader(t('webhooks.title', "Webhooks"), t('webhooks.subtitle', "Configure webhook endpoints to push events to third-party systems"));
  const [webhooks, setWebhooks] = useState<WebhookType[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [showAddForm, setShowAddForm] = useState(false);
  const [revealedKeys, setRevealedKeys] = useState<Set<string>>(new Set());
  const [expandedLogs, setExpandedLogs] = useState(false);
  const [expandedAttempts, setExpandedAttempts] = useState(false);
  const [deliveryLogs, setDeliveryLogs] = useState<DeliveryLog[]>([]);
  const [deliveryAttempts, setDeliveryAttempts] = useState<DeliveryAttempt[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const [attemptsLoading, setAttemptsLoading] = useState(false);
  const [newWebhook, setNewWebhook] = useState({ url: '', events: [] as string[] });
  const [webhookErrors, setWebhookErrors] = useState<{ url?: string; events?: string }>({});
  const [webhookTouched, setWebhookTouched] = useState<Record<string, boolean>>({});
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [copiedSecret, setCopiedSecret] = useState<string | null>(null);
  const [resendingId, setResendingId] = useState<string | null>(null);
  const [filterWebhookId, setFilterWebhookId] = useState<string | null>(null);
  const retryQueueRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    setLoading(true);
    listWebhooks()
      .then(res => { setWebhooks(res.webhooks); setError(null); })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const validateUrl = (url: string) => {
    if (!url.trim()) return t('webhooks.validation.urlRequired', 'Endpoint URL is required');
    try {
      const u = new URL(url);
      if (!['http:', 'https:'].includes(u.protocol)) return t('webhooks.validation.urlProtocol', 'URL must use HTTP or HTTPS protocol');
    } catch {
      return t('webhooks.validation.urlInvalid', 'Please enter a valid URL (e.g. https://your-app.com/webhooks)');
    }
  };

  const validateEvents = (events: string[]) => {
    if (events.length === 0) return t('webhooks.validation.eventsRequired', 'Please select at least one event');
  };

  const handleUrlBlur = () => {
    setWebhookTouched(prev => ({ ...prev, url: true }));
    setWebhookErrors(prev => ({ ...prev, url: validateUrl(newWebhook.url) }));
  };

  const handleUrlChange = (url: string) => {
    setNewWebhook(prev => ({ ...prev, url }));
    if (webhookTouched.url) setWebhookErrors(prev => ({ ...prev, url: validateUrl(url) }));
  };

  const toggleEvent = (event: string) => {
    const next = newWebhook.events.includes(event)
      ? newWebhook.events.filter(e => e !== event)
      : [...newWebhook.events, event];
    setNewWebhook(prev => ({ ...prev, events: next }));
    if (webhookTouched.events) setWebhookErrors(prev => ({ ...prev, events: validateEvents(next) }));
  };

  const handleSave = async () => {
    const urlErr = validateUrl(newWebhook.url);
    const eventsErr = validateEvents(newWebhook.events);
    setWebhookErrors({ url: urlErr, events: eventsErr });
    setWebhookTouched({ url: true, events: true });
    if (urlErr || eventsErr) return;
    setSaving(true);
    try {
      const res = await createWebhook({ endpoint_url: newWebhook.url, events: newWebhook.events });
      setWebhooks(prev => [res.webhook, ...prev]);
      setShowAddForm(false);
      setNewWebhook({ url: '', events: [] });
      setWebhookErrors({});
      setWebhookTouched({});
    } catch (e) {
      setError(e instanceof Error ? e.message : t('webhooks.error.saveFailed', 'Failed to save webhook'));
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    setDeletingId(id);
    try {
      await deleteWebhook(id);
      setWebhooks(prev => prev.filter(w => w.id !== id));
    } catch (e) {
      setError(e instanceof Error ? e.message : t('webhooks.error.deleteFailed', 'Failed to delete webhook'));
    } finally {
      setDeletingId(null);
    }
  };

  const handleToggleStatus = async (id: string, currentStatus: string) => {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    try {
      const res = await updateWebhook(id, { status: newStatus });
      setWebhooks(prev => prev.map(w => w.id === id ? res.webhook : w));
    } catch (e) {
      setError(e instanceof Error ? e.message : t('webhooks.error.updateFailed', 'Failed to update webhook'));
    }
  };

  const handleToggleLogs = async () => {
    const next = !expandedLogs;
    setExpandedLogs(next);
    if (next && deliveryLogs.length === 0) {
      setLogsLoading(true);
      try {
        const res = await listDeliveryLogs();
        setDeliveryLogs(res.logs);
      } catch {
        // silently ignore
      } finally {
        setLogsLoading(false);
      }
    }
  };

  const handleToggleAttempts = async () => {
    const next = !expandedAttempts;
    setExpandedAttempts(next);
    if (next) {
      setAttemptsLoading(true);
      try {
        const res = await listDeliveryAttempts();
        setDeliveryAttempts(res.attempts);
      } catch {
        // silently ignore
      } finally {
        setAttemptsLoading(false);
      }
    }
  };

  const handleHealthBadgeClick = async (webhookId: string) => {
    setFilterWebhookId(webhookId);
    if (!expandedAttempts) {
      setExpandedAttempts(true);
      setAttemptsLoading(true);
      try {
        const res = await listDeliveryAttempts();
        setDeliveryAttempts(res.attempts);
      } catch {
        // silently ignore
      } finally {
        setAttemptsLoading(false);
      }
    }
    setTimeout(() => {
      retryQueueRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 80);
  };

  const handleResend = async (attemptId: string) => {
    setResendingId(attemptId);
    try {
      const res = await resendDeliveryAttempt(attemptId);
      setDeliveryAttempts(prev => prev.map(a => a.id === attemptId ? res.attempt : a));
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to queue resend');
    } finally {
      setResendingId(null);
    }
  };

  const copySecret = (id: string, secret: string) => {
    navigator.clipboard.writeText(secret).catch(() => {});
    setCopiedSecret(id);
    setTimeout(() => setCopiedSecret(null), 2000);
  };

  const toggleKey = (id: string) => {
    setRevealedKeys(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  };

  const activeCount = webhooks.filter(w => w.status === 'active').length;
  const totalDeliveries = webhooks.reduce((s, w) => s + (w.totalDeliveries ?? 0), 0);
  const avgSuccess = webhooks.length > 0
    ? (webhooks.reduce((s, w) => s + (w.successRate ?? 100), 0) / webhooks.length).toFixed(1)
    : '—';

  const visibleAttempts = filterWebhookId
    ? deliveryAttempts.filter(a => a.webhookId === filterWebhookId)
    : deliveryAttempts;
  const pendingAttempts = visibleAttempts.filter(a => a.status === 'pending').length;
  const exhaustedAttempts = visibleAttempts.filter(a => a.status === 'exhausted').length;
  const filterWebhook = filterWebhookId ? webhooks.find(w => w.id === filterWebhookId) : null;

  return (
    <>
      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
        {[
          { label: t('webhooks.stats.activeEndpoints', 'Active Endpoints'), value: activeCount, color: 'hsl(142, 72%, 29%)' },
          { label: t('webhooks.stats.totalEndpoints', 'Total Endpoints'), value: webhooks.length, color: 'hsl(210, 100%, 40%)' },
          { label: t('webhooks.stats.totalDeliveries', 'Total Deliveries'), value: totalDeliveries.toLocaleString(), color: 'hsl(var(--primary))' },
          { label: t('webhooks.stats.avgSuccessRate', 'Avg Success Rate'), value: `${avgSuccess}%`, color: 'hsl(var(--primary))' },
        ].map(stat => (
          <div key={stat.label} className="rounded-xl p-4" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <p className="text-xl font-bold" style={{ color: stat.color }}>{stat.value}</p>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{stat.label}</p>
          </div>
        ))}
      </div>

      {error && (
        <div className="mb-4 px-4 py-3 rounded-xl text-sm flex items-center gap-2" style={{ backgroundColor: 'hsl(var(--danger-bg))', color: 'hsl(var(--danger))', border: '1px solid hsl(var(--danger-border))' }}>
          <AlertCircle size={14} /> {error}
          <button className="ml-auto" onClick={() => setError(null)}><X size={14} /></button>
        </div>
      )}

      {/* Header actions */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.endpoints.title', 'Webhook Endpoints')}</h3>
        <button className="btn-primary text-sm" onClick={() => setShowAddForm(!showAddForm)}>
          <Plus size={15} /> {t('webhooks.endpoints.add', 'Add Endpoint')}
        </button>
      </div>

      {/* Add form */}
      {showAddForm && (
        <div className="rounded-2xl p-5 mb-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '2px solid hsl(var(--primary))' }}>
          <div className="flex items-center justify-between mb-4">
            <h4 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.addForm.title', 'New Webhook Endpoint')}</h4>
            <button onClick={() => { setShowAddForm(false); setWebhookErrors({}); setWebhookTouched({}); }}>
              <X size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />
            </button>
          </div>
          <div className="space-y-4">
            <div>
              <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('webhooks.addForm.urlLabel', 'Endpoint URL *')}</label>
              <input
                type="url"
                placeholder={t('webhooks.urlPlaceholder', 'https://your-app.com/webhooks')}
                value={newWebhook.url}
                onChange={e => handleUrlChange(e.target.value)}
                onBlur={handleUrlBlur}
                className="input-field w-full font-mono"
                style={{
                  borderColor: webhookTouched.url && webhookErrors.url ? 'hsl(0, 84%, 44%)' : undefined,
                }}
              />
              {webhookTouched.url && webhookErrors.url && (
                <p className="flex items-center gap-1 text-xs mt-1.5 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
                  <AlertCircle size={12} />{webhookErrors.url}
                </p>
              )}
            </div>
            <div>
              <label className="block text-xs font-semibold mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('webhooks.addForm.eventsLabel', 'Subscribe to Events *')}</label>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                {allEvents.map(event => (
                  <label key={event} className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={newWebhook.events.includes(event)} onChange={() => toggleEvent(event)} className="rounded" />
                    <span className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>{event}</span>
                  </label>
                ))}
              </div>
              {webhookTouched.events && webhookErrors.events && (
                <p className="flex items-center gap-1 text-xs mt-2 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
                  <AlertCircle size={12} />{webhookErrors.events}
                </p>
              )}
            </div>
            <div className="flex gap-3">
              <button className="btn-primary" onClick={handleSave} disabled={saving}>
                {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
                {t('webhooks.addForm.submit', 'Save Endpoint')}
              </button>
              <button className="btn-secondary" onClick={() => { setShowAddForm(false); setWebhookErrors({}); setWebhookTouched({}); }}>{t('common.cancel', 'Cancel')}</button>
            </div>
          </div>
        </div>
      )}

      {/* Webhooks list */}
      {loading ? (
        <div className="flex items-center justify-center py-16 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Loader2 size={20} className="animate-spin" /> {t('webhooks.loading', 'Loading webhooks…')}
        </div>
      ) : (
        <div className="space-y-3 mb-8">
          {webhooks.length === 0 ? (
            <div className="text-center py-16 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <Webhook size={32} className="mx-auto mb-3 opacity-30" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.noEndpoints.title', 'No webhook endpoints configured')}</p>
              <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('webhooks.noEndpoints.subtitle', 'Add an endpoint to start receiving event notifications')}</p>
            </div>
          ) : webhooks.map(webhook => {
            const isRevealed = revealedKeys.has(webhook.id);
            const events = Array.isArray(webhook.events) ? webhook.events : [];
            const hasPending = webhook.pendingAttempts > 0;
            const hasExhausted = webhook.exhaustedAttempts > 0;
            return (
              <div key={webhook.id} className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="flex items-start gap-4 p-4">
                  <div
                    className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0 mt-0.5 cursor-pointer"
                    title={t('webhooks.endpoints.toggleStatus', 'Click to toggle status')}
                    style={{
                      backgroundColor: webhook.status === 'active' ? 'hsl(142, 72%, 96%)' : 'hsl(220, 9%, 96%)',
                      color: webhook.status === 'active' ? 'hsl(142, 72%, 29%)' : 'hsl(220, 9%, 46%)',
                    }}
                    onClick={() => handleToggleStatus(webhook.id, webhook.status)}
                  >
                    <Webhook size={16} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1 flex-wrap">
                      <p className="text-sm font-mono font-semibold truncate" style={{ color: 'hsl(var(--foreground))' }}>{webhook.endpointUrl}</p>
                      <span
                        className="text-xs font-semibold px-2 py-0.5 rounded-full shrink-0 cursor-pointer"
                        style={{
                          backgroundColor: webhook.status === 'active' ? 'hsl(142, 72%, 96%)' : 'hsl(220, 9%, 96%)',
                          color: webhook.status === 'active' ? 'hsl(142, 72%, 29%)' : 'hsl(220, 9%, 46%)',
                        }}
                        onClick={() => handleToggleStatus(webhook.id, webhook.status)}
                      >
                        {webhook.status === 'active' ? t('common.active', 'active') : t('common.inactive', 'inactive')}
                      </span>
                      {hasPending && (
                        <button
                          className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full shrink-0 transition-opacity hover:opacity-75"
                          style={{ backgroundColor: 'hsl(38, 100%, 96%)', color: 'hsl(38, 92%, 40%)' }}
                          title={t('webhooks.health.pendingTitle', 'View pending retries in Retry Queue')}
                          onClick={() => handleHealthBadgeClick(webhook.id)}
                        >
                          <Clock size={10} />
                          {webhook.pendingAttempts} {t('webhooks.health.pending', 'pending')}
                        </button>
                      )}
                      {hasExhausted && (
                        <button
                          className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full shrink-0 transition-opacity hover:opacity-75"
                          style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)' }}
                          title={t('webhooks.health.exhaustedTitle', 'View exhausted retries in Retry Queue')}
                          onClick={() => handleHealthBadgeClick(webhook.id)}
                        >
                          <AlertTriangle size={10} />
                          {webhook.exhaustedAttempts} {t('webhooks.health.exhausted', 'exhausted')}
                        </button>
                      )}
                    </div>
                    <div className="flex flex-wrap gap-1 mb-2">
                      {events.map(e => (
                        <span key={e} className="text-xs font-mono px-1.5 py-0.5 rounded" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>{e}</span>
                      ))}
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="flex items-center gap-1.5">
                        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('webhooks.endpoints.secretLabel', 'Secret:')}</span>
                        <span className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                          {isRevealed ? webhook.secret : '••••••••••••••••'}
                        </span>
                        <button onClick={() => toggleKey(webhook.id)} className="p-0.5">
                          {isRevealed ? <EyeOff size={12} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <Eye size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                        </button>
                        <button className="p-0.5" title={t('common.copySecret', 'Copy secret')} onClick={() => copySecret(webhook.id, webhook.secret)}>
                          {copiedSecret === webhook.id
                            ? <CheckCircle size={12} style={{ color: 'hsl(142, 72%, 29%)' }} />
                            : <Copy size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                        </button>
                      </div>
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {t('webhooks.endpoints.created', 'Created')} {new Date(webhook.createdAt).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <button
                      className="p-1.5 rounded-lg hover:bg-red-50 transition-colors"
                      title={t('common.delete', 'Delete')}
                      onClick={() => handleDelete(webhook.id)}
                      disabled={deletingId === webhook.id}
                    >
                      {deletingId === webhook.id
                        ? <Loader2 size={14} className="animate-spin" style={{ color: 'hsl(var(--danger))' }} />
                        : <Trash2 size={14} style={{ color: 'hsl(var(--danger))' }} />}
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Failed / Retry Attempts */}
      {!loading && webhooks.length > 0 && (
        <div className="mb-6" ref={retryQueueRef}>
          <div className="flex items-center gap-2 mb-3">
            <button className="flex items-center gap-2 flex-1 text-left" onClick={handleToggleAttempts}>
              <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                {t('webhooks.attempts.title', 'Retry Queue')}
              </h3>
              {expandedAttempts && deliveryAttempts.length > 0 && (
                <>
                  {pendingAttempts > 0 && (
                    <span className="text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(38, 100%, 96%)', color: 'hsl(38, 92%, 40%)' }}>
                      {pendingAttempts} pending
                    </span>
                  )}
                  {exhaustedAttempts > 0 && (
                    <span className="text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)' }}>
                      {exhaustedAttempts} exhausted
                    </span>
                  )}
                </>
              )}
              {attemptsLoading && <Loader2 size={13} className="animate-spin ml-1" style={{ color: 'hsl(var(--muted-foreground))' }} />}
              <div className="ml-auto">
                {expandedAttempts ? <ChevronUp size={15} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <ChevronDown size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />}
              </div>
            </button>
            {filterWebhookId && (
              <button
                className="flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-lg shrink-0 transition-colors"
                style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}
                title={t('webhooks.attempts.clearFilter', 'Show all endpoints')}
                onClick={() => setFilterWebhookId(null)}
              >
                <X size={11} />
                {filterWebhook ? filterWebhook.endpointUrl.replace(/^https?:\/\//, '').split('/')[0] : t('webhooks.attempts.filtered', 'Filtered')}
              </button>
            )}
          </div>
          {expandedAttempts && (
            attemptsLoading ? (
              <div className="flex items-center justify-center py-8 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <Loader2 size={16} className="animate-spin" /> {t('webhooks.attempts.loading', 'Loading retry queue…')}
              </div>
            ) : visibleAttempts.length === 0 ? (
              <div className="rounded-2xl p-6 text-center" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <CheckCircle size={24} className="mx-auto mb-2" style={{ color: 'hsl(142, 72%, 29%)', opacity: 0.5 }} />
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {filterWebhookId
                    ? t('webhooks.attempts.emptyFiltered', 'No failed deliveries for this endpoint.')
                    : t('webhooks.attempts.empty', 'No failed deliveries awaiting retry.')}
                </p>
              </div>
            ) : (
              <div className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                        {['Event', 'Endpoint', 'Status', 'Attempts', 'Last Error', 'Next Retry', 'Action'].map(h => (
                          <th key={h} className="text-left px-4 py-2.5 text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {visibleAttempts.map((attempt, idx) => {
                        const sc = deliveryStatusConfig[attempt.status] ?? deliveryStatusConfig.pending;
                        const canResend = attempt.status === 'exhausted' || attempt.status === 'pending';
                        return (
                          <tr key={attempt.id} style={{ borderBottom: idx < visibleAttempts.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                            <td className="px-4 py-3"><span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{attempt.event}</span></td>
                            <td className="px-4 py-3"><span className="text-xs font-mono truncate max-w-32 block" style={{ color: 'hsl(var(--muted-foreground))' }} title={attempt.endpointUrl}>{attempt.endpointUrl.replace('https://', '').split('/')[0]}</span></td>
                            <td className="px-4 py-3">
                              <span className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full w-fit" style={{ backgroundColor: sc.bg, color: sc.color }}>
                                {sc.icon} {attempt.status}
                              </span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{attempt.attemptCount}<span className="font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>/{attempt.maxAttempts}</span></span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs truncate max-w-40 block" style={{ color: 'hsl(0, 84%, 44%)' }} title={attempt.lastErrorMessage ?? undefined}>
                                {attempt.lastErrorMessage ?? '—'}
                              </span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                                {attempt.status === 'pending' && attempt.nextRetryAt
                                  ? new Date(attempt.nextRetryAt).toLocaleTimeString()
                                  : attempt.status === 'succeeded' ? 'Done' : '—'}
                              </span>
                            </td>
                            <td className="px-4 py-3">
                              {canResend ? (
                                <button
                                  className="flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-lg transition-colors"
                                  style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}
                                  onClick={() => handleResend(attempt.id)}
                                  disabled={resendingId === attempt.id}
                                  title="Queue for immediate retry"
                                >
                                  {resendingId === attempt.id
                                    ? <Loader2 size={11} className="animate-spin" />
                                    : <RefreshCw size={11} />}
                                  Resend
                                </button>
                              ) : attempt.status === 'processing' ? (
                                <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>In progress…</span>
                              ) : null}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )
          )}
        </div>
      )}

      {/* Delivery logs */}
      {!loading && webhooks.length > 0 && (
        <div>
          <button className="flex items-center gap-2 w-full text-left mb-3" onClick={handleToggleLogs}>
            <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.logs.title', 'Delivery Logs')}</h3>
            {logsLoading && <Loader2 size={13} className="animate-spin ml-1" style={{ color: 'hsl(var(--muted-foreground))' }} />}
            <div className="ml-auto">
              {expandedLogs ? <ChevronUp size={15} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <ChevronDown size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />}
            </div>
          </button>
          {expandedLogs && (
            logsLoading ? (
              <div className="flex items-center justify-center py-8 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <Loader2 size={16} className="animate-spin" /> {t('webhooks.logs.loading', 'Loading logs…')}
              </div>
            ) : deliveryLogs.length === 0 ? (
              <div className="rounded-2xl p-6 text-center" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('webhooks.logs.empty', 'No delivery logs yet. Logs will appear here as events are triggered.')}</p>
              </div>
            ) : (
              <div className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                        {[
                          t('webhooks.logs.table.event', 'Event'),
                          t('webhooks.logs.table.endpoint', 'Endpoint'),
                          t('webhooks.logs.table.status', 'Status'),
                          t('webhooks.logs.table.response', 'Response'),
                          t('webhooks.logs.table.duration', 'Duration'),
                          t('webhooks.logs.table.timestamp', 'Timestamp')
                        ].map(h => (
                          <th key={h} className="text-left px-4 py-2.5 text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {deliveryLogs.map((log, idx) => {
                        const sc = deliveryStatusConfig[log.status] ?? deliveryStatusConfig.failed;
                        return (
                          <tr key={log.id} style={{ borderBottom: idx < deliveryLogs.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                            <td className="px-4 py-3"><span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{log.event}</span></td>
                            <td className="px-4 py-3"><span className="text-xs font-mono truncate max-w-32 block" style={{ color: 'hsl(var(--muted-foreground))' }}>{log.endpointUrl?.replace('https://', '').split('/')[0]}</span></td>
                            <td className="px-4 py-3">
                              <span className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full w-fit" style={{ backgroundColor: sc.bg, color: sc.color }}>
                                {sc.icon} {log.status}
                              </span>
                            </td>
                            <td className="px-4 py-3"><span className="text-xs font-mono font-semibold" style={{ color: log.responseCode && log.responseCode < 300 ? 'hsl(142, 72%, 29%)' : 'hsl(0, 84%, 44%)' }}>{log.responseCode ?? '—'}</span></td>
                            <td className="px-4 py-3"><span className="text-xs font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{log.durationMs != null ? `${log.durationMs}ms` : '—'}</span></td>
                            <td className="px-4 py-3"><span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{new Date(log.triggeredAt).toLocaleString()}</span></td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )
          )}
        </div>
      )}
    </>
  );
}
