import { For, Show, createEffect, createResource, createSignal, createMemo } from "solid-js";
import { A } from "@solidjs/router";
import { locales, planCatalog, planCodes, planCurrencies, tenantPresets } from "@bookra/shared-types";
import { apiClient } from "../lib/api-client";
import { useAuth } from "../providers/auth-provider";
import { useI18n } from "../providers/i18n-provider";
import { BookraCharacter } from "../components/bookra-character";
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  Badge,
  Input,
  Select,
  SkeletonCard,
  Tooltip
} from "../components/ui";
import { WidgetBuilder } from "../components/widget-builder";

// Icon Components
const LayoutDashboardIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/><rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/></svg>
);

const CalendarDaysIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/><path d="M8 14h.01"/><path d="M12 14h.01"/><path d="M16 14h.01"/><path d="M8 18h.01"/><path d="M12 18h.01"/><path d="M16 18h.01"/></svg>
);

const CreditCardIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/></svg>
);

const Settings2Icon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 7h-9"/><path d="M14 17H5"/><circle cx="17" cy="17" r="3"/><circle cx="7" cy="7" r="3"/></svg>
);

const LogOutIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" x2="9" y1="12" y2="12"/></svg>
);

const MenuIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/></svg>
);

const XIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
);

const TrendingUpIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>
);

const UsersIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
);

const ClockIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
);

const MoreHorizontalIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></svg>
);

const CheckCircleIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>
);

const AlertCircleIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>
);

const ChevronLeftIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg>
);

const ChevronRightIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>
);

// Types
type Section = "overview" | "bookings" | "billing" | "settings";

// Demo Data
const createDemoData = (i18n: any) => ({
  summary: {
    tenantSlug: "demo-studio",
    tenantName: "Demo Studio",
    publicBookingUrl: "http://localhost:3000/book/demo-studio",
    kpis: [
      { label: i18n.locale() === 'cs' ? 'Celkem rezervací' : 'Total Bookings', value: 42, change: "+12%", trend: "up" },
      { label: i18n.locale() === 'cs' ? 'Zrušených' : 'Cancelled', value: 3, change: "-5%", trend: "down" },
      { label: i18n.locale() === 'cs' ? 'Dokončených' : 'Completed', value: 38, change: "+8%", trend: "up" },
      { label: i18n.locale() === 'cs' ? 'Noví klienti' : 'New Clients', value: 12, change: "+24%", trend: "up" },
    ],
    upcomingBookings: [
      { id: "1", customerName: "Alice Johnson", service: "Yoga Class", status: "confirmed", startsAt: new Date(Date.now() + 86400000).toISOString(), reference: "BK-001", avatar: "AJ" },
      { id: "2", customerName: "Bob Smith", service: "Massage Therapy", status: "pending", startsAt: new Date(Date.now() + 172800000).toISOString(), reference: "BK-002", avatar: "BS" },
      { id: "3", customerName: "Carol White", service: "Personal Training", status: "confirmed", startsAt: new Date(Date.now() + 259200000).toISOString(), reference: "BK-003", avatar: "CW" },
      { id: "4", customerName: "David Brown", service: "Nutrition Consult", status: "cancelled", startsAt: new Date(Date.now() + 345600000).toISOString(), reference: "BK-004", avatar: "DB" },
    ],
    recentActivity: [
      { action: "New booking", detail: "Alice Johnson booked Yoga Class", time: "2 min ago", type: "booking" },
      { action: "Payment received", detail: "$120 from Bob Smith", time: "15 min ago", type: "payment" },
      { action: "Booking cancelled", detail: "David Brown cancelled", time: "1 hour ago", type: "cancel" },
      { action: "New review", detail: "5-star review from Carol White", time: "3 hours ago", type: "review" },
    ],
  },
  bootstrap: {
    tenantId: "demo-tenant-id",
    tenantName: "Demo Studio",
    preset: "studio",
    locale: i18n.locale(),
    timezone: "Europe/Prague",
    currentUser: { role: "admin", name: "Demo User", email: "demo@bookra.io" },
    brand: { primaryColor: "#a65c3e", name: "Demo Studio" },
  },
  billing: {
    planCode: "pro",
    status: "active",
    nextBilling: "2024-02-15",
    amount: "$49",
    entitlements: {
      maxLocations: 3,
      maxStaff: 10,
      emailReminders: true,
      customBranding: true,
      analytics: true,
    },
  },
});

