'use client';

import { useState, useEffect, use } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  ArrowLeft, Building2, CreditCard, BarChart3, Activity, ShieldOff, ShieldCheck,
  Bot, Volume2, ShoppingBag, CalendarDays, Monitor, Loader2, Save, Clock, Gift,
  XCircle, ChevronDown, LogIn,
} from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { getAdminAlertSettings, saveAdminAlertSettings, AlertSettings } from '@client/api/alert-settings';
import { toast } from 'sonner';
import { useLanguage } from '@client/contexts/LanguageContext';

type TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;

interface Branch { id: string; name: string; isActive: boolean; }
interface SubscriptionDetail {
  id: string | null; planId: string | null; planName: string | null;
  priceMonthly: number; status: string | null;
  trialStart: string | null; trialEnd: string | null;
  currentPeriodEnd: string | null; stripeSubscriptionId: string | null;
}
interface ActivityEntry { eventType: string; description: string; actor: string; time: string; }
interface RestaurantDetail {
  id: string; displayId: string; name: string; owner: string; email: string;
  phone: string | null; cuisineType: string | null; address: string | null;
  description: string | null; seatingCapacity: number | null;
  status: string; joinedDate: string;
  subscription: SubscriptionDetail;
  branches: Branch[];
  usage: { conversations: number; aiQueries: number; orders: number; };
  recentActivity: ActivityEntry[];
  availablePlans: { id: string; name: string; priceMonthly: number; }[];
}

function Toggle({ checked, onChange }: { checked: boolean; onChange: () => void }) {
  return (
    <button
      onClick={onChange}
      className="relative inline-flex items-center w-9 h-5 rounded-full transition-colors shrink-0"
      style={{ backgroundColor: checked ? 'hsl(var(--primary))' : 'hsl(var(--border-strong))' }}
    >
      <span
        className="inline-block w-3.5 h-3.5 bg-white rounded-full shadow transition-transform"
        style={{ transform: checked ? 'translateX(18px)' : 'translateX(2px)' }}
      />
    </button>
  );
}

function trialDaysLeft(trialEnd: string | null, t: (key: string, fallback: string) => string): { text: string; expired: boolean } | null {
  if (!trialEnd) return null;
  const end = new Date(trialEnd);
  const now = new Date();
  const diff = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
  if (diff < 0) return { text: t('admin.restaurants.trialExpired', 'Trial expired'), expired: true };
  if (diff === 0) return { text: t('admin.restaurants.expiresToday', 'Expires today'), expired: false };
  return { text: t('admin.restaurants.daysLeft', `${diff} day${diff !== 1 ? 's' : ''} left`).replace('{{diff}}', String(diff)), expired: false };
}