// Calendar Component
function CalendarView(props: { bookings: any[] }) {
  const [currentDate, setCurrentDate] = createSignal(new Date());
  
  const weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  
  const calendarDays = createMemo(() => {
    const date = currentDate();
    const year = date.getFullYear();
    const month = date.getMonth();
    
    const firstDay = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    
    const days: Array<{ day: number | null; bookings: any[] }> = [];
    
    for (let i = 0; i < firstDay; i++) {
      days.push({ day: null, bookings: [] });
    }
    
    for (let day = 1; day <= daysInMonth; day++) {
      const dayBookings = props.bookings.filter(b => {
        const bookingDate = new Date(b.startsAt);
        return bookingDate.getDate() === day && bookingDate.getMonth() === month;
      });
      days.push({ day, bookings: dayBookings });
    }
    
    return days;
  });
  
  const prevMonth = () => {
    const d = currentDate();
    setCurrentDate(new Date(d.getFullYear(), d.getMonth() - 1, 1));
  };
  
  const nextMonth = () => {
    const d = currentDate();
    setCurrentDate(new Date(d.getFullYear(), d.getMonth() + 1, 1));
  };
  
  return (
    <div class="bg-white rounded-2xl border border-gray-200 p-6">
      <div class="flex items-center justify-between mb-6">
        <h3 class="text-lg font-semibold text-gray-900">
          {monthNames[currentDate().getMonth()]} {currentDate().getFullYear()}
        </h3>
        <div class="flex gap-2">
          <button onClick={prevMonth} class="p-2 hover:bg-gray-100 rounded-lg transition-colors">
            <ChevronLeftIcon />
          </button>
          <button onClick={nextMonth} class="p-2 hover:bg-gray-100 rounded-lg transition-colors">
            <ChevronRightIcon />
          </button>
        </div>
      </div>
      
      <div class="grid grid-cols-7 gap-1 mb-2">
        {weekDays.map(day => (
          <div class="text-center text-xs font-medium text-gray-500 py-2">{day}</div>
        ))}
      </div>
      
      <div class="grid grid-cols-7 gap-1">
        {calendarDays().map(({ day, bookings }) => (
          <div class={`
            aspect-square p-2 rounded-lg border transition-all
            ${day ? 'bg-white border-gray-100 hover:border-gray-300' : 'bg-transparent border-transparent'}
            ${bookings.length > 0 ? 'ring-2 ring-orange-100' : ''}
          `}>
            {day && (
              <>
                <span class="text-sm text-gray-700">{day}</span>
                {bookings.length > 0 && (
                  <div class="mt-1 flex flex-wrap gap-0.5">
                    {bookings.slice(0, 3).map(() => (
                      <div class="w-1.5 h-1.5 rounded-full bg-orange-500" />
                    ))}
                    {bookings.length > 3 && (
                      <span class="text-[8px] text-orange-600">+{bookings.length - 3}</span>
                    )}
                  </div>
                )}
              </>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// Main Dashboard Component
export function DashboardRoute() {
  const i18n = useI18n();
  const auth = useAuth();
  const [activeSection, setActiveSection] = createSignal<Section>("overview");
  const [isMobileMenuOpen, setIsMobileMenuOpen] = createSignal(false);
  const [token] = createResource(() => auth.session()?.session?.id, () => auth.getToken());
  const isDemoMode = () => token()?.startsWith("demo.") ?? false;
  
  const demoData = createMemo(() => createDemoData(i18n));
  
  const [summary] = createResource(token, async (bearer) => {
    if (!bearer) return null;
    if (bearer.startsWith("demo.")) return demoData().summary;
    const response = await apiClient.GET("/v1/dashboard/summary", {
      headers: { Authorization: `Bearer ${bearer}` },
    });
    return response.data ?? null;
  });
  
  const [bootstrap] = createResource(token, async (bearer) => {
    if (!bearer) return null;
    if (bearer.startsWith("demo.")) return demoData().bootstrap;
    const response = await apiClient.GET("/v1/tenants/bootstrap", {
      headers: { Authorization: `Bearer ${bearer}` },
    });
    return response.data ?? null;
  });
  
  const [billing] = createResource(token, async (bearer) => {
    if (!bearer) return null;
    if (bearer.startsWith("demo.")) return demoData().billing;
    const response = await apiClient.GET("/v1/billing/subscription", {
      headers: { Authorization: `Bearer ${bearer}` },
    });
    return response.data ?? null;
  });

  const resolvedSummary = () => (summary.latest as any) ?? (isDemoMode() ? demoData().summary : undefined);
  const resolvedBootstrap = () => (bootstrap.latest as any) ?? (isDemoMode() ? demoData().bootstrap : undefined);
  const resolvedBilling = () => (billing.latest as any) ?? (isDemoMode() ? demoData().billing : undefined);
  const hasTenant = () => Boolean(bootstrap.latest?.tenantId) || isDemoMode();
  const isDashboardReady = () => Boolean(token() && hasTenant() && (summary.latest || isDemoMode()) && (billing.latest || isDemoMode()));

  // Navigation items with new icons
  const navItems = [
    { id: "overview" as Section, label: i18n.locale() === 'cs' ? 'Přehled' : 'Overview', icon: LayoutDashboardIcon },
    { id: "bookings" as Section, label: i18n.locale() === 'cs' ? 'Rezervace' : 'Bookings', icon: CalendarDaysIcon },
    { id: "billing" as Section, label: i18n.locale() === 'cs' ? 'Platby' : 'Billing', icon: CreditCardIcon },
    { id: "settings" as Section, label: i18n.locale() === 'cs' ? 'Nastavení' : 'Settings', icon: Settings2Icon },
  ];

  // Page Components
  const OverviewPage = () => (
    <div class="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      {/* Welcome Header */}
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-semibold text-gray-900">
            {i18n.locale() === 'cs' ? 'Dobrý den,' : 'Welcome back,'} {auth.session()?.user?.name}
          </h1>
          <p class="text-gray-500 mt-1">
            {i18n.locale() === 'cs' 
              ? `Zde je přehled vašeho ${resolvedBootstrap().tenantName}` 
              : `Here's what's happening with ${resolvedBootstrap().tenantName}`}
          </p>
        </div>
        <div class="flex items-center gap-3">
          <span class="text-sm text-gray-500">{new Date().toLocaleDateString()}</span>
        </div>
      </div>

      {/* KPI Cards */}
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {resolvedSummary().kpis.map((kpi: any) => (
          <div class="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow">
            <div class="flex items-start justify-between">
              <div>
                <p class="text-sm font-medium text-gray-500">{kpi.label}</p>
                <p class="text-2xl font-bold text-gray-900 mt-1">{kpi.value}</p>
              </div>
              <div class={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${
                kpi.trend === 'up' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
              }`}>
                <TrendingUpIcon />
                {kpi.change}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Main Content Grid */}
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Calendar */}
        <div class="lg:col-span-2">
          <CalendarView bookings={resolvedSummary().upcomingBookings} />
        </div>

        {/* Recent Activity */}
        <div class="bg-white rounded-2xl border border-gray-200 p-6">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">
            {i18n.locale() === 'cs' ? 'Nedávná aktivita' : 'Recent Activity'}
          </h3>
          <div class="space-y-4">
            {resolvedSummary().recentActivity?.map((activity: any) => (
              <div class="flex items-start gap-3">
                <div class={`w-8 h-8 rounded-full flex items-center justify-center ${
                  activity.type === 'booking' ? 'bg-blue-50 text-blue-600' :
                  activity.type === 'payment' ? 'bg-green-50 text-green-600' :
                  activity.type === 'cancel' ? 'bg-red-50 text-red-600' :
                  'bg-yellow-50 text-yellow-600'
                }`}>
                  {activity.type === 'booking' ? <CheckCircleIcon /> :
                   activity.type === 'cancel' ? <AlertCircleIcon /> :
                   <MoreHorizontalIcon />}
                </div>
                <div class="flex-1 min-w-0">
                  <p class="text-sm font-medium text-gray-900">{activity.action}</p>
                  <p class="text-xs text-gray-500 mt-0.5">{activity.detail}</p>
                  <p class="text-xs text-gray-400 mt-1">{activity.time}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Upcoming Bookings */}
      <div class="bg-white rounded-2xl border border-gray-200 p-6">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">
            {i18n.locale() === 'cs' ? 'Nadcházející rezervace' : 'Upcoming Bookings'}
          </h3>
          <button 
            onClick={() => setActiveSection("bookings")}
            class="text-sm text-orange-600 hover:text-orange-700 font-medium"
          >
            {i18n.locale() === 'cs' ? 'Zobrazit vše' : 'View all'}
          </button>
        </div>
        <div class="divide-y divide-gray-100">
          {resolvedSummary().upcomingBookings?.slice(0, 3).map((booking: any) => (
            <div class="py-4 flex items-center justify-between">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-sm font-medium text-gray-600">
                  {booking.avatar}
                </div>
                <div>
                  <p class="font-medium text-gray-900">{booking.customerName}</p>
                  <p class="text-sm text-gray-500">{booking.service}</p>
                </div>
              </div>
              <div class="text-right">
                <p class="text-sm text-gray-900">{new Date(booking.startsAt).toLocaleDateString()}</p>
                <span class={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                  booking.status === 'confirmed' ? 'bg-green-50 text-green-700' :
                  booking.status === 'pending' ? 'bg-yellow-50 text-yellow-700' :
                  'bg-red-50 text-red-700'
                }`}>
                  {booking.status}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const BookingsPage = () => (
    <div class="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <div class="flex items-center justify-between">
        <h1 class="text-2xl font-semibold text-gray-900">
          {i18n.locale() === 'cs' ? 'Rezervace' : 'Bookings'}
        </h1>
        <button class="bg-orange-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-orange-700 transition-colors">
          {i18n.locale() === 'cs' ? 'Nová rezervace' : 'New Booking'}
        </button>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2">
          <CalendarView bookings={resolvedSummary().upcomingBookings} />
        </div>
        <div class="space-y-4">
          <div class="bg-white rounded-2xl border border-gray-200 p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
              {i18n.locale() === 'cs' ? 'Všechny rezervace' : 'All Bookings'}
            </h3>
            <div class="space-y-3 max-h-[500px] overflow-y-auto">
              {resolvedSummary().upcomingBookings?.map((booking: any) => (
                <div class="p-4 rounded-xl border border-gray-100 hover:border-orange-200 hover:bg-orange-50/30 transition-all cursor-pointer">
                  <div class="flex items-start justify-between">
                    <div class="flex items-center gap-3">
                      <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-sm font-medium text-gray-600">
                        {booking.avatar}
                      </div>
                      <div>
                        <p class="font-medium text-gray-900">{booking.customerName}</p>
                        <p class="text-sm text-gray-500">{booking.service}</p>
                      </div>
                    </div>
                    <span class={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                      booking.status === 'confirmed' ? 'bg-green-50 text-green-700' :
                      booking.status === 'pending' ? 'bg-yellow-50 text-yellow-700' :
                      'bg-red-50 text-red-700'
                    }`}>
                      {booking.status}
                    </span>
                  </div>
                  <div class="mt-3 flex items-center gap-4 text-sm text-gray-500">
                    <span class="flex items-center gap-1">
                      <ClockIcon />
                      {new Date(booking.startsAt).toLocaleString()}
                    </span>
                    <span>{booking.reference}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );

  const BillingPage = () => (
    <div class="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <h1 class="text-2xl font-semibold text-gray-900">
        {i18n.locale() === 'cs' ? 'Platby a předplatné' : 'Billing & Subscription'}
      </h1>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Current Plan */}
        <div class="lg:col-span-2 bg-gradient-to-br from-gray-900 to-gray-800 rounded-2xl p-8 text-white">
          <div class="flex items-start justify-between">
            <div>
              <p class="text-gray-400 text-sm font-medium uppercase tracking-wide">Current Plan</p>
              <h2 class="text-3xl font-bold mt-2 capitalize">{resolvedBilling().planCode}</h2>
              <p class="text-gray-400 mt-1">{resolvedBilling().amount}/month</p>
            </div>
            <span class="inline-flex items-center px-3 py-1 rounded-full bg-green-500/20 text-green-400 text-sm font-medium">
              {resolvedBilling().status}
            </span>
          </div>
          <div class="mt-8 flex items-center gap-4">
            <button class="bg-white text-gray-900 px-4 py-2 rounded-lg font-medium hover:bg-gray-100 transition-colors">
              Upgrade Plan
            </button>
            <button class="text-gray-400 hover:text-white transition-colors">
              View Invoices
            </button>
          </div>
        </div>

        {/* Next Billing */}
        <div class="bg-white rounded-2xl border border-gray-200 p-6">
          <p class="text-gray-500 text-sm font-medium">Next billing date</p>
          <p class="text-2xl font-bold text-gray-900 mt-2">{resolvedBilling().nextBilling}</p>
          <p class="text-gray-500 text-sm mt-1">{resolvedBilling().amount} will be charged</p>
        </div>
      </div>

      {/* Features */}
      <div class="bg-white rounded-2xl border border-gray-200 p-6">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">Plan Features</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {Object.entries(resolvedBilling().entitlements).map(([key, value]) => (
            <div class="flex items-center gap-3 p-4 rounded-xl bg-gray-50">
              <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600">
                <CheckCircleIcon />
              </div>
              <div>
                <p class="font-medium text-gray-900 capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</p>
                <p class="text-sm text-gray-500">{typeof value === 'boolean' ? (value ? 'Enabled' : 'Disabled') : value}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const SettingsPage = () => (
    <div class="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <h1 class="text-2xl font-semibold text-gray-900">
        {i18n.locale() === 'cs' ? 'Nastavení' : 'Settings'}
      </h1>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="bg-white rounded-2xl border border-gray-200 p-6">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">Business Information</h3>
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Business Name</label>
              <input 
                type="text" 
                value={resolvedBootstrap().tenantName}
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                readOnly
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Timezone</label>
              <input 
                type="text" 
                value={resolvedBootstrap().timezone}
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                readOnly
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Locale</label>
              <input 
                type="text" 
                value={resolvedBootstrap().locale}
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                readOnly
              />
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl border border-gray-200 p-6">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">Widget Integration</h3>
          <WidgetBuilder 
            config={{
              tenantSlug: resolvedSummary().tenantSlug,
              publicBookingUrl: resolvedSummary().publicBookingUrl,
              tenantName: resolvedSummary().tenantName,
              primaryColor: resolvedBootstrap().brand?.primaryColor,
            }}
          />
        </div>
      </div>
    </div>
  );

  // Navigation Sidebar
  const Sidebar = () => (
    <aside class="hidden lg:flex flex-col w-64 h-screen sticky top-0 border-r border-gray-200 bg-white">
      <div class="p-6 border-b border-gray-100">
        <A href="/" class="inline-flex items-center gap-3">
          <img src="/bookra-logo.svg" alt="Bookra" class="h-8 w-auto dark:invert" />
        </A>
        <Show when={isDemoMode()}>
          <div class="mt-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-amber-100 text-amber-800 text-xs font-medium">
            {i18n.locale() === 'cs' ? 'Demo režim' : 'Demo Mode'}
          </div>
        </Show>
      </div>

      <nav class="flex-1 p-4 space-y-1">
        {navItems.map((item) => (
          <button
            onClick={() => setActiveSection(item.id)}
            class={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all duration-200 ${
              activeSection() === item.id
                ? "bg-orange-50 text-orange-700"
                : "text-gray-600 hover:text-gray-900 hover:bg-gray-50"
            }`}
          >
            <item.icon />
            {item.label}
          </button>
        ))}
      </nav>

      <div class="p-4 border-t border-gray-100">
        <Show when={auth.session()}>
          <div class="flex items-center gap-3 mb-3">
            <div class="w-10 h-10 rounded-full bg-orange-100 flex items-center justify-center">
              <span class="font-semibold text-orange-700 text-sm">
                {auth.session()?.user?.name?.charAt(0) || 'U'}
              </span>
            </div>
            <div class="flex-1 min-w-0">
              <p class="text-sm font-medium text-gray-900 truncate">{auth.session()?.user?.name}</p>
              <p class="text-xs text-gray-500 truncate">{auth.session()?.user?.email}</p>
            </div>
          </div>
        </Show>
        <button
          onClick={() => void auth.signOut()}
          class="w-full flex items-center gap-3 px-4 py-2 rounded-xl text-sm font-medium text-gray-500 hover:text-red-600 hover:bg-red-50 transition-all duration-200"
        >
          <LogOutIcon />
          {i18n.t("auth.signOut")}
        </button>
      </div>
    </aside>
  );

  // Mobile Menu
  const MobileMenu = () => (
    <Show when={isMobileMenuOpen()}>
      <div class="lg:hidden fixed inset-0 z-50">
        <div class="absolute inset-0 bg-black/50" onClick={() => setIsMobileMenuOpen(false)} />
        <div class="absolute left-0 top-0 h-full w-64 bg-white border-r border-gray-200 shadow-xl">
          <div class="p-4 border-b border-gray-100 flex items-center justify-between">
            <img src="/bookra-logo.svg" alt="Bookra" class="h-8 w-auto dark:invert" />
            <button onClick={() => setIsMobileMenuOpen(false)} class="p-2 hover:bg-gray-100 rounded-lg">
              <XIcon />
            </button>
          </div>
          <nav class="p-4 space-y-1">
            {navItems.map((item) => (
              <button
                onClick={() => {
                  setActiveSection(item.id);
                  setIsMobileMenuOpen(false);
                }}
                class={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all ${
                  activeSection() === item.id
                    ? "bg-orange-50 text-orange-700"
                    : "text-gray-600 hover:bg-gray-50"
                }`}
              >
                <item.icon />
                {item.label}
              </button>
            ))}
          </nav>
        </div>
      </div>
    </Show>
  );

  // Active Page Content
  const ActivePage = () => {
    switch (activeSection()) {
      case "overview": return <OverviewPage />;
      case "bookings": return <BookingsPage />;
      case "billing": return <BillingPage />;
      case "settings": return <SettingsPage />;
      default: return <OverviewPage />;
    }
  };

  return (
    <div class="min-h-screen flex">
      <Sidebar />
      
      <div class="flex-1 flex flex-col min-h-screen">
        <MobileSidebar />
        
        <main class="flex-1 p-4 lg:p-8 overflow-y-auto">
          <Show when={!token.loading && !token()}>
            <div class="max-w-md mx-auto py-16 text-center">
              <div class="relative inline-block mb-8">
                <BookraCharacter pose="forbidden" size="xl" animate={true} />
                <div class="absolute -bottom-2 -right-2 w-10 h-10 rounded-full bg-error/10 flex items-center justify-center">
                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-error">
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                  </svg>
                </div>
              </div>
              <div class="surface-elevated p-8 rounded-card">
                <h3 class="font-display text-xl font-semibold text-ink mb-3">
                  {i18n.locale() === 'cs' ? 'Přístup odepřen' : 'Access Denied'}
                </h3>
                <p class="text-ink-muted mb-6">
                  {i18n.locale() === 'cs' 
                    ? 'Pro přístup do dashboardu se musíte přihlásit.' 
                    : 'You need to sign in to access the dashboard.'}
                </p>
                <div class="flex flex-col gap-3">
                  <button 
                    class="btn-primary w-full"
                    onClick={() => window.dispatchEvent(new CustomEvent('openAuthDialog', { detail: { mode: 'sign-in' } }))}
                  >
                    {i18n.t("auth.signIn")}
                  </button>
                  <button 
                    class="btn-ghost w-full text-sm"
                    onClick={() => window.dispatchEvent(new CustomEvent('openAuthDialog', { detail: { mode: 'register' } }))}
                  >
                    {i18n.t("auth.createAccount")}
                  </button>
                </div>
              </div>
            </div>
          </Show>
      <Show when={token() && (bootstrap.loading || summary.loading || billing.loading)}>
        <div class="flex flex-col items-center py-12">
          <BookraCharacter pose="walk" size="lg" animate={true} />
          <p class="mt-4 text-sm text-ink-muted animate-pulse">Loading your dashboard...</p>
        </div>
      </Show>
      <Show when={token() && bootstrap.latest && !hasTenant()}>
        <Card class="surface-elevated animate-slide-up" style={{"animation-delay": "0.1s"}}>
          <div class="max-w-2xl space-y-6">
            <CardHeader>
              <div class="flex items-center gap-4 mb-4">
                <BookraCharacter pose="laptop" size="md" animate={true} />
                <div>
                  <div class="flex items-center gap-2 mb-1">
                    <Badge variant="secondary">{i18n.t("dashboard.bootstrap")}</Badge>
                  </div>
                  <CardTitle class="mt-1">{i18n.t("dashboard.onboarding.title")}</CardTitle>
                </div>
              </div>
              <CardDescription>{i18n.t("dashboard.onboarding.body")}</CardDescription>
            </CardHeader>
            <CardContent class="space-y-4">
              <div class="grid gap-4 md:grid-cols-2">
                <Input
                  label={i18n.t("dashboard.onboarding.name")}
                  value={businessName()}
                  onInput={(event) => setBusinessName(event.currentTarget.value)}
                />
                <Input
                  label={i18n.t("dashboard.onboarding.slug")}
                  value={slug()}
                  onInput={(event) => setSlug(event.currentTarget.value.toLowerCase())}
                  hint="bookra.io/book/your-slug"
                />
                <Select
                  label={i18n.t("dashboard.onboarding.preset")}
                  value={preset()}
                  onChange={(value) => setPreset(value as (typeof tenantPresets)[number])}
                  options={tenantPresets.map(p => ({ value: p, label: p.charAt(0).toUpperCase() + p.slice(1) }))}
                />
                <Select
                  label={i18n.t("dashboard.onboarding.locale")}
                  value={selectedLocale()}
                  onChange={(value) => setSelectedLocale(value as (typeof locales)[number])}
                  options={locales.map(l => ({ value: l, label: l === 'cs' ? 'Čeština' : 'English' }))}
                />
                <Select
                  label="Plan"
                  value={planCode()}
                  onChange={(value) => setPlanCode(value as (typeof planCodes)[number])}
                  options={planCodes.map((code) => {
                    const isCzech = i18n.locale() === 'cs';
                    const price = isCzech 
                      ? `${planCatalog[code].monthlyCzk} Kč` 
                      : `$${planCatalog[code].monthlyUsd}`;
                    return {
                      value: code,
                      label: `${planCatalog[code].name} · ${price}/${isCzech ? 'měsíc' : 'mo'}`,
                    };
                  })}
                />
                <Select
                  label="Billing currency"
                  value={billingCurrency()}
                  onChange={(value) => setBillingCurrency(value as (typeof planCurrencies)[number])}
                  options={planCurrencies.map((currency) => ({
                    value: currency,
                    label: currency.toUpperCase(),
                  }))}
                />
                <div class="md:col-span-2">
                  <Input
                    label={i18n.t("dashboard.onboarding.timezone")}
                    value={timezone()}
                    onInput={(event) => setTimezone(event.currentTarget.value)}
                    hint="Automatically detected from your browser"
                  />
                </div>
                <Input
                  label="Brand name"
                  value={brandName()}
                  onInput={(event) => setBrandName(event.currentTarget.value)}
                />
                <Input
                  label="Website"
                  value={siteUrl()}
                  onInput={(event) => setSiteUrl(event.currentTarget.value)}
                  placeholder="https://example.com"
                />
                <Input
                  label="Logo URL"
                  value={logoUrl()}
                  onInput={(event) => setLogoUrl(event.currentTarget.value)}
                  placeholder="https://example.com/logo.png"
                />
                <Input
                  label="Primary color"
                  value={primaryColor()}
                  onInput={(event) => setPrimaryColor(event.currentTarget.value)}
                />
                <Input
                  label="First location"
                  value={locationName()}
                  onInput={(event) => setLocationName(event.currentTarget.value)}
                />
                <Input
                  label="Default service"
                  value={serviceName()}
                  onInput={(event) => setServiceName(event.currentTarget.value)}
                />
                <Input
                  label="Duration minutes"
                  value={durationMinutes()}
                  onInput={(event) => setDurationMinutes(event.currentTarget.value)}
                />
                <Input
                  label="Buffer after minutes"
                  value={bufferAfterMinutes()}
                  onInput={(event) => setBufferAfterMinutes(event.currentTarget.value)}
                />
                <Input
                  label="Cancel window hours"
                  value={cancelWindowHours()}
                  onInput={(event) => setCancelWindowHours(event.currentTarget.value)}
                />
                <Input
                  label="Availability starts"
                  value={availabilityStarts()}
                  onInput={(event) => setAvailabilityStarts(event.currentTarget.value)}
                />
                <Input
                  label="Availability ends"
                  value={availabilityEnds()}
                  onInput={(event) => setAvailabilityEnds(event.currentTarget.value)}
                />
                <div class="md:col-span-2">
                  <Input
                    label="Team invites"
                    value={inviteEmails()}
                    onInput={(event) => setInviteEmails(event.currentTarget.value)}
                    hint="Comma-separated emails. You can skip this."
                  />
                </div>
              </div>
            </CardContent>
            <div class="flex flex-wrap items-center gap-3 pt-4">
              <Button
                isLoading={submittingOnboarding()}
                onClick={() => void submitOnboarding()}
              >
                {submittingOnboarding() ? i18n.t("dashboard.onboarding.pending") : i18n.t("dashboard.onboarding.submit")}
              </Button>
              <Show when={onboardingMessage()}>
                <div class="flex items-center gap-3 text-sm animate-fade-in">
                  <BookraCharacter pose="success" size="xs" animate={false} />
                  <p class="font-medium text-success">{onboardingMessage()}</p>
                </div>
              </Show>
            </div>
          </div>
        </Card>
      </Show>
      <Show when={isDashboardReady()}>
      {/* Forbidden character at top */}
      <div class="flex justify-center mb-6">
        <BookraCharacter pose="forbidden" size="lg" animate={false} />
      </div>
      <div class="grid gap-6 md:grid-cols-[1.2fr_0.8fr] animate-slide-up" style={{"animation-delay": "0.1s"}}>
        <Card class="bg-gradient-to-br from-ink to-ink/95 text-canvas border-ink shadow-xl">
          <CardHeader>
            <div class="flex items-center gap-3">
              <BookraCharacter pose="time" size="sm" animate={false} />
              <div class="flex items-center gap-2">
                <div class="w-8 h-8 rounded-lg bg-canvas/10 flex items-center justify-center">
                  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-canvas/80">
                    <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>
                  </svg>
                </div>
                <Badge variant="outline" class="border-canvas/30 text-canvas/70">{i18n.t("dashboard.bootstrap")}</Badge>
              </div>
            </div>
          </CardHeader>
          <CardContent class="space-y-3 text-sm font-sans">
            <div class="flex items-center justify-between py-2 border-b border-canvas/10">
              <span class="text-canvas/60 flex items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
                </svg>
                Tenant
              </span>
              <span class="font-medium text-canvas/90">{resolvedBootstrap().tenantName}</span>
            </div>
            <div class="flex items-center justify-between py-2 border-b border-canvas/10">
              <span class="text-canvas/60 flex items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                </svg>
                Preset
              </span>
              <span class="font-medium text-canvas/90 capitalize">{resolvedBootstrap().preset}</span>
            </div>
            <div class="flex items-center justify-between py-2 border-b border-canvas/10">
              <span class="text-canvas/60 flex items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
                </svg>
                Locale
              </span>
              <span class="font-medium text-canvas/90 uppercase">{resolvedBootstrap().locale}</span>
            </div>
            <div class="flex items-center justify-between py-2 border-b border-canvas/10">
              <span class="text-canvas/60 flex items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
                </svg>
                Timezone
              </span>
              <span class="font-medium text-canvas/90 text-xs">{resolvedBootstrap().timezone}</span>
            </div>
            <div class="flex items-center justify-between py-2">
              <span class="text-canvas/60 flex items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                </svg>
                Role
              </span>
              <Badge size="sm" class="bg-canvas/20 text-canvas border-none capitalize">
                {resolvedBootstrap().currentUser.role}
              </Badge>
            </div>
          </CardContent>
        </Card>
        <Card class="surface-elevated">
          <CardHeader>
            <div class="flex items-center gap-3">
              <BookraCharacter pose="announcement" size="sm" animate={true} />
              <div class="flex items-center gap-2">
                <div class="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center">
                  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-accent">
                    <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>
                  </svg>
                </div>
                <Badge variant="success">
                  {i18n.t("dashboard.liveData")}
                </Badge>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <p class="text-sm text-ink-muted leading-relaxed">
              {i18n.t("dashboard.liveDataBody")}
            </p>
            <div class="mt-4 flex items-center gap-2 text-xs text-ink-subtle">
              <div class="w-2 h-2 rounded-full bg-success animate-pulse" />
              <span>{i18n.t("dashboard.apiReady")}</span>
            </div>
          </CardContent>
        </Card>
      </div>
      <Card class="surface-elevated animate-slide-up" style={{"animation-delay": "0.2s"}}>
        <div class="flex flex-col gap-6 md:flex-row md:items-start md:justify-between p-6">
          <div class="space-y-4">
            <div class="flex items-center gap-3">
              <BookraCharacter pose="error" size="sm" animate={resolvedBilling().status !== "active"} />
              <div class="flex items-center gap-2">
                <div class="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center">
                  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-accent">
                    <rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/>
                  </svg>
                </div>
                <Badge variant="secondary">{i18n.t("dashboard.billing")}</Badge>
              </div>
            </div>
            <div>
              <CardTitle class="font-display text-2xl">
                {i18n.t("dashboard.plan")}: <span class="text-accent font-semibold">{resolvedBilling().planCode}</span>
              </CardTitle>
              <CardDescription class="mt-2 flex items-center gap-2">
                {i18n.t("dashboard.status")}:
                <Badge
                  variant={resolvedBilling().status === "active" ? "success" : "default"}
                  class="capitalize"
                >
                  {resolvedBilling().status}
                </Badge>
              </CardDescription>
            </div>
            <div class="flex flex-wrap gap-2">
              <div class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-canvas-subtle text-xs text-ink-muted">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>
                </svg>
                {resolvedBilling().entitlements.maxLocations} locations
              </div>
              <div class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-canvas-subtle text-xs text-ink-muted">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
                </svg>
                {resolvedBilling().entitlements.maxStaff} staff
              </div>
              <div class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-canvas-subtle text-xs text-ink-muted">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M4 4h16v16H4z"/><path d="m22 6-10 7L2 6"/>
                </svg>
                Email reminders {resolvedBilling().entitlements.emailReminders ? 'enabled' : 'disabled'}
              </div>
            </div>
            <Show when={billingMessage()}>
              <p class="text-sm text-success font-medium flex items-center gap-1.5">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
                {billingMessage()}
              </p>
            </Show>
          </div>
          <div class="flex flex-wrap gap-3">
            <Button
              onClick={() => void openCheckout()}
              class="shadow-md hover:shadow-lg transition-shadow"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="mr-2">
                <circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/>
              </svg>
              {i18n.t("dashboard.checkout")}
            </Button>
            <Tooltip content="Refresh subscription status from Stripe">
              <Button variant="secondary" onClick={() => void refreshBilling()}>
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="mr-2">
                  <polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
                </svg>
                {i18n.t("dashboard.refreshBilling")}
              </Button>
            </Tooltip>
          </div>
        </div>
      </Card>
      <div class="grid gap-6 md:grid-cols-3 animate-slide-up" style={{"animation-delay": "0.3s"}}>
        <For each={resolvedSummary().kpis}>
          {(kpi, index) => (
            <Card class="group surface-elevated hover:shadow-xl transition-all duration-500" style={{ "animation-delay": `${0.1 * (index() + 4)}s` }}>
              <CardContent class="p-6">
                <div class="flex items-center justify-between mb-4">
                  <p class="font-display text-xs font-medium text-ink-muted uppercase tracking-wider">{kpi.label}</p>
                  <div class="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center group-hover:bg-accent/20 transition-colors duration-300">
                    {index() === 0 ? (
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-accent">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                      </svg>
                    ) : index() === 1 ? (
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-accent">
                        <circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
                      </svg>
                    ) : (
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-accent">
                        <line x1="12" y1="20" x2="12" y2="10"/><line x1="18" y1="20" x2="18" y2="4"/><line x1="6" y1="20" x2="6" y2="16"/>
                      </svg>
                    )}
                  </div>
                </div>
                <p class="font-display text-3xl lg:text-4xl font-semibold text-ink tracking-tight group-hover:text-accent transition-colors duration-300">{kpi.value}</p>
                <div class="mt-3 flex items-center gap-1.5">
                  <div class={`w-2 h-2 rounded-full ${index() === 1 ? 'bg-error' : 'bg-success'}`} />
                  <span class="text-xs text-ink-subtle">
                    {index() === 0 ? '+12% from last week' : index() === 1 ? 'Within normal range' : 'Strong performance'}
                  </span>
                </div>
              </CardContent>
            </Card>
          )}
        </For>
      </div>
      <div class="grid gap-6 lg:grid-cols-[0.9fr_1.1fr] animate-slide-up" style={{"animation-delay": "0.4s"}}>
        <Card class="surface-elevated">
          <CardHeader>
            <div class="flex items-center gap-3 mb-2">
              <BookraCharacter pose="announcement" size="sm" animate={false} />
              <div>
                <CardTitle>Next bookings</CardTitle>
                <CardDescription>{resolvedSummary().publicBookingUrl}</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent class="space-y-3">
            <Show
              when={resolvedSummary().upcomingBookings?.length}
              fallback={
                <div class="flex flex-col items-center py-8 text-center">
                  <BookraCharacter pose="connection_error" size="md" animate={true} />
                  <p class="mt-4 text-sm text-ink-muted">No upcoming bookings yet.</p>
                  <p class="text-xs text-ink-subtle mt-1">Share your booking page to get started</p>
                </div>
              }
            >
              <For each={resolvedSummary().upcomingBookings ?? []}>
                {(booking) => (
                  <div class="rounded-card border border-border bg-canvas-subtle/50 p-3">
                    <div class="flex items-center justify-between gap-3">
                      <p class="font-display font-semibold text-ink">{booking.customerName}</p>
                      <Badge size="sm">{booking.status}</Badge>
                    </div>
                    <p class="mt-1 text-sm text-ink-muted">{new Date(booking.startsAt).toLocaleString()}</p>
                    <p class="text-xs text-ink-subtle">{booking.reference}</p>
                  </div>
                )}
              </For>
            </Show>
            <div class="rounded-card border border-border bg-canvas p-3 text-sm">
              <p class="font-medium text-ink">Umami</p>
              <p class="text-ink-muted">{resolvedSummary().tracking?.message ?? "Umami tracking is not connected."}</p>
            </div>
          </CardContent>
        </Card>
        <Card class="surface-elevated">
          <CardHeader>
            <div class="flex items-center gap-3 mb-2">
              <BookraCharacter pose="laptop" size="md" animate={true} />
              <div>
                <CardTitle>{i18n.t("widget.builder.title")}</CardTitle>
                <CardDescription>{i18n.t("widget.builder.subtitle")}</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <WidgetBuilder 
              config={{
                tenantSlug: resolvedSummary().tenantSlug,
                publicBookingUrl: resolvedSummary().publicBookingUrl,
                tenantName: resolvedSummary().tenantName,
                primaryColor: resolvedBootstrap().brand?.primaryColor,
              }}
            />
          </CardContent>
        </Card>
      </div>
      </Show>
        </main>
      </div>
    </div>
  );
}