export default function AdminRestaurantDetailPage({ params }: { params: Promise<{ id?: string }> }) {
  const { t, currentLang } = useLanguage();
  usePageHeader(t('admin.restaurants.detailTitle', "Restaurant Detail"), t('admin.restaurants.detailSubtitle', "Full restaurant profile and management"));
  const { id } = use(params);
  const restaurantId = id ?? '';
  const router = useRouter();

  const [restaurant, setRestaurant] = useState<RestaurantDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [enteringRestaurant, setEnteringRestaurant] = useState(false);

  const [alertSettings, setAlertSettings] = useState<AlertSettings | null>(null);
  const [alertLoading, setAlertLoading] = useState(true);
  const [alertSaving, setAlertSaving] = useState(false);
  const [alertSaved, setAlertSaved] = useState(false);

  const [trialDays, setTrialDays] = useState(14);
  const [selectedPlanId, setSelectedPlanId] = useState('');
  const [trialSaving, setTrialSaving] = useState(false);

  useEffect(() => {
    if (!restaurantId) { setLoading(false); return; }
    fetch(`/api/admin/restaurants/${restaurantId}`)
      .then(r => r.json())
      .then(data => {
        const detail = data.restaurant ?? null;
        setRestaurant(detail);
        setSelectedPlanId(detail?.subscription?.planId ?? '');
        if (detail?.subscription?.trialEnd) {
          const end = new Date(detail.subscription.trialEnd);
          const now = new Date();
          const diff = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
          if (diff > 0) setTrialDays(diff);
        }
      })
      .catch(() => toast.error(t('admin.restaurants.errorLoad', 'Failed to load restaurant')))
      .finally(() => setLoading(false));
  }, [restaurantId, t]);

  useEffect(() => {
    if (!restaurantId) { setAlertLoading(false); return; }
    getAdminAlertSettings(restaurantId)
      .then(s => setAlertSettings(s))
      .catch(() => setAlertSettings({
        soundEnabled: true, volume: 70, autoDismiss: 30,
        showOrders: true, showBookings: true, showAiEscalations: true, browserNotifications: false,
      }))
      .finally(() => setAlertLoading(false));
  }, [restaurantId]);

  const updateAlert = (key: keyof AlertSettings, value: boolean | number) =>
    setAlertSettings(prev => prev ? { ...prev, [key]: value } : prev);

  const handleAlertSave = async () => {
    if (!alertSettings) return;
    setAlertSaving(true);
    try {
      await saveAdminAlertSettings(restaurantId, alertSettings);
      setAlertSaved(true);
      toast.success(t('admin.restaurants.alertSaved', 'Alert settings saved'));
      setTimeout(() => setAlertSaved(false), 2500);
    } catch {
      toast.error(t('admin.restaurants.errorSaveAlerts', 'Failed to save alert settings'));
    } finally {
      setAlertSaving(false);
    }
  };

  const handleSubscriptionUpdate = async (opts: { action?: 'grant_trial' | 'revoke_trial'; planOnly?: boolean }) => {
    setTrialSaving(true);
    try {
      const body: Record<string, unknown> = {};
      if (opts.action) {
        body.action = opts.action;
        if (opts.action === 'grant_trial') body.trialDays = trialDays;
      }
      if (selectedPlanId) body.planId = selectedPlanId;
      const res = await fetch(`/api/admin/restaurants/${restaurantId}/subscription`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!res.ok) throw new Error('Request failed');
      if (opts.planOnly) {
        toast.success(t('admin.restaurants.planUpdated', 'Plan updated'));
      } else {
        toast.success(opts.action === 'grant_trial' 
          ? t('admin.restaurants.trialGranted', `Trial granted for ${trialDays} days`).replace('{{days}}', String(trialDays)) 
          : t('admin.restaurants.trialRevoked', 'Trial revoked'));
      }
      const refreshed = await fetch(`/api/admin/restaurants/${restaurantId}`).then(r => r.json());
      setRestaurant(refreshed.restaurant ?? null);
    } catch {
      toast.error(t('admin.restaurants.errorUpdateSubscription', 'Failed to update subscription'));
    } finally {
      setTrialSaving(false);
    }
  };

  const handleEnterRestaurant = async () => {
    if (!restaurant) return;
    setEnteringRestaurant(true);
    try {
      const res = await fetch('/api/admin/support/impersonate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ restaurantId }),
      });
      if (!res.ok) throw new Error('Failed to switch context');
      router.push('/restaurant-dashboard');
    } catch {
      toast.error(t('admin.restaurants.errorEnterView', 'Failed to enter restaurant view'));
      setEnteringRestaurant(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
        <Loader2 size={20} className="animate-spin" /> {t('admin.restaurants.loading', 'Loading restaurant…')}
      </div>
    );
  }

  if (!restaurant) {
    return (
      <div className="text-center py-20">
        <p className="text-sm font-medium mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.notFound', 'Restaurant not found')}</p>
        <Link href="/admin/restaurants" className="btn-secondary text-sm">{t('admin.restaurants.backToList', 'Back to list')}</Link>
      </div>
    );
  }

  const sub = restaurant.subscription;
  const trial = trialDaysLeft(sub.trialEnd, t);

  return (
    <>
      <div className="flex items-center gap-3 mb-6">
        <Link href="/admin/restaurants" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
            <Building2 size={20} style={{ color: 'hsl(var(--primary))' }} />
          </div>
          <div>
            <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{restaurant.name}</h2>
            <span className={`badge ${restaurant.status === 'active' ? 'badge-success' : 'badge-danger'} text-xs`}>{restaurant.status}</span>
          </div>
        </div>
        <div className="ml-auto flex gap-2 items-center">
          <button
            onClick={handleEnterRestaurant}
            disabled={enteringRestaurant}
            className="btn-primary text-xs py-2 flex items-center gap-1.5"
          >
            {enteringRestaurant ? <Loader2 size={13} className="animate-spin" /> : <LogIn size={13} />}
            {t('admin.restaurants.enterAsRestaurant', 'Enter as Restaurant')}
          </button>
          {restaurant.status === 'active' ? (
            <button className="btn-secondary text-xs py-2" style={{ color: 'hsl(var(--danger))' }}>
              <ShieldOff size={14} /> {t('admin.restaurants.suspend', 'Suspend')}
            </button>
          ) : (
            <button className="btn-primary text-xs py-2">
              <ShieldCheck size={14} /> {t('admin.restaurants.activate', 'Activate')}
            </button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          {/* Profile */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.profile', 'Restaurant Profile')}</h3>
            <div className="grid grid-cols-2 gap-4 text-sm">
              {[
                { label: t('admin.restaurants.labelOwner', 'Owner'), value: restaurant.owner || '—' },
                { label: t('admin.restaurants.labelEmail', 'Email'), value: restaurant.email || '—' },
                { label: t('admin.restaurants.labelPhone', 'Phone'), value: restaurant.phone || '—' },
                { label: t('admin.restaurants.labelCuisine', 'Cuisine'), value: restaurant.cuisineType || '—' },
                { label: t('admin.restaurants.labelAddress', 'Address'), value: restaurant.address || '—' },
                { label: t('admin.restaurants.labelCapacity', 'Seating Capacity'), value: restaurant.seatingCapacity != null ? String(restaurant.seatingCapacity) : '—' },
                { label: t('admin.restaurants.labelJoined', 'Joined'), value: new Date(restaurant.joinedDate).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' }) },
                { label: t('admin.restaurants.labelId', 'Restaurant ID'), value: restaurant.displayId || restaurantId },
              ].map(item => (
                <div key={item.label}>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</p>
                  <p className="font-medium mt-0.5 truncate" style={{ color: 'hsl(var(--foreground))' }}>{item.value}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Branches */}
          <div className="card overflow-hidden">
            <div className="px-5 py-3.5 flex items-center justify-between" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.branches', 'Branches')} ({restaurant.branches.length})</h3>
            </div>
            {restaurant.branches.length === 0 ? (
              <p className="px-5 py-4 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.restaurants.noBranches', 'No branches found.')}</p>
            ) : restaurant.branches.map((branch, idx) => (
              <div key={branch.id} className="flex items-center justify-between px-5 py-3.5" style={{ borderBottom: idx < restaurant.branches.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                <div className="flex items-center gap-3">
                  <Building2 size={16} style={{ color: 'hsl(var(--primary))' }} />
                  <span className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{branch.name}</span>
                </div>
                <span className={`badge ${branch.isActive ? 'badge-success' : 'badge-neutral'}`}>{branch.isActive ? t('admin.restaurants.statusActive', 'active') : t('admin.restaurants.statusInactive', 'inactive')}</span>
              </div>
            ))}
          </div>

          {/* Alert Settings Override */}
          <div className="card p-5">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <Volume2 size={16} style={{ color: 'hsl(var(--primary))' }} />
                <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.alertSettingsOverride', 'Alert Settings Override')}</h3>
              </div>
              <button
                className="btn-primary text-xs py-1.5 px-3"
                onClick={handleAlertSave}
                disabled={alertSaving || alertLoading || !alertSettings}
              >
                {alertSaving ? <Loader2 size={12} className="animate-spin" /> : <Save size={12} />}
                {alertSaved ? t('admin.restaurants.saved', 'Saved!') : t('admin.restaurants.save', 'Save')}
              </button>
            </div>
            {alertLoading ? (
              <div className="flex items-center gap-2 py-4 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <Loader2 size={14} className="animate-spin" /> {t('admin.restaurants.loadingAlerts', 'Loading alert settings…')}
              </div>
            ) : alertSettings ? (
              <div className="space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { key: 'showOrders' as keyof AlertSettings, icon: <ShoppingBag size={13} />, label: t('admin.restaurants.orderAlerts', 'Order Alerts'), color: 'hsl(22, 89%, 48%)' },
                    { key: 'showBookings' as keyof AlertSettings, icon: <CalendarDays size={13} />, label: t('admin.restaurants.bookingAlerts', 'Booking Alerts'), color: 'hsl(210, 100%, 40%)' },
                    { key: 'showAiEscalations' as keyof AlertSettings, icon: <Bot size={13} />, label: t('admin.restaurants.aiEscalations', 'AI Escalations'), color: 'hsl(231, 40%, 45%)' },
                    { key: 'browserNotifications' as keyof AlertSettings, icon: <Monitor size={13} />, label: t('admin.restaurants.browserNotifications', 'Browser Notifications'), color: 'hsl(38, 92%, 40%)' },
                    { key: 'soundEnabled' as keyof AlertSettings, icon: <Volume2 size={13} />, label: t('admin.restaurants.soundEnabled', 'Sound Enabled'), color: 'hsl(var(--primary))' },
                  ].map(item => (
                    <div key={item.key} className="flex items-center justify-between p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                      <div className="flex items-center gap-2 text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>
                        <span style={{ color: item.color }}>{item.icon}</span>
                        {item.label}
                      </div>
                      <Toggle
                        checked={alertSettings[item.key] as boolean}
                        onChange={() => updateAlert(item.key, !alertSettings[item.key])}
                      />
                    </div>
                  ))}
                  <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.volume', 'Volume')}</span>
                      <span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--primary))' }}>{alertSettings.volume}%</span>
                    </div>
                    <input
                      type="range" min={0} max={100} value={alertSettings.volume}
                      onChange={e => updateAlert('volume', parseInt(e.target.value, 10))}
                      className="w-full accent-orange-500"
                    />
                  </div>
                </div>
                <div className="flex items-center gap-2 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('admin.restaurants.autoDismiss', 'Auto-dismiss after:')}
                  <div className="flex gap-1 ml-1">
                    {[15, 30, 60, 120].map(sec => (
                      <button
                        key={sec}
                        onClick={() => updateAlert('autoDismiss', sec)}
                        className="px-2 py-0.5 rounded-lg text-xs font-semibold transition-all"
                        style={{
                          backgroundColor: alertSettings.autoDismiss === sec ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                          color: alertSettings.autoDismiss === sec ? 'white' : 'hsl(var(--foreground-secondary))',
                        }}
                      >
                        {sec < 60 ? `${sec}s` : `${sec / 60}m`}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            ) : (
              <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.restaurants.errorLoadAlerts', 'Unable to load alert settings.')}</p>
            )}
          </div>
        </div>

        {/* Right column */}
        <div className="space-y-5">
          {/* Subscription */}
          <div className="card p-5">
            <div className="flex items-center gap-2 mb-4">
              <CreditCard size={16} style={{ color: 'hsl(var(--primary))' }} />
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.subscription', 'Subscription')}</h3>
            </div>
            <div className="p-3 rounded-xl mb-4" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
              <p className="font-bold text-base" style={{ color: 'hsl(var(--primary))' }}>{sub.planName ?? t('admin.restaurants.noPlan', 'No Plan')}</p>
              <p className="text-sm" style={{ color: 'hsl(var(--primary))' }}>
                {sub.priceMonthly > 0 ? `$${sub.priceMonthly}/mo` : t('admin.restaurants.free', 'Free')}
              </p>
            </div>
            <div className="space-y-2 text-xs">
              {[
                { label: t('admin.restaurants.labelStatus', 'Status'), value: sub.status ?? '—' },
                sub.trialStart ? { label: t('admin.restaurants.labelTrialStart', 'Trial Started'), value: new Date(sub.trialStart).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' }) } : null,
                sub.trialEnd ? { label: t('admin.restaurants.labelTrialEnd', 'Trial Ends'), value: new Date(sub.trialEnd).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' }) } : null,
                sub.currentPeriodEnd ? { label: t('admin.restaurants.labelNextBilling', 'Next Billing'), value: new Date(sub.currentPeriodEnd).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' }) } : null,
              ].filter(Boolean).map((item) => item && (
                <div key={item.label} className="flex justify-between">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</span>
                  <span className="font-medium capitalize" style={{ color: 'hsl(var(--foreground))' }}>{item.value}</span>
                </div>
              ))}
              {trial && (
                <div className="flex justify-between">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.restaurants.trialStatus', 'Trial Status')}</span>
                  <span className="font-semibold" style={{ color: trial.expired ? 'hsl(var(--danger))' : 'hsl(var(--success))' }}>
                    {trial.text}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Trial Management */}
          <div className="card p-5">
            <div className="flex items-center gap-2 mb-4">
              <Clock size={16} style={{ color: 'hsl(var(--primary))' }} />
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.trialManagement', 'Trial Management')}</h3>
            </div>

            <div className="space-y-3">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.restaurants.plan', 'Plan')}</label>
                <div className="relative">
                  <select
                    value={selectedPlanId}
                    onChange={e => setSelectedPlanId(e.target.value)}
                    className="input-base appearance-none pr-8 w-full"
                  >
                    <option value="">— {t('admin.restaurants.keepCurrentPlan', 'Keep current plan')} —</option>
                    {restaurant.availablePlans.map(p => (
                      <option key={p.id} value={p.id}>{p.name} (${p.priceMonthly}/mo)</option>
                    ))}
                  </select>
                  <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none" style={{ color: 'hsl(var(--muted-foreground))' }} />
                </div>
              </div>

              <button
                onClick={() => handleSubscriptionUpdate({ planOnly: true })}
                disabled={trialSaving || !selectedPlanId}
                className="btn-secondary w-full justify-center flex items-center gap-2"
              >
                {trialSaving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
                {t('admin.restaurants.savePlanChange', 'Save Plan Change')}
              </button>

              <div className="border-t my-1" style={{ borderColor: 'hsl(var(--border))' }} />

              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.restaurants.trialDuration', 'Trial Duration (days)')}</label>
                <input
                  type="number"
                  min={1}
                  max={365}
                  value={trialDays}
                  onChange={e => setTrialDays(Math.max(1, parseInt(e.target.value, 10) || 14))}
                  className="input-base w-full"
                />
              </div>

              <button
                onClick={() => handleSubscriptionUpdate({ action: 'grant_trial' })}
                disabled={trialSaving}
                className="btn-primary w-full justify-center flex items-center gap-2"
              >
                {trialSaving ? <Loader2 size={14} className="animate-spin" /> : <Gift size={14} />}
                {t('admin.restaurants.grantTrial', 'Grant Trial')}
              </button>

              <button
                onClick={() => handleSubscriptionUpdate({ action: 'revoke_trial' })}
                disabled={trialSaving || sub.status !== 'trial'}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold border transition-colors disabled:opacity-50"
                style={{ color: 'hsl(var(--danger))', borderColor: 'hsl(var(--danger) / 0.4)', backgroundColor: 'transparent' }}
              >
                {trialSaving ? <Loader2 size={14} className="animate-spin" /> : <XCircle size={14} />}
                {t('admin.restaurants.revokeTrial', 'Revoke Trial')}
              </button>
            </div>
          </div>

          {/* Usage */}
          <div className="card p-5">
            <div className="flex items-center gap-2 mb-4">
              <BarChart3 size={16} style={{ color: 'hsl(var(--primary))' }} />
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.usage', 'Usage')}</h3>
            </div>
            <div className="space-y-4">
              {[
                { label: t('admin.restaurants.usageAiQueries', 'AI Queries / API Calls'), icon: Bot, value: restaurant.usage.aiQueries },
                { label: t('admin.restaurants.usageConversations', 'Conversations'), icon: Activity, value: restaurant.usage.conversations },
                { label: t('admin.restaurants.usageOrders', 'Orders'), icon: ShoppingBag, value: restaurant.usage.orders },
                { label: t('admin.restaurants.usageBranches', 'Branches'), icon: Building2, value: restaurant.branches.length },
              ].map(stat => {
                const StatIcon = stat.icon;
                return (
                  <div key={stat.label} className="flex items-center justify-between">
                    <div className="flex items-center gap-1.5 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      <StatIcon size={12} /> {stat.label}
                    </div>
                    <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                      {stat.value.toLocaleString()}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* Recent Activity (full-width below grid) */}
      {restaurant.recentActivity.length > 0 && (
        <div className="card p-5 mt-5">
          <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.restaurants.recentActivity', 'Recent Activity')}</h3>
          <div className="space-y-3">
            {restaurant.recentActivity.map((log, idx) => (
              <div key={idx} className="flex items-center gap-3 py-2" style={{ borderBottom: idx < restaurant.recentActivity.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                <div className="w-7 h-7 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  <Activity size={13} style={{ color: 'hsl(var(--primary))' }} />
                </div>
                <div className="flex-1">
                  <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{log.description}</p>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>by {log.actor}</p>
                </div>
                <span className="text-xs shrink-0" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {new Date(log.time).toLocaleDateString(currentLang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  );
}
