'use client';

import { toast } from 'sonner';
import { useState, useEffect, useRef } from 'react';
import AlertOverlay from '@client/components/AlertOverlay';
import DemoDisabled from '@client/components/demo/DemoDisabled';
import { useAuth } from '@client/contexts/AuthContext';
import { Save, Clock, Bell, ToggleLeft, ToggleRight, Upload, Check, CreditCard, Download, Zap, TrendingUp, MessageSquare, Phone, GitBranch, Plus, Trash2, Star, Receipt, Shield, ArrowUpCircle, ArrowDownCircle, Volume2, VolumeX, Sliders, Monitor, TestTube, ShoppingBag, CalendarDays, Bot, Webhook, Key, Eye, EyeOff, Copy, CheckCircle, XCircle, ChevronDown, ChevronUp, X, Code, Lock, Globe, Play, Edit2, RefreshCw, Search, CheckCircle2, Circle, ExternalLink, Truck, Users, BarChart3, BookOpen, Tag, RotateCcw, Mail, Info, ShoppingCart, AlertCircle } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import { SafeChart } from '@client/components/ui/SafeChart';
import ConfirmModal from '@client/components/ui/ConfirmModal';
import { listWebhooks, createWebhook, updateWebhook as apiUpdateWebhook, deleteWebhook as apiDeleteWebhook, Webhook as ApiWebhook, listDeliveryLogs, DeliveryLog } from '@client/api/webhooks';
import { listApiKeys, createApiKey as apiCreateApiKey, revokeApiKey as apiRevokeApiKey, ApiKey as ApiKeyData } from '@client/api/api-keys';
import {
  getSubscription, getUsage, listPlans as fetchBillingPlans, getApiUsageChart, startCheckout, listInvoices,
  getActiveGateways, getBillingContact, saveBillingContact, startRazorpayCheckout, verifyRazorpayPayment, fetchProrationPreview, validatePromoCode,
  BillingSubscription, BillingUsage, Plan as BillingPlan, UnifiedInvoice as StripeInvoice, GatewayInfo,
} from '@client/api/billing';
import { listTemplates as fetchServerTemplates, saveTemplates as saveServerTemplates } from '@client/api/templates';
import {
  getNotificationPreferences as fetchNotifPrefs,
  saveNotificationPreferences as saveNotifPrefs,
  NotifPreference,
} from '@client/api/notification-preferences';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import ProviderKeysTab from '@client/components/settings/ProviderKeysTab';
import EmailSmtpTab from '@client/components/settings/EmailSmtpTab';
import ChangeEmailForm from '@client/components/settings/ChangeEmailForm';
import { getBranch } from '@client/api/branches';

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


type Tab = 'profile' | 'hours' | 'alert-settings' | 'billing' | 'notifications' | 'templates' | 'webhooks' | 'rest-api' | 'provider-keys' | 'email-smtp';

const days = (t: TFn) => [
  t('common.days.monday', 'Monday'),
  t('common.days.tuesday', 'Tuesday'),
  t('common.days.wednesday', 'Wednesday'),
  t('common.days.thursday', 'Thursday'),
  t('common.days.friday', 'Friday'),
  t('common.days.saturday', 'Saturday'),
  t('common.days.sunday', 'Sunday')
];

type BillingTab = 'overview' | 'plans' | 'invoices';

const planColors: Record<string, string> = {
  Starter: 'hsl(210, 100%, 40%)',
  Growth: 'hsl(142, 72%, 29%)',
  Pro: 'hsl(22, 89%, 48%)',
  Enterprise: 'hsl(231, 40%, 14%)',
};

const usageIcons: Record<string, React.ReactNode> = {
  conversations: <MessageSquare size={16} />,
  voiceMinutes: <Phone size={16} />,
  branches: <GitBranch size={16} />,
  apiCalls: <Zap size={16} />,
};

const usageLabels = (t: TFn): Record<string, string> => ({
  conversations: t('restaurantSettings.billing.usage.conversations', 'AI Conversations'),
  voiceMinutes: t('restaurantSettings.billing.usage.voiceMinutes', 'Voice Minutes'),
  branches: t('restaurantSettings.billing.usage.branches', 'Branches'),
  apiCalls: t('restaurantSettings.billing.usage.apiCalls', 'API Calls')
});

const usageUnits = (t: TFn): Record<string, string> => ({
  conversations: t('restaurantSettings.billing.usage.units.conversations', 'conversations'),
  voiceMinutes: t('restaurantSettings.billing.usage.units.voiceMinutes', 'minutes'),
  branches: t('restaurantSettings.billing.usage.units.branches', 'branches'),
  apiCalls: t('restaurantSettings.billing.usage.units.apiCalls', 'calls')
});
const usageColorMap: Record<string, string> = { conversations: 'hsl(22, 89%, 48%)', voiceMinutes: 'hsl(210, 100%, 40%)', branches: 'hsl(142, 72%, 29%)', apiCalls: 'hsl(270, 60%, 50%)' };
const limitKeys: Record<string, string> = { conversations: 'conversations_per_month', voiceMinutes: 'concurrent_voice_calls', branches: 'max_branches', apiCalls: 'api_calls_per_minute' };

// ─── Templates ───────────────────────────────────────────────────────────────
type Channel = 'sms' | 'email' | 'whatsapp';
type TemplateKey = 'order-confirmation' | 'booking-confirmation' | 'customer-alert';

interface Variable { tag: string; label: string; example: string; }
interface Template { id: TemplateKey; label: string; description: string; icon: React.ReactNode; color: string; variables: Variable[]; defaults: Record<Channel, string>; }

const templateVariables = (t: TFn): Record<TemplateKey, Variable[]> => ({
  'order-confirmation': [
    { tag: '{{customer_name}}', label: t('restaurantSettings.templates.vars.customerName', 'Customer Name'), example: 'John Smith' },
    { tag: '{{order_id}}', label: t('restaurantSettings.templates.vars.orderId', 'Order ID'), example: '#ORD-4821' },
    { tag: '{{order_items}}', label: t('restaurantSettings.templates.vars.orderItems', 'Order Items'), example: 'Margherita Pizza, Garlic Bread' },
    { tag: '{{order_total}}', label: t('restaurantSettings.templates.vars.orderTotal', 'Order Total'), example: '$34.50' },
    { tag: '{{estimated_time}}', label: t('restaurantSettings.templates.vars.estimatedTime', 'Estimated Time'), example: '25–30 mins' },
    { tag: '{{restaurant_name}}', label: t('restaurantSettings.templates.vars.restaurantName', 'Restaurant Name'), example: 'The Rustic Fork' },
    { tag: '{{tracking_link}}', label: t('restaurantSettings.templates.vars.trackingLink', 'Tracking Link'), example: 'https://track.example.com/4821' },
  ],
  'booking-confirmation': [
    { tag: '{{customer_name}}', label: t('restaurantSettings.templates.vars.customerName', 'Customer Name'), example: 'Jane Doe' },
    { tag: '{{booking_id}}', label: t('restaurantSettings.templates.vars.bookingId', 'Booking ID'), example: '#BKG-2034' },
    { tag: '{{booking_date}}', label: t('restaurantSettings.templates.vars.bookingDate', 'Booking Date'), example: 'Saturday, March 20, 2026' },
    { tag: '{{booking_time}}', label: t('restaurantSettings.templates.vars.bookingTime', 'Booking Time'), example: '7:30 PM' },
    { tag: '{{party_size}}', label: t('restaurantSettings.templates.vars.partySize', 'Party Size'), example: '4 guests' },
    { tag: '{{table_number}}', label: t('restaurantSettings.templates.vars.tableNumber', 'Table Number'), example: 'Table 12' },
    { tag: '{{restaurant_name}}', label: t('restaurantSettings.templates.vars.restaurantName', 'Restaurant Name'), example: 'The Rustic Fork' },
    { tag: '{{restaurant_address}}', label: t('restaurantSettings.templates.vars.restaurantAddress', 'Restaurant Address'), example: '123 Main St, New York' },
    { tag: '{{cancel_link}}', label: t('restaurantSettings.templates.vars.cancelLink', 'Cancel Link'), example: 'https://book.example.com/cancel/2034' },
  ],
  'customer-alert': [
    { tag: '{{customer_name}}', label: t('restaurantSettings.templates.vars.customerName', 'Customer Name'), example: 'Alex Johnson' },
    { tag: '{{alert_type}}', label: t('restaurantSettings.templates.vars.alertType', 'Alert Type'), example: 'Order Delay' },
    { tag: '{{alert_message}}', label: t('restaurantSettings.templates.vars.alertMessage', 'Alert Message'), example: 'Your order is running 10 minutes late.' },
    { tag: '{{order_id}}', label: t('restaurantSettings.templates.vars.orderId', 'Order ID'), example: '#ORD-5512' },
    { tag: '{{restaurant_name}}', label: t('restaurantSettings.templates.vars.restaurantName', 'Restaurant Name'), example: 'The Rustic Fork' },
    { tag: '{{support_link}}', label: t('restaurantSettings.templates.vars.supportLink', 'Support Link'), example: 'https://help.example.com' },
  ],
});

const defaultTemplates: Record<TemplateKey, Record<Channel, string>> = {
  'order-confirmation': {
    sms: `Hi {{customer_name}}! Your order {{order_id}} from {{restaurant_name}} has been confirmed. Items: {{order_items}}. Total: {{order_total}}. Estimated delivery: {{estimated_time}}. Track here: {{tracking_link}}`,
    email: `Dear {{customer_name}},\n\nThank you for your order at {{restaurant_name}}!\n\nOrder ID: {{order_id}}\nItems: {{order_items}}\nTotal: {{order_total}}\nEstimated Time: {{estimated_time}}\n\nTrack your order: {{tracking_link}}\n\nWe hope you enjoy your meal!\n\nThe {{restaurant_name}} Team`,
    whatsapp: `👋 Hi {{customer_name}}!\n\n✅ Your order *{{order_id}}* is confirmed!\n\n🍽️ *Items:* {{order_items}}\n💰 *Total:* {{order_total}}\n⏱️ *ETA:* {{estimated_time}}\n\n📍 Track: {{tracking_link}}`,
  },
  'booking-confirmation': {
    sms: `Hi {{customer_name}}! Your table at {{restaurant_name}} is confirmed. Booking {{booking_id}} for {{party_size}} on {{booking_date}} at {{booking_time}}. Cancel: {{cancel_link}}`,
    email: `Dear {{customer_name}},\n\nYour reservation at {{restaurant_name}} is confirmed!\n\nBooking ID: {{booking_id}}\nDate: {{booking_date}}\nTime: {{booking_time}}\nParty Size: {{party_size}}\nTable: {{table_number}}\nAddress: {{restaurant_address}}\n\nNeed to cancel? {{cancel_link}}\n\nWe look forward to seeing you!\n\nThe {{restaurant_name}} Team`,
    whatsapp: `👋 Hi {{customer_name}}!\n\n🎉 Your reservation is confirmed!\n\n📅 *Date:* {{booking_date}}\n🕐 *Time:* {{booking_time}}\n👥 *Guests:* {{party_size}}\n🪑 *Table:* {{table_number}}\n📍 *Address:* {{restaurant_address}}\n\nNeed to cancel? {{cancel_link}}`,
  },
  'customer-alert': {
    sms: `Hi {{customer_name}}, alert from {{restaurant_name}}: {{alert_message}} (Ref: {{order_id}}). Need help? {{support_link}}`,
    email: `Dear {{customer_name}},\n\nWe wanted to let you know:\n\n{{alert_message}}\n\nReference: {{order_id}}\n\nIf you need assistance, please visit: {{support_link}}\n\nApologies for any inconvenience.\n\nThe {{restaurant_name}} Team`,
    whatsapp: `⚠️ Hi {{customer_name}},\n\n*{{alert_type}}* — {{alert_message}}\n\nRef: {{order_id}}\n\nNeed help? {{support_link}}`,
  },
};

const templatesList = (t: TFn): Template[] => [
  { id: 'order-confirmation', label: t('restaurantSettings.templates.orderConfirmation.label', 'Order Confirmation'), description: t('restaurantSettings.templates.orderConfirmation.description', 'Sent when a customer order is successfully placed.'), icon: <CheckCircle2 size={16} />, color: 'hsl(142, 72%, 29%)', variables: templateVariables(t)['order-confirmation'], defaults: defaultTemplates['order-confirmation'] },
  { id: 'booking-confirmation', label: t('restaurantSettings.templates.bookingConfirmation.label', 'Booking Confirmation'), description: t('restaurantSettings.templates.bookingConfirmation.description', 'Sent when a table reservation is confirmed.'), icon: <Bell size={16} />, color: 'hsl(210, 100%, 40%)', variables: templateVariables(t)['booking-confirmation'], defaults: defaultTemplates['booking-confirmation'] },
  { id: 'customer-alert', label: t('restaurantSettings.templates.customerAlert.label', 'Customer Alert'), description: t('restaurantSettings.templates.customerAlert.description', 'Sent to notify customers about delays or updates.'), icon: <Info size={16} />, color: 'hsl(22, 89%, 48%)', variables: templateVariables(t)['customer-alert'], defaults: defaultTemplates['customer-alert'] },
];

const channels = (t: TFn): { id: Channel; label: string; icon: React.ReactNode }[] => [
  // { id: 'sms', label: t('common.sms', 'SMS'), icon: <Phone size={14} /> },
  { id: 'email', label: t('common.email', 'Email'), icon: <Mail size={14} /> },
  // { id: 'whatsapp', label: t('common.whatsapp', 'WhatsApp'), icon: <MessageSquare size={14} /> },
];

function escapeHtml(str: string): string {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function renderPreview(text: string, vars: Variable[]): string {
  let result = escapeHtml(text);
  vars.forEach((v) => {
    const escapedTag = escapeHtml(v.tag);
    result = result.split(escapedTag).join(`<span style="background:hsl(22,89%,95%);color:hsl(22,89%,35%);padding:0 3px;border-radius:3px;font-weight:600">${escapeHtml(v.example)}</span>`);
  });
  return result.replace(/\n/g, '<br/>');
}

// ─── Webhooks ─────────────────────────────────────────────────────────────────
const allWebhookEvents = [
  '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',
];

// ─── REST API ─────────────────────────────────────────────────────────────────

const apiEndpoints = (t: TFn) => [
  { method: 'GET', path: '/v1/orders', description: t('restApi.endpoints.listOrders', 'List all orders with filters and pagination') },
  { method: 'GET', path: '/v1/orders/:id', description: t('restApi.endpoints.getOrder', 'Get a single order by ID') },
  { method: 'POST', path: '/v1/orders', description: t('restApi.endpoints.createOrder', 'Create a new order') },
  { method: 'PATCH', path: '/v1/orders/:id', description: t('restApi.endpoints.updateOrder', 'Update order status or details') },
  { method: 'GET', path: '/v1/bookings', description: t('restApi.endpoints.listBookings', 'List all table bookings') },
  { method: 'POST', path: '/v1/bookings', description: t('restApi.endpoints.createBooking', 'Create a new table booking') },
  { method: 'DELETE', path: '/v1/bookings/:id', description: t('restApi.endpoints.cancelBooking', 'Cancel a booking') },
  { method: 'GET', path: '/v1/customers', description: t('restApi.endpoints.listCustomers', 'List all customers') },
  { method: 'GET', path: '/v1/customers/:id', description: t('restApi.endpoints.getCustomer', 'Get customer profile and order history') },
  { method: 'GET', path: '/v1/menu/items', description: t('restApi.endpoints.listMenuItems', 'List all menu items') },
  { method: 'POST', path: '/v1/menu/items', description: t('restApi.endpoints.createMenuItem', 'Create a new menu item') },
  { method: 'GET', path: '/v1/analytics/summary', description: t('restApi.endpoints.analyticsSummary', 'Get revenue and order analytics summary') },
  { method: 'GET', path: '/v1/ai/conversations', description: t('restApi.endpoints.listConversations', 'List AI conversations') },
  { method: 'POST', path: '/v1/ai/conversations/:id/takeover', description: t('restApi.endpoints.takeoverConversation', 'Take over an AI conversation') },
];

const methodColors: Record<string, { color: string; bg: string }> = {
  GET: { color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)' },
  POST: { color: 'hsl(210, 100%, 40%)', bg: 'hsl(210, 100%, 96%)' },
  PATCH: { color: 'hsl(38, 92%, 40%)', bg: 'hsl(38, 100%, 96%)' },
  DELETE: { color: 'hsl(0, 84%, 44%)', bg: 'hsl(0, 84%, 97%)' },
};

const allPermissions = ['orders:read', 'orders:write', 'bookings:read', 'bookings:write', 'customers:read', 'customers:write', 'menu:read', 'menu:write', 'analytics:read', 'ai:read', 'ai:write'];

// ─── Marketplace ──────────────────────────────────────────────────────────────
interface Integration { id: string; name: string; description: string; category: string; logo: string; logoColor: string; connected: boolean; popular?: boolean; setupSteps: { title: string; description: string }[]; docsUrl?: string; }

const getMarketplaceIntegrations = (t: TFn): Integration[] => [
  { id: 'square', name: t('marketplace.square.name', 'Square POS'), description: t('marketplace.square.description', 'Sync orders, menu items, and inventory directly from your Square point-of-sale system.'), category: 'POS Systems', logo: 'SQ', logoColor: 'hsl(210, 100%, 40%)', connected: false, popular: true, setupSteps: [{ title: t('marketplace.square.step1.title', 'Create a Square Developer Account'), description: t('marketplace.square.step1.desc', 'Go to developer.squareup.com and sign in with your Square account.') }, { title: t('marketplace.square.step2.title', 'Generate API Credentials'), description: t('marketplace.square.step2.desc', 'Create a new application and copy your Application ID and Access Token.') }, { title: t('marketplace.square.step3.title', 'Enter Credentials in RestroAgent'), description: t('marketplace.square.step3.desc', 'Paste your Application ID and Access Token and click Authorize.') }, { title: t('marketplace.square.step4.title', 'Select Location'), description: t('marketplace.square.step4.desc', 'Choose which Square location to sync with this RestroAgent branch.') }, { title: t('marketplace.square.step5.title', 'Configure Sync Settings'), description: t('marketplace.square.step5.desc', 'Choose what data to sync: menu items, inventory levels, orders, and customer data.') }] },
  { id: 'toast', name: t('marketplace.toast.name', 'Toast POS'), description: t('marketplace.toast.description', 'Connect Toast to automatically import your menu, manage orders, and track sales in real time.'), category: 'POS Systems', logo: 'TO', logoColor: 'hsl(22, 89%, 48%)', connected: false, popular: true, setupSteps: [{ title: t('marketplace.toast.step1.title', 'Access Toast Developer Portal'), description: t('marketplace.toast.step1.desc', 'Log in to your Toast account and navigate to Settings > Integrations > Developer Portal.') }, { title: t('marketplace.toast.step2.title', 'Create an API Token'), description: t('marketplace.toast.step2.desc', 'Under API Access, generate a new token with read/write permissions.') }, { title: t('marketplace.toast.step3.title', 'Copy Restaurant GUID'), description: t('marketplace.toast.step3.desc', 'Find your Restaurant GUID in Toast under Settings > Restaurant Information.') }, { title: t('marketplace.toast.step4.title', 'Connect to RestroAgent'), description: t('marketplace.toast.step4.desc', 'Enter your API Token and Restaurant GUID and click Connect.') }, { title: t('marketplace.toast.step5.title', 'Map Menu Categories'), description: t('marketplace.toast.step5.desc', 'Map your Toast menu categories to RestroAgent categories.') }] },
  { id: 'stripe', name: t('marketplace.stripe.name', 'Stripe Payments'), description: t('marketplace.stripe.description', 'Accept online payments, manage subscriptions, and process refunds through Stripe.'), category: 'Payment Gateways', logo: 'ST', logoColor: 'hsl(270, 60%, 50%)', connected: false, setupSteps: [{ title: t('marketplace.stripe.step1.title', 'Log in to Stripe Dashboard'), description: t('marketplace.stripe.step1.desc', 'Go to dashboard.stripe.com and navigate to Developers > API Keys.') }, { title: t('marketplace.stripe.step2.title', 'Copy Publishable & Secret Keys'), description: t('marketplace.stripe.step2.desc', 'Copy both your Publishable Key and Secret Key.') }, { title: t('marketplace.stripe.step3.title', 'Add Keys to RestroAgent'), description: t('marketplace.stripe.step3.desc', 'Paste both keys in the Stripe connection form.') }, { title: t('marketplace.stripe.step4.title', 'Configure Webhook Endpoint'), description: t('marketplace.stripe.step4.desc', 'In Stripe, add a webhook endpoint pointing to your RestroAgent webhook URL.') }, { title: t('marketplace.stripe.step5.title', 'Test the Integration'), description: t('marketplace.stripe.step5.desc', 'Use Stripe test mode to process a test payment.') }] },
  { id: 'doordash', name: t('marketplace.doordash.name', 'DoorDash Drive'), description: t('marketplace.doordash.description', 'Dispatch delivery drivers on-demand through DoorDash Drive for your own online orders.'), category: 'Delivery Platforms', logo: 'DD', logoColor: 'hsl(0, 80%, 50%)', connected: false, popular: true, setupSteps: [{ title: t('marketplace.doordash.step1.title', 'Apply for DoorDash Drive Access'), description: t('marketplace.doordash.step1.desc', 'Visit developer.doordash.com and apply for Drive API access.') }, { title: t('marketplace.doordash.step2.title', 'Get API Key'), description: t('marketplace.doordash.step2.desc', 'Once approved, generate an API key under your application settings.') }, { title: t('marketplace.doordash.step3.title', 'Configure Delivery Zone'), description: t('marketplace.doordash.step3.desc', 'Set your restaurant address and maximum delivery radius.') }, { title: t('marketplace.doordash.step4.title', 'Connect to RestroAgent'), description: t('marketplace.doordash.step4.desc', 'Enter your API key and restaurant address in the DoorDash connection form.') }, { title: t('marketplace.doordash.step5.title', 'Set Dispatch Rules'), description: t('marketplace.doordash.step5.desc', 'Configure when to auto-dispatch and set estimated prep times.') }] },
  { id: 'hubspot', name: t('marketplace.hubspot.name', 'HubSpot CRM'), description: t('marketplace.hubspot.description', 'Sync customer profiles, order history, and AI conversation data to HubSpot.'), category: 'CRM Tools', logo: 'HS', logoColor: 'hsl(22, 89%, 48%)', connected: false, setupSteps: [{ title: t('marketplace.hubspot.step1.title', 'Create a HubSpot Private App'), description: t('marketplace.hubspot.step1.desc', 'In HubSpot, go to Settings > Integrations > Private Apps and create a new app.') }, { title: t('marketplace.hubspot.step2.title', 'Copy Access Token'), description: t('marketplace.hubspot.step2.desc', 'Copy the access token generated for your private app.') }, { title: t('marketplace.hubspot.step3.title', 'Connect to RestroAgent'), description: t('marketplace.hubspot.step3.desc', 'Enter your API Key and Audience ID in the HubSpot connection form.') }, { title: t('marketplace.hubspot.step4.title', 'Set Subscription Rules'), description: t('marketplace.hubspot.step4.desc', 'Choose which customer actions trigger a Mailchimp subscription.') }] },
  { id: 'twilio', name: t('marketplace.twilio.name', 'Twilio SMS'), description: t('marketplace.twilio.description', 'Send SMS notifications for order confirmations, booking reminders, and customer alerts via Twilio.'), category: 'Messaging', logo: 'TW', logoColor: 'hsl(0, 70%, 45%)', connected: false, setupSteps: [{ title: t('marketplace.twilio.step1.title', 'Create a Twilio Account'), description: t('marketplace.twilio.step1.desc', 'Sign up at twilio.com and verify your phone number.') }, { title: t('marketplace.twilio.step2.title', 'Get Account SID and Auth Token'), description: t('marketplace.twilio.step2.desc', 'From the Twilio Console dashboard, copy your Account SID and Auth Token.') }, { title: t('marketplace.twilio.step3.title', 'Purchase a Phone Number'), description: t('marketplace.twilio.step3.desc', 'Buy a Twilio phone number to use as the sender for SMS messages.') }, { title: t('marketplace.twilio.step4.title', 'Connect to RestroAgent'), description: t('marketplace.twilio.step4.desc', 'Enter your Account SID, Auth Token, and Twilio phone number.') }] },
  { id: 'google-analytics', name: t('marketplace.google-analytics.name', 'Google Analytics'), description: t('marketplace.google-analytics.description', 'Track customer journeys, conversion funnels, and AI agent performance in Google Analytics 4.'), category: 'Analytics', logo: 'GA', logoColor: 'hsl(210, 100%, 40%)', connected: false, setupSteps: [{ title: t('marketplace.ga.step1.title', 'Create a GA4 Property'), description: t('marketplace.ga.step1.desc', 'In Google Analytics, create a new GA4 property for your restaurant.') }, { title: t('marketplace.ga.step2.title', 'Get Measurement ID'), description: t('marketplace.ga.step2.desc', 'Go to Admin > Data Streams > Web and copy your Measurement ID.') }, { title: t('marketplace.ga.step3.title', 'Enter Measurement ID'), description: t('marketplace.ga.step3.desc', 'Paste your Measurement ID in the Google Analytics connection form.') }, { title: t('marketplace.ga.step4.title', 'Verify Data Flow'), description: t('marketplace.ga.step4.desc', 'Use the GA4 DebugView to confirm events are being received.') }] },
  { id: 'mailchimp', name: t('marketplace.mailchimp.name', 'Mailchimp'), description: t('marketplace.mailchimp.description', 'Automatically add customers to Mailchimp lists and trigger email campaigns based on order behavior.'), category: 'CRM Tools', logo: 'MC', logoColor: 'hsl(45, 100%, 35%)', connected: false, setupSteps: [{ title: t('marketplace.mailchimp.step1.title', 'Get Mailchimp API Key'), description: t('marketplace.mailchimp.step1.desc', 'In Mailchimp, go to Account > Extras > API Keys and generate a new key.') }, { title: t('marketplace.mailchimp.step2.title', 'Find Your Audience ID'), description: t('marketplace.mailchimp.step2.desc', 'Navigate to Audience > All Contacts > Settings to find your Audience ID.') }, { title: t('marketplace.mailchimp.step3.title', 'Connect in RestroAgent'), description: t('marketplace.mailchimp.step3.desc', 'Enter your API Key and Audience ID in the Mailchimp connection form.') }, { title: t('marketplace.hubspot.step4.title', 'Set Subscription Rules'), description: t('marketplace.hubspot.step4.desc', 'Choose which customer actions trigger a Mailchimp subscription.') }] },
];


const categoryIcons: Record<string, React.ReactNode> = {
  'POS Systems': <ShoppingCart size={14} />,
  'Payment Gateways': <CreditCard size={14} />,
  'Delivery Platforms': <Truck size={14} />,
  'CRM Tools': <Users size={14} />,
  'Messaging': <MessageSquare size={14} />,
  'Analytics': <BarChart3 size={14} />,
};

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

const getCurrencies = (t: TFn) => [
  { code: 'USD', symbol: '$', name: t('currency.USD', 'US Dollar') },
  { code: 'EUR', symbol: '€', name: t('currency.EUR', 'Euro') },
  { code: 'GBP', symbol: '£', name: t('currency.GBP', 'British Pound') },
  { code: 'INR', symbol: '₹', name: t('currency.INR', 'Indian Rupee') },
  { code: 'AED', symbol: 'AED', name: t('currency.AED', 'UAE Dirham') },
  { code: 'SAR', symbol: 'SAR', name: t('currency.SAR', 'Saudi Riyal') },
  { code: 'CAD', symbol: 'CA$', name: t('currency.CAD', 'Canadian Dollar') },
  { code: 'AUD', symbol: 'A$', name: t('currency.AUD', 'Australian Dollar') },
  { code: 'SGD', symbol: 'S$', name: t('currency.SGD', 'Singapore Dollar') },
  { code: 'MYR', symbol: 'RM', name: t('currency.MYR', 'Malaysian Ringgit') },
  { code: 'THB', symbol: '฿', name: t('currency.THB', 'Thai Baht') },
  { code: 'PHP', symbol: '₱', name: t('currency.PHP', 'Philippine Peso') },
  { code: 'IDR', symbol: 'Rp', name: t('currency.IDR', 'Indonesian Rupiah') },
  { code: 'JPY', symbol: '¥', name: t('currency.JPY', 'Japanese Yen') },
  { code: 'KRW', symbol: '₩', name: t('currency.KRW', 'South Korean Won') },
  { code: 'CNY', symbol: '¥', name: t('currency.CNY', 'Chinese Yuan') },
  { code: 'HKD', symbol: 'HK$', name: t('currency.HKD', 'Hong Kong Dollar') },
  { code: 'TWD', symbol: 'NT$', name: t('currency.TWD', 'Taiwan Dollar') },
  { code: 'NZD', symbol: 'NZ$', name: t('currency.NZD', 'New Zealand Dollar') },
  { code: 'ZAR', symbol: 'R', name: t('currency.ZAR', 'South African Rand') },
  { code: 'BRL', symbol: 'R$', name: t('currency.BRL', 'Brazilian Real') },
  { code: 'MXN', symbol: 'MX$', name: t('currency.MXN', 'Mexican Peso') },
  { code: 'CLP', symbol: 'CL$', name: t('currency.CLP', 'Chilean Peso') },
  { code: 'COP', symbol: 'CO$', name: t('currency.COP', 'Colombian Peso') },
  { code: 'ARS', symbol: 'AR$', name: t('currency.ARS', 'Argentine Peso') },
  { code: 'PEN', symbol: 'S/.', name: t('currency.PEN', 'Peruvian Sol') },
  { code: 'TRY', symbol: '₺', name: t('currency.TRY', 'Turkish Lira') },
  { code: 'EGP', symbol: 'E£', name: t('currency.EGP', 'Egyptian Pound') },
  { code: 'NGN', symbol: '₦', name: t('currency.NGN', 'Nigerian Naira') },
  { code: 'KES', symbol: 'KSh', name: t('currency.KES', 'Kenyan Shilling') },
  { code: 'GHS', symbol: 'GH₵', name: t('currency.GHS', 'Ghanaian Cedi') },
  { code: 'PKR', symbol: 'Rs', name: t('currency.PKR', 'Pakistani Rupee') },
  { code: 'BDT', symbol: '৳', name: t('currency.BDT', 'Bangladeshi Taka') },
  { code: 'LKR', symbol: 'Rs', name: t('currency.LKR', 'Sri Lankan Rupee') },
  { code: 'NPR', symbol: 'Rs', name: t('currency.NPR', 'Nepalese Rupee') },
  { code: 'QAR', symbol: 'QR', name: t('currency.QAR', 'Qatari Riyal') },
  { code: 'KWD', symbol: 'KD', name: t('currency.KWD', 'Kuwaiti Dinar') },
  { code: 'BHD', symbol: 'BD', name: t('currency.BHD', 'Bahraini Dinar') },
  { code: 'OMR', symbol: 'OMR', name: t('currency.OMR', 'Omani Rial') },
  { code: 'JOD', symbol: 'JD', name: t('currency.JOD', 'Jordanian Dinar') },
  { code: 'CHF', symbol: 'CHF', name: t('currency.CHF', 'Swiss Franc') },
  { code: 'SEK', symbol: 'kr', name: t('currency.SEK', 'Swedish Krona') },
  { code: 'NOK', symbol: 'kr', name: t('currency.NOK', 'Norwegian Krone') },
  { code: 'DKK', symbol: 'kr', name: t('currency.DKK', 'Danish Krone') },
  { code: 'PLN', symbol: 'zł', name: t('currency.PLN', 'Polish Zloty') },
  { code: 'CZK', symbol: 'Kč', name: t('currency.CZK', 'Czech Koruna') },
  { code: 'HUF', symbol: 'Ft', name: t('currency.HUF', 'Hungarian Forint') },
  { code: 'RON', symbol: 'lei', name: t('currency.RON', 'Romanian Leu') },
  { code: 'RUB', symbol: '₽', name: t('currency.RUB', 'Russian Ruble') },
  { code: 'UAH', symbol: '₴', name: t('currency.UAH', 'Ukrainian Hryvnia') },
  { code: 'ILS', symbol: '₪', name: t('currency.ILS', 'Israeli Shekel') },
  { code: 'VND', symbol: '₫', name: t('currency.VND', 'Vietnamese Dong') },
  { code: 'MMK', symbol: 'K', name: t('currency.MMK', 'Myanmar Kyat') },
  { code: 'KHR', symbol: '៛', name: t('currency.KHR', 'Cambodian Riel') },
  { code: 'LAK', symbol: '₭', name: t('currency.LAK', 'Lao Kip') },
];

export default function RestaurantSettingsPage() {
  const { t, currentLang, setLang, activeLanguages } = useLanguage();
  const currencies = getCurrencies(t);
  usePageHeader(t('restaurantSettings.title', "Restaurant Settings"), t('restaurantSettings.subtitle', "Profile, hours, notifications, and integrations"));
  const { userRecord, refreshUserRecord, sessionBranchId } = useAuth();
  const [activeTab, setActiveTab] = useState<Tab>(() => {
    if (typeof window === 'undefined') return 'profile';
    const q = new URLSearchParams(window.location.search).get('tab');
    const allowed: Tab[] = ['profile', 'hours', 'alert-settings', 'billing', 'notifications', 'templates', 'webhooks', 'rest-api', 'provider-keys', 'email-smtp'];
    return (q && (allowed as string[]).includes(q) ? (q as Tab) : 'profile');
  });
  const [apiHost, setApiHost] = useState<string>('');
  useEffect(() => {
    if (typeof window !== 'undefined') setApiHost(window.location.host);
  }, []);
  const apiBaseUrlDisplay = apiHost ? `${apiHost}/api` : 'this-deployment/api';
  const apiBaseUrlFull = apiHost ? `${window.location.protocol}//${apiHost}/api/v1` : '/api/v1';
  const [hours, setHours] = useState(days(t).map(d => ({ day: d, open: d !== t('common.days.monday', 'Monday'), from: '11:00', to: '22:00' })));
  const toggleDay = (idx: number) => setHours(prev => prev.map((h, i) => i === idx ? { ...h, open: !h.open } : h));

  const [selectedBranchTimezone, setSelectedBranchTimezone] = useState<string | null>(null);
  useEffect(() => {
    if (!sessionBranchId) {
      setSelectedBranchTimezone(null);
      return;
    }
    let cancelled = false;
    getBranch(sessionBranchId)
      .then(({ branch }) => { if (!cancelled) setSelectedBranchTimezone(branch.timezone || null); })
      .catch(() => { if (!cancelled) setSelectedBranchTimezone(null); });
    return () => { cancelled = true; };
  }, [sessionBranchId]);

  const currentLogoUrl: string | null = userRecord?.restaurants?.logo_url || null;
  const currentCurrency: string | null = userRecord?.restaurants?.currency || null;
  const currencyLocked: boolean = !!userRecord?.restaurants?.currency_locked;
  const [logoPreview, setLogoPreview] = useState<string | null>(null);
  const [logoUploading, setLogoUploading] = useState(false);
  const logoInputRef = useRef<HTMLInputElement>(null);
  const [selectedCurrency, setSelectedCurrency] = useState<string>('USD');
  const [currencySaving, setCurrencySaving] = useState(false);
  const [currencyError, setCurrencyError] = useState<string | null>(null);

  const [profileName, setProfileName] = useState('');
  const [profileCuisine, setProfileCuisine] = useState('');
  const [profilePhone, setProfilePhone] = useState('');
  const [profileAddress, setProfileAddress] = useState('');
  const [profileDescription, setProfileDescription] = useState('');
  const [profileSeating, setProfileSeating] = useState('');
  const [profileBookingDuration, setProfileBookingDuration] = useState('90');
  const [profileBookingBuffer, setProfileBookingBuffer] = useState('15');
  const [profileLowStockThreshold, setProfileLowStockThreshold] = useState('5');
  const [profileSaving, setProfileSaving] = useState(false);
  const [profileLoaded, setProfileLoaded] = useState(false);

  useEffect(() => {
    if (userRecord?.restaurants && !profileLoaded) {
      const r = userRecord.restaurants;
      setProfileName(r.name || '');
      setProfileCuisine(r.cuisine_type || '');
      setProfilePhone(r.phone || '');
      setProfileAddress(r.address || '');
      setProfileDescription(r.description || '');
      setProfileSeating(r.seating_capacity != null ? String(r.seating_capacity) : '');
      setProfileLoaded(true);
    }
  }, [userRecord, profileLoaded]);

  // Booking defaults aren't on userRecord — fetch them from the profile API.
  useEffect(() => {
    let cancelled = false;
    fetch('/api/restaurant/profile', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (cancelled || !data?.profile) return;
        const p = data.profile as { default_booking_duration_min?: number; default_booking_buffer_min?: number; default_low_stock_threshold?: number };
        if (p.default_booking_duration_min != null) setProfileBookingDuration(String(p.default_booking_duration_min));
        if (p.default_booking_buffer_min != null) setProfileBookingBuffer(String(p.default_booking_buffer_min));
        if (p.default_low_stock_threshold != null) setProfileLowStockThreshold(String(p.default_low_stock_threshold));
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  const handleProfileSave = async () => {
    if (!profileName.trim()) {
      toast.error(t('restaurantSettings.profile.nameRequired', 'Restaurant name is required'));
      return;
    }
    setProfileSaving(true);
    try {
      const res = await fetch('/api/restaurant/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: profileName.trim(),
          cuisine_type: profileCuisine.trim() || null,
          phone: profilePhone.trim() || null,
          address: profileAddress.trim() || null,
          description: profileDescription.trim() || null,
          seating_capacity: profileSeating ? Number(profileSeating) : null,
          default_booking_duration_min: profileBookingDuration ? Number(profileBookingDuration) : 90,
          default_booking_buffer_min: profileBookingBuffer ? Number(profileBookingBuffer) : 15,
          default_low_stock_threshold: profileLowStockThreshold ? Number(profileLowStockThreshold) : 5,
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Failed to save');
      }
      await refreshUserRecord();
      toast.success(t('restaurantSettings.profile.savedSuccessfully', 'Profile saved successfully'));
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : t('restaurantSettings.profile.failedToSave', 'Failed to save profile');
      toast.error(message);
    } finally {
      setProfileSaving(false);
    }
  };

  const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) { alert('File too large. Maximum 2 MB.'); return; }
    const previewUrl = URL.createObjectURL(file);
    setLogoPreview(previewUrl);
    setLogoUploading(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch('/api/restaurant/logo-upload', { method: 'POST', body: fd });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Upload failed');
      await refreshUserRecord();
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Upload failed');
      setLogoPreview(null);
    } finally {
      setLogoUploading(false);
    }
  };

  const handleCurrencySave = async () => {
    if (!selectedCurrency) return;
    setCurrencySaving(true);
    setCurrencyError(null);
    try {
      const res = await fetch('/api/restaurant/currency', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ currency: selectedCurrency }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Save failed');
      await refreshUserRecord();
      setSelectedCurrency('');
    } catch (err) {
      setCurrencyError(err instanceof Error ? err.message : 'Save failed');
    } finally {
      setCurrencySaving(false);
    }
  };

  // Alert Settings state
  const defaultAlertSettings = { soundEnabled: true, volume: 70, autoDismiss: 30, showOrders: true, showBookings: true, showAiEscalations: true, browserNotifications: false };
  const [alertSettings, setAlertSettings] = useState(defaultAlertSettings);
  const [alertSaved, setAlertSaved] = useState(false);
  const [showDemo, setShowDemo] = useState(false);
  useEffect(() => {
    if (activeTab !== 'alert-settings') return;
    fetch('/api/alert-settings', { credentials: 'include' })
      .then(r => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
      .then(d => { if (d?.settings) setAlertSettings(d.settings); })
      .catch(() => toast.error(t('restaurantSettings.alerts.failedToLoad', 'Failed to load alert settings')));
  }, [activeTab, t]);
  const updateAlert = (key: string, value: boolean | number) => setAlertSettings(prev => ({ ...prev, [key]: value }));
  const handleAlertSave = async () => {
    try {
      await fetch('/api/alert-settings', { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(alertSettings) });
      setAlertSaved(true); setTimeout(() => setAlertSaved(false), 2000);
    } catch { toast.error(t('restaurantSettings.alerts.failedToSave', 'Failed to save alert settings')); }
  };

  // Billing state (API-backed)
  const [billingTab, setBillingTab] = useState<BillingTab>('overview');
  const [billingCycle, setBillingCycle] = useState<'monthly' | 'annual'>('monthly');
  const [billingCurrency, setBillingCurrency] = useState('USD');
  const [confirmPlan, setConfirmPlan] = useState<string | null>(null);
  const [checkoutLoading, setCheckoutLoading] = useState(false);
  const [billingInvoices, setBillingInvoices] = useState<StripeInvoice[]>([]);
  const [invoicesLoading, setInvoicesLoading] = useState(false);
  const [invoiceSortField, setInvoiceSortField] = useState<'date' | 'amount' | 'status'>('date');
  const [invoiceSortDir, setInvoiceSortDir] = useState<'asc' | 'desc'>('desc');
  const [showSampleInvoice, setShowSampleInvoice] = useState(false);
  const [billingSubscription, setBillingSubscription] = useState<BillingSubscription | null>(null);
  const [billingUsage, setBillingUsage] = useState<BillingUsage | null>(null);
  const [billingPlans, setBillingPlans] = useState<BillingPlan[]>([]);
  const [billingLoading, setBillingLoading] = useState(false);
  const [activeGateways, setActiveGateways] = useState<GatewayInfo[]>([]);
  const [billingContactEmail, setBillingContactEmail] = useState('');
  const [billingContactSaving, setBillingContactSaving] = useState(false);
  const [billingContactSaved, setBillingContactSaved] = useState(false);
  const [promoCode, setPromoCode] = useState('');
  const [promoValidating, setPromoValidating] = useState(false);
  const [promoValidated, setPromoValidated] = useState<{ discountedAmount: number; originalAmount: number; currency: string; description: string } | null>(null);
  const [prorationPreview, setProrationPreview] = useState<{ prorationAmount: number | null; currency: string; lines: { description: string; amount: number; currency: string }[]; staticPreview?: boolean } | null>(null);
  const [prorationLoading, setProrationLoading] = useState(false);

  useEffect(() => {
    if (activeTab !== 'billing') return;
    setBillingLoading(true);
    Promise.all([getSubscription(), getUsage(), fetchBillingPlans(), getActiveGateways(), getBillingContact()])
      .then(([sub, usg, pls, gws, contactEmail]) => {
        setBillingSubscription(sub);
        setBillingUsage(usg);
        setBillingPlans(pls);
        const gwList = gws ?? [];
        setActiveGateways(gwList);
        if (gwList.length > 0) setBillingCurrency(gwList[0].currency);
        setBillingContactEmail(contactEmail ?? sub?.billingContactEmail ?? '');
      })
      .catch(() => {})
      .finally(() => setBillingLoading(false));
  }, [activeTab]);

  useEffect(() => {
    if (activeTab !== 'billing' || !billingCurrency) return;
    fetchBillingPlans(billingCurrency)
      .then(pls => setBillingPlans(pls))
      .catch(() => {});
  }, [billingCurrency, activeTab]);

  useEffect(() => {
    if (!confirmPlan) { setProrationPreview(null); return; }
    const gw = activeGateways.find(g => g.currency === billingCurrency) ?? activeGateways.find(g => g.id === 'stripe');
    if (gw?.id !== 'stripe') { setProrationPreview(null); return; }
    setProrationLoading(true);
    fetchProrationPreview(confirmPlan, billingCycle)
      .then(preview => setProrationPreview(preview.noSubscription ? null : preview))
      .catch(() => setProrationPreview(null))
      .finally(() => setProrationLoading(false));
  }, [confirmPlan, billingCycle, activeGateways, billingCurrency]);

  useEffect(() => {
    if (activeTab !== 'billing' || billingTab !== 'invoices') return;
    setInvoicesLoading(true);
    listInvoices()
      .then(invs => setBillingInvoices(invs))
      .catch(() => setBillingInvoices([]))
      .finally(() => setInvoicesLoading(false));
  }, [activeTab, billingTab]);

  const bPlanName = billingSubscription?.planName ?? 'No Plan';
  const bPlanPrice = billingSubscription?.priceMonthly ?? 0;
  const bPlanLimits = billingSubscription?.limits ?? {};
  const overviewCurrencySymbol = getCurrencies(t).find(c => c.code === billingCurrency)?.symbol ?? billingCurrency;
  const bPlanColor = planColors[bPlanName] ?? 'hsl(var(--primary))';
  const bUsageEntries = billingUsage ? [
    { key: 'conversations', used: billingUsage.conversations },
    { key: 'voiceMinutes', used: billingUsage.voiceMinutes },
    { key: 'branches', used: billingUsage.branches },
    { key: 'apiCalls', used: billingUsage.apiCalls },
  ] : [];

  // Notification preferences state (API-backed)
  const [notifPrefs, setNotifPrefs] = useState<NotifPreference[]>([
    { id: 'new-order', category: 'Orders', event: 'New Order Received', description: 'When a customer places a new order through any channel', inApp: true, email: false, sms: false },
    { id: 'order-cancelled', category: 'Orders', event: 'Order Cancelled', description: 'When a customer cancels an existing order', inApp: true, email: true, sms: false },
    { id: 'new-booking', category: 'Table Bookings', event: 'New Booking', description: 'When a customer makes a new table reservation', inApp: true, email: false, sms: false },
    { id: 'booking-cancelled', category: 'Table Bookings', event: 'Booking Cancelled', description: 'When a customer cancels a reservation', inApp: true, email: true, sms: false },
    { id: 'ai-escalation', category: 'AI Agent', event: 'AI Escalation', description: 'When the AI escalates to staff', inApp: true, email: false, sms: true },
    { id: 'system-update', category: 'System', event: 'Platform Update', description: 'When a new platform version is deployed', inApp: true, email: true, sms: false },
    { id: 'billing-failed', category: 'Billing', event: 'Payment Failed', description: 'When a billing payment fails', inApp: true, email: true, sms: true },
  ]);
  const [notifLoading, setNotifLoading] = useState(false);
  const [notifSaving, setNotifSaving] = useState(false);
  const [notifSaved, setNotifSaved] = useState(false);

  useEffect(() => {
    if (activeTab !== 'notifications') return;
    setNotifLoading(true);
    fetchNotifPrefs()
      .then(prefs => { if (prefs && Array.isArray(prefs) && prefs.length > 0) setNotifPrefs(prefs); })
      .catch(() => {})
      .finally(() => setNotifLoading(false));
  }, [activeTab]);

  const toggleNotifPref = (id: string, channel: 'inApp' | 'email' | 'sms') => {
    setNotifPrefs(prev => prev.map(p => p.id === id ? { ...p, [channel]: !p[channel] } : p));
    setNotifSaved(false);
  };

  const handleNotifSave = async () => {
    setNotifSaving(true);
    try { await saveNotifPrefs(notifPrefs); setNotifSaved(true); setTimeout(() => setNotifSaved(false), 2000); } catch {} finally { setNotifSaving(false); }
  };

  // Templates state (API-backed)
  const [activeTemplate, setActiveTemplate] = useState<TemplateKey>('order-confirmation');
  const [activeChannel, setActiveChannel] = useState<Channel>('email');
  const [templateContents, setTemplateContents] = useState<Record<TemplateKey, Record<Channel, string>>>(JSON.parse(JSON.stringify(defaultTemplates)));
  const [savedState, setSavedState] = useState<Record<string, boolean>>({});
  const [copiedTag, setCopiedTag] = useState<string | null>(null);
  const [showPreview, setShowPreview] = useState(true);
  const [templateSaving, setTemplateSaving] = useState(false);
  const currentTpl = templatesList(t).find(tpl => tpl.id === activeTemplate)!;
  const currentContent = templateContents[activeTemplate][activeChannel];
  const handleContentChange = (val: string) => { setTemplateContents(prev => ({ ...prev, [activeTemplate]: { ...prev[activeTemplate], [activeChannel]: val } })); setSavedState(prev => ({ ...prev, [`${activeTemplate}-${activeChannel}`]: false })); };
  const handleInsertTag = (tag: string) => setTemplateContents(prev => ({ ...prev, [activeTemplate]: { ...prev[activeTemplate], [activeChannel]: prev[activeTemplate][activeChannel] + tag } }));
  const handleTemplateSave = async () => {
    setTemplateSaving(true);
    try {
      await saveServerTemplates([{ templateKey: activeTemplate, channel: activeChannel, content: currentContent }]);
      setSavedState(prev => ({ ...prev, [`${activeTemplate}-${activeChannel}`]: true }));
    } catch {} finally { setTemplateSaving(false); }
  };
  const handleTemplateReset = () => { setTemplateContents(prev => ({ ...prev, [activeTemplate]: { ...prev[activeTemplate], [activeChannel]: defaultTemplates[activeTemplate][activeChannel] } })); setSavedState(prev => ({ ...prev, [`${activeTemplate}-${activeChannel}`]: false })); };
  const handleCopyTag = (tag: string) => { navigator.clipboard.writeText(tag).catch(() => {}); setCopiedTag(tag); setTimeout(() => setCopiedTag(null), 1500); };
  const isSaved = savedState[`${activeTemplate}-${activeChannel}`];

  useEffect(() => {
    if (activeTab !== 'templates') return;
    fetchServerTemplates()
      .then(serverTemplates => {
        if (serverTemplates.length > 0) {
          const merged = JSON.parse(JSON.stringify(defaultTemplates));
          serverTemplates.forEach(st => { if (merged[st.templateKey]?.[st.channel] !== undefined) merged[st.templateKey][st.channel] = st.content; });
          setTemplateContents(merged);
        }
      })
      .catch(() => {});
  }, [activeTab]);

  // Webhooks state
  const [webhooks, setWebhooks] = useState<ApiWebhook[]>([]);
  const [webhooksLoading, setWebhooksLoading] = useState(false);
  const [webhooksError, setWebhooksError] = useState<string | null>(null);
  const [webhookSaving, setWebhookSaving] = useState(false);
  const [showAddWebhook, setShowAddWebhook] = useState(false);
  const [revealedWebhookKeys, setRevealedWebhookKeys] = useState<Set<string>>(new Set());
  const [expandedLogs, setExpandedLogs] = useState(false);
  const [deliveryLogs, setDeliveryLogs] = useState<DeliveryLog[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const [newWebhook, setNewWebhook] = useState({ url: '', events: [] as string[], active: true });
  const [settingsWebhookErrors, setSettingsWebhookErrors] = useState<{ url?: string; events?: string }>({});
  const [settingsWebhookTouched, setSettingsWebhookTouched] = useState<Record<string, boolean>>({});

  useEffect(() => {
    if (activeTab !== 'webhooks') return;
    setWebhooksLoading(true);
    listWebhooks()
      .then(res => { setWebhooks(res.webhooks); setWebhooksError(null); })
      .catch(e => setWebhooksError(e.message))
      .finally(() => setWebhooksLoading(false));
  }, [activeTab]);

  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 validateSettingsWebhookUrl = (url: string): string | undefined => {
    if (!url.trim()) return 'Endpoint URL is required';
    try {
      const u = new URL(url);
      if (!['http:', 'https:'].includes(u.protocol)) return 'URL must use HTTP or HTTPS protocol';
    } catch {
      return 'Please enter a valid URL (e.g. https://your-app.com/webhooks)';
    }
  };

  const validateSettingsWebhookEvents = (events: string[]): string | undefined => {
    if (events.length === 0) return 'Please select at least one event to subscribe to';
  };

  const handleSettingsWebhookSave = async () => {
    const urlErr = validateSettingsWebhookUrl(newWebhook.url);
    const eventsErr = validateSettingsWebhookEvents(newWebhook.events);
    setSettingsWebhookErrors({ url: urlErr, events: eventsErr });
    setSettingsWebhookTouched({ url: true, events: true });
    if (urlErr || eventsErr) return;
    setWebhookSaving(true);
    try {
      const res = await createWebhook({ endpoint_url: newWebhook.url, events: newWebhook.events });
      setWebhooks(prev => [res.webhook, ...prev]);
      setShowAddWebhook(false);
      setNewWebhook({ url: '', events: [], active: true });
      setSettingsWebhookErrors({});
      setSettingsWebhookTouched({});
    } catch (e) {
      setWebhooksError(e instanceof Error ? e.message : 'Failed to save webhook');
    } finally {
      setWebhookSaving(false);
    }
  };

  const handleDeleteWebhook = async (id: string) => {
    try {
      await apiDeleteWebhook(id);
      setWebhooks(prev => prev.filter(w => w.id !== id));
    } catch (e) {
      setWebhooksError(e instanceof Error ? e.message : 'Failed to delete webhook');
    }
  };

  const handleToggleWebhookStatus = async (id: string, currentStatus: string) => {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    try {
      const res = await apiUpdateWebhook(id, { status: newStatus });
      setWebhooks(prev => prev.map(w => w.id === id ? res.webhook : w));
    } catch (e) {
      setWebhooksError(e instanceof Error ? e.message : 'Failed to update webhook status');
    }
  };

  const handleSettingsWebhookUrlChange = (url: string) => {
    setNewWebhook(prev => ({ ...prev, url }));
    if (settingsWebhookTouched.url) setSettingsWebhookErrors(prev => ({ ...prev, url: validateSettingsWebhookUrl(url) }));
  };

  const toggleWebhookKey = (id: string) => setRevealedWebhookKeys(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const toggleWebhookEvent = (event: string) => {
    setNewWebhook(prev => ({ ...prev, events: prev.events.includes(event) ? prev.events.filter(e => e !== event) : [...prev.events, event] }));
    if (settingsWebhookTouched.events) {
      const newEvents = newWebhook.events.includes(event)
        ? newWebhook.events.filter(e => e !== event)
        : [...newWebhook.events, event];
      setSettingsWebhookErrors(prev => ({ ...prev, events: validateSettingsWebhookEvents(newEvents) }));
    }
  };

  // REST API state
  const [apiKeys, setApiKeys] = useState<ApiKeyData[]>([]);
  const [apiKeysLoading, setApiKeysLoading] = useState(false);
  const [apiKeysError, setApiKeysError] = useState<string | null>(null);
  const [newKeyBanner, setNewKeyBanner] = useState<string | null>(null);
  const [apiKeySaving, setApiKeySaving] = useState(false);
  const [revealedApiKeys, setRevealedApiKeys] = useState<Set<string>>(new Set());
  const [showAddApiKey, setShowAddApiKey] = useState(false);
  const [showDocs, setShowDocs] = useState(true);
  const [newApiKey, setNewApiKey] = useState({ name: '', permissions: [] as string[] });
  const [copiedKeyId, setCopiedKeyId] = useState<string | null>(null);
  const [usageData, setUsageData] = useState<{ day: string; calls: number }[]>([]);

  useEffect(() => {
    if (activeTab !== 'rest-api') return;
    setApiKeysLoading(true);
    Promise.all([
      listApiKeys(),
      getApiUsageChart(),
    ]).then(([keysRes, chartRes]) => {
      setApiKeys(keysRes.keys); setApiKeysError(null);
      setUsageData(chartRes);
    }).catch(e => setApiKeysError(e.message))
      .finally(() => setApiKeysLoading(false));
  }, [activeTab]);

  const toggleApiKeyReveal = (id: string) => setRevealedApiKeys(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const copyApiKey = (id: string, key: string) => { navigator.clipboard.writeText(key).catch(() => {}); setCopiedKeyId(id); setTimeout(() => setCopiedKeyId(null), 2000); };
  const revokeApiKey = async (id: string) => {
    try {
      const res = await apiRevokeApiKey(id);
      setApiKeys(prev => prev.map(k => k.id === id ? { ...k, ...res.key } : k));
    } catch (e) {
      setApiKeysError(e instanceof Error ? e.message : 'Failed to revoke key');
    }
  };
  const togglePermission = (perm: string) => setNewApiKey(prev => ({ ...prev, permissions: prev.permissions.includes(perm) ? prev.permissions.filter(p => p !== perm) : [...prev.permissions, perm] }));
  const totalApiCalls = apiKeys.filter(k => k.status === 'active').reduce((s, k) => s + (k.callsThisMonth ?? 0), 0);
  const handleGenerateApiKey = async () => {
    if (!newApiKey.name.trim()) return;
    setApiKeySaving(true);
    try {
      const res = await apiCreateApiKey({ name: newApiKey.name, permissions: newApiKey.permissions });
      setApiKeys(prev => [res.key, ...prev]);
      setNewKeyBanner(res.key.key ?? null);
      setShowAddApiKey(false);
      setNewApiKey({ name: '', permissions: [] });
    } catch (e) {
      setApiKeysError(e instanceof Error ? e.message : 'Failed to generate key');
    } finally {
      setApiKeySaving(false);
    }
  };

  const canManageSmtp = userRecord?.role === 'owner' || userRecord?.role === 'manager';
  const tabs_list: { key: Tab; label: string }[] = [
    { key: 'profile', label: t('restaurantSettings.tabs.profile', 'Profile') },
    { key: 'hours', label: t('restaurantSettings.tabs.hours', 'Hours') },
    { key: 'alert-settings', label: t('restaurantSettings.tabs.alerts', 'Alert Settings') },
    { key: 'billing', label: t('restaurantSettings.tabs.billing', 'Billing') },
    { key: 'notifications', label: t('restaurantSettings.tabs.notifications', 'Notifications') },
    { key: 'templates', label: t('restaurantSettings.tabs.templates', 'Templates') },
    { key: 'webhooks', label: t('restaurantSettings.tabs.webhooks', 'Webhooks') },
    { key: 'rest-api', label: t('restaurantSettings.tabs.restApi', 'Rest API') },
    { key: 'provider-keys', label: t('restaurantSettings.tabs.providerKeys', 'AI Keys') },
    ...(canManageSmtp ? [{ key: 'email-smtp' as Tab, label: t('restaurantSettings.tabs.emailSmtp', 'Email (SMTP)') }] : []),
  ];

  const showSaveButton = ['profile', 'hours', 'notifications'].includes(activeTab);

  return (
    <>
      {/* Tab Bar */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex flex-wrap gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          {tabs_list.map(t_tab => (
            <button
              key={t_tab.key}
              onClick={() => setActiveTab(t_tab.key)}
              className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === t_tab.key ? 'bg-white shadow-sm' : ''}`}
              style={{ color: activeTab === t_tab.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
            >
              {t_tab.label}
            </button>
          ))}
        </div>
        {showSaveButton && (
          <DemoDisabled>
            <button
              className="btn-primary"
              disabled={activeTab === 'profile' && profileSaving}
              onClick={activeTab === 'profile' ? handleProfileSave : undefined}
            >
              {activeTab === 'profile' && profileSaving ? <RefreshCw size={15} className="animate-spin" /> : <Save size={15} />}
              {activeTab === 'profile' && profileSaving ? t('common.saving', 'Saving...') : t('common.saveChanges', 'Save Changes')}
            </button>
          </DemoDisabled>
        )}
      </div>

      {/* ── Profile ── */}
      {activeTab === 'profile' && (
        <div className="max-w-2xl space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.profile.title', 'Restaurant Profile')}</h3>
            <div className="flex items-center gap-4 mb-5">
              <div className="w-20 h-20 rounded-xl flex items-center justify-center text-3xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                {(logoPreview || currentLogoUrl) ? (
                  <img src={logoPreview || currentLogoUrl!} alt={t('restaurantSettings.profile.logo', 'Logo')} className="w-full h-full object-cover" />
                ) : (
                  <span>🍴</span>
                )}
              </div>
              <div>
                <input ref={logoInputRef} type="file" accept="image/png,image/jpeg,image/gif,image/webp" className="hidden" onChange={handleLogoUpload} />
                <button className="btn-secondary text-sm" onClick={() => logoInputRef.current?.click()} disabled={logoUploading}>
                  {logoUploading ? <RefreshCw size={14} className="animate-spin" /> : <Upload size={14} />}
                  {logoUploading ? t('common.uploading', 'Uploading...') : t('restaurantSettings.profile.uploadLogo', 'Upload Logo')}
                </button>
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.profile.logoSubtitle', 'PNG, JPG, GIF, WEBP up to 2MB')}</p>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="col-span-2">
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.profile.nameLabel', 'Restaurant Name')}</label>
                <input className="input-base" value={profileName} onChange={e => setProfileName(e.target.value)} placeholder={t('restaurantSettings.profile.namePlaceholder', 'Restaurant name')} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.profile.cuisineLabel', 'Cuisine Type')}</label>
                <input className="input-base" value={profileCuisine} onChange={e => setProfileCuisine(e.target.value)} placeholder={t('restaurantSettings.profile.cuisinePlaceholder', 'e.g. Italian, Mexican, Contemporary American')} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.profile.phoneLabel', 'Phone Number')}</label>
                <input className="input-base" value={profilePhone} onChange={e => setProfilePhone(e.target.value)} placeholder={t('restaurantSettings.profile.phonePlaceholder', '+1 (555) 000-0000')} />
              </div>
              <div className="col-span-2">
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.profile.addressLabel', 'Address')}</label>
                <input className="input-base" value={profileAddress} onChange={e => setProfileAddress(e.target.value)} placeholder={t('restaurantSettings.profile.addressPlaceholder', 'Street address, city, state, zip')} />
              </div>
              <div className="col-span-2">
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.profile.descriptionLabel', 'Description')}</label>
                <textarea className="input-base resize-none" rows={3} value={profileDescription} onChange={e => setProfileDescription(e.target.value)} placeholder={t('restaurantSettings.profile.descriptionPlaceholder', 'Describe your restaurant...')} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.profile.seatingLabel', 'Seating Capacity')}</label>
                <input className="input-base" value={profileSeating} onChange={e => setProfileSeating(e.target.value)} type="number" min="0" placeholder="0" />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                  {t('restaurantSettings.profile.bookingDurationLabel', 'Default booking duration (minutes)')}
                </label>
                <input
                  className="input-base"
                  value={profileBookingDuration}
                  onChange={e => setProfileBookingDuration(e.target.value)}
                  type="number"
                  min="15"
                  max="480"
                  step="15"
                  placeholder="90"
                />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('restaurantSettings.profile.bookingDurationHint', 'How long a reservation occupies a table by default.')}
                </p>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                  {t('restaurantSettings.profile.bookingBufferLabel', 'Default turnover buffer (minutes)')}
                </label>
                <input
                  className="input-base"
                  value={profileBookingBuffer}
                  onChange={e => setProfileBookingBuffer(e.target.value)}
                  type="number"
                  min="0"
                  max="60"
                  step="5"
                  placeholder="15"
                />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('restaurantSettings.profile.bookingBufferHint', 'Time kept clear between consecutive bookings on the same table.')}
                </p>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                  {t('restaurantSettings.profile.defaultLowStockThresholdLabel', 'Default low-stock alert threshold')}
                </label>
                <input
                  className="input-base"
                  value={profileLowStockThreshold}
                  onChange={e => setProfileLowStockThreshold(e.target.value)}
                  type="number"
                  min="0"
                  max="1000"
                  step="1"
                  placeholder="5"
                />
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('restaurantSettings.profile.defaultLowStockThresholdHint', 'Used for items without a custom threshold. Set to 0 to disable low-stock alerts by default.')}
                </p>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5 flex items-center gap-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                  {t('restaurantSettings.profile.currencyLabel', 'Currency')}
                  {currencyLocked && <Lock size={11} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                </label>
                {currencyLocked ? (
                  <div>
                    <div className="input-base flex items-center gap-2" style={{ backgroundColor: 'hsl(var(--muted))', cursor: 'not-allowed', opacity: 0.8 }}>
                      <Lock size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
                      <span style={{ color: 'hsl(var(--foreground))' }}>
                        {(() => { const c = currencies.find(c => c.code === currentCurrency); return c ? `${c.code} (${c.symbol}) — ${c.name}` : currentCurrency; })()}
                      </span>
                    </div>
                    <p className="text-xs mt-1 flex items-center gap-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      <Lock size={10} /> {t('restaurantSettings.profile.currencyLocked', 'Currency is locked once set and cannot be changed. Contact support if needed.')}
                    </p>
                  </div>
                ) : (
                  <div>
                    <div className="flex gap-2">
                      <select
                        className="input-base flex-1"
                        value={selectedCurrency}
                        onChange={e => { setSelectedCurrency(e.target.value); setCurrencyError(null); }}
                      >
                        {currencies.map(c => (
                          <option key={c.code} value={c.code}>{c.code} ({c.symbol}) — {c.name}</option>
                        ))}
                      </select>
                      <DemoDisabled>
                        <button
                          className="btn-primary text-sm"
                          onClick={handleCurrencySave}
                          disabled={!selectedCurrency || currencySaving}
                        >
                          {currencySaving ? <RefreshCw size={14} className="animate-spin" /> : <Save size={14} />}
                          {t('common.set', 'Set')}
                        </button>
                      </DemoDisabled>
                    </div>
                    {currencyError && (
                      <p className="text-xs mt-1 flex items-center gap-1" style={{ color: 'hsl(var(--danger))' }}>
                        <Info size={10} /> {currencyError}
                      </p>
                    )}
                    <p className="text-xs mt-1 flex items-center gap-1" style={{ color: 'hsl(22, 89%, 48%)' }}>
                      <Info size={10} /> {t('restaurantSettings.profile.currencyWarning', 'Choose carefully — currency cannot be changed after it is set')}
                    </p>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Language Preference */}
          <div className="card p-5">
            <h3 className="font-semibold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.profile.languageTitle', 'Language Preference')}</h3>
            <p className="text-xs mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.profile.languageSubtitle', 'Choose the language for your dashboard interface')}</p>
            <div className="flex items-center gap-3">
              <Globe size={16} style={{ color: 'hsl(var(--primary))' }} />
              <select
                className="input-base flex-1"
                value={currentLang}
                onChange={e => setLang(e.target.value)}
              >
                {(activeLanguages.length > 0 ? activeLanguages : [{ code: 'en', name: 'English', native_name: 'English', flag_emoji: '🇬🇧', is_rtl: false, is_active: true, is_default: true, display_order: 0 }]).map(l => (
                  <option key={l.code} value={l.code}>{l.flag_emoji ? `${l.flag_emoji} ` : ''}{l.native_name || l.name}</option>
                ))}
              </select>
            </div>
          </div>

          {/* Change Email */}
          {userRecord?.email && (
            <ChangeEmailForm
              currentEmail={userRecord.email}
              onEmailChanged={refreshUserRecord}
            />
          )}
        </div>
      )}

      {/* ── Hours ── */}
      {activeTab === 'hours' && (
        <div className="max-w-lg">
          {selectedBranchTimezone && (
            <p className="text-sm mb-4 flex items-center gap-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Globe size={13} className="shrink-0" />
              {t('restaurantSettings.hours.timezoneNote', 'Hours are in {{tz}}. Change timezone in branch settings.', { tz: selectedBranchTimezone })}
            </p>
          )}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.hours.title', 'Operating Hours')}</h3>
            <div className="space-y-3">
              {hours.map((h, idx) => (
                <div key={h.day} className="flex items-center gap-3">
                  <button onClick={() => toggleDay(idx)}>
                    {h.open ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                  </button>
                  <span className="w-24 text-sm font-medium" style={{ color: h.open ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>{t(`common.days.${h.day.toLowerCase()}`, h.day)}</span>
                  {h.open ? (
                    <div className="flex items-center gap-2 flex-1">
                      <input type="time" className="input-base py-1.5 text-sm" value={h.from} onChange={e => setHours(prev => prev.map((p, i) => i === idx ? { ...p, from: e.target.value } : p))} />
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.to', 'to')}</span>
                      <input type="time" className="input-base py-1.5 text-sm" value={h.to} onChange={e => setHours(prev => prev.map((p, i) => i === idx ? { ...p, to: e.target.value } : p))} />
                    </div>
                  ) : (
                    <span className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.closed', 'Closed')}</span>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ── Alert Settings ── */}
      {activeTab === 'alert-settings' && (
        <div className="max-w-2xl">
          <div className="flex items-center justify-between mb-6">
            <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.alerts.subtitle', 'Configure real-time order and booking alert behavior')}</p>
            <div className="flex gap-2">
              <button className="btn-secondary text-sm" onClick={() => setShowDemo(true)}><TestTube size={15} /> {t('restaurantSettings.alerts.preview', 'Preview Alert')}</button>
              <DemoDisabled><button className="btn-primary" onClick={handleAlertSave}><Save size={15} /> {alertSaved ? t('common.saved', 'Saved!') : t('common.saveSettings', 'Save Settings')}</button></DemoDisabled>
            </div>
          </div>
          <div className="space-y-4">
            <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}><Volume2 size={16} style={{ color: 'hsl(var(--primary))' }} /> {t('restaurantSettings.alerts.sound.title', 'Sound Notifications')}</h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div><p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.alerts.sound.enable', 'Enable Sound Alerts')}</p><p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.alerts.sound.enableSubtitle', 'Play a sound when new alerts arrive')}</p></div>
                  <Toggle checked={alertSettings.soundEnabled} onChange={() => updateAlert('soundEnabled', !alertSettings.soundEnabled)} />
                </div>
                {alertSettings.soundEnabled && (
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <label className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.alerts.sound.volume', 'Alert Volume')}</label>
                      <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 className="flex items-center justify-between mt-1">
                      <VolumeX size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
                      <Volume2 size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}><Clock size={16} style={{ color: 'hsl(210, 100%, 40%)' }} /> {t('restaurantSettings.alerts.dismiss.title', 'Auto-Dismiss Timer')}</h3>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.alerts.dismiss.label', 'Dismiss alerts after')}</label>
                <div className="flex gap-2">
                  {[15, 30, 60, 120].map(sec => (
                    <button key={sec} onClick={() => updateAlert('autoDismiss', sec)} className="flex-1 py-2 rounded-xl text-sm font-semibold transition-all" style={{ backgroundColor: alertSettings.autoDismiss === sec ? 'hsl(var(--primary))' : 'hsl(var(--muted))', color: alertSettings.autoDismiss === sec ? 'white' : 'hsl(var(--foreground-secondary))' }}>
                      {sec < 60 ? t('common.secondsShort', '{{sec}}s', { sec }) : t('common.minutesShort', '{{min}}m', { min: sec / 60 })}
                    </button>
                  ))}
                </div>
                <p className="text-xs mt-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.alerts.dismiss.subtitle', 'Alerts will automatically dismiss after {{sec}} seconds if not acted upon', { sec: alertSettings.autoDismiss })}</p>
              </div>
            </div>
            <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}><Sliders size={16} style={{ color: 'hsl(142, 72%, 29%)' }} /> {t('restaurantSettings.alerts.types.title', 'Alert Types')}</h3>
              <div className="space-y-3">
                {[
                  { key: 'showOrders', icon: <ShoppingBag size={15} />, label: t('restaurantSettings.alerts.types.orders', 'New Orders'), desc: t('restaurantSettings.alerts.types.ordersSubtitle', 'Show alert when a new order is placed'), color: 'hsl(22, 89%, 48%)' },
                  { key: 'showBookings', icon: <CalendarDays size={15} />, label: t('restaurantSettings.alerts.types.bookings', 'New Bookings'), desc: t('restaurantSettings.alerts.types.bookingsSubtitle', 'Show alert when a table is reserved'), color: 'hsl(210, 100%, 40%)' },
                  { key: 'showAiEscalations', icon: <Bot size={15} />, label: t('restaurantSettings.alerts.types.aiEscalations', 'AI Escalations'), desc: t('restaurantSettings.alerts.types.aiEscalationsSubtitle', 'Show alert when AI hands off to staff'), color: 'hsl(231, 40%, 45%)' },
                ].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-3">
                      <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ backgroundColor: `${item.color}15`, color: item.color }}>{item.icon}</div>
                      <div><p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.label}</p><p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.desc}</p></div>
                    </div>
                    <Toggle checked={alertSettings[item.key as keyof typeof alertSettings] as boolean} onChange={() => updateAlert(item.key, !alertSettings[item.key as keyof typeof alertSettings])} />
                  </div>
                ))}
              </div>
            </div>
            <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}><Monitor size={16} style={{ color: 'hsl(38, 92%, 40%)' }} /> {t('restaurantSettings.alerts.browser.title', 'Browser Notifications')}</h3>
              <div className="flex items-center justify-between">
                <div><p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.alerts.browser.enable', 'Enable Browser Notifications')}</p><p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.alerts.browser.enableSubtitle', 'Receive alerts even when the tab is not in focus')}</p></div>
                <Toggle checked={alertSettings.browserNotifications} onChange={() => updateAlert('browserNotifications', !alertSettings.browserNotifications)} />
              </div>
              {alertSettings.browserNotifications && (
                <div className="mt-3 p-3 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--warning-bg))', color: 'hsl(var(--warning))', border: '1px solid hsl(var(--warning-border))' }}>
                  {t('restaurantSettings.alerts.browser.permissionNote', 'Browser will request notification permission when you save these settings.')}
                </div>
              )}
            </div>
          </div>
          {showDemo && (
            <AlertOverlay
              alerts={[
                {
                  id: 'demo-order',
                  type: 'order',
                  title: 'New Order #1042',
                  subtitle: 'Website — Dine-in',
                  details: ['2x Paneer Tikka', '1x Dal Makhani', '1x Butter Naan'],
                  timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                  countdown: alertSettings.autoDismiss,
                },
                {
                  id: 'demo-booking',
                  type: 'booking',
                  title: 'New Reservation',
                  subtitle: 'Tonight at 7:30 PM',
                  details: ['Party of 4', 'Guest: Jane Smith', 'Outdoor seating preferred'],
                  timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                  countdown: alertSettings.autoDismiss,
                },
                {
                  id: 'demo-ai',
                  type: 'escalation',
                  title: 'AI Escalation',
                  subtitle: 'Customer needs staff assistance',
                  details: ['Channel: Web Chat', 'Customer: Alex M.', 'Topic: Allergy query'],
                  timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                  countdown: alertSettings.autoDismiss,
                },
              ]}
              onDismiss={() => setShowDemo(false)}
              onAccept={() => setShowDemo(false)}
              soundEnabled={alertSettings.soundEnabled}
              volume={alertSettings.volume}
            />
          )}
        </div>
      )}

      {/* ── Billing ── */}
      {activeTab === 'billing' && (
        <div>
          <div className="flex gap-1 p-1 rounded-xl mb-6 w-fit" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            {([{ key: 'overview' as BillingTab, label: t('restaurantSettings.billing.tabs.overview', 'Overview'), icon: <TrendingUp size={15} /> }, { key: 'plans' as BillingTab, label: t('restaurantSettings.billing.tabs.plans', 'Plans'), icon: <Star size={15} /> }, { key: 'invoices' as BillingTab, label: t('restaurantSettings.billing.tabs.invoices', 'Invoices'), icon: <Receipt size={15} /> }]).map(t_bt => (
              <button key={t_bt.key} onClick={() => setBillingTab(t_bt.key)} className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${billingTab === t_bt.key ? 'bg-white shadow-sm' : ''}`} style={{ color: billingTab === t_bt.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>
                {t_bt.icon} {t_bt.label}
              </button>
            ))}
          </div>

          {billingTab === 'overview' && (
            <div className="space-y-5">
              {billingLoading ? (
                <div className="flex items-center justify-center py-12 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <RefreshCw size={16} className="animate-spin" /> {t('restaurantSettings.billing.loading', 'Loading billing data…')}
                </div>
              ) : (
                <>
                  {billingSubscription?.status === 'past_due' && (
                    <div className="flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium" style={{ backgroundColor: 'rgba(220,38,38,0.1)', color: 'hsl(0,84%,40%)', border: '1px solid rgba(220,38,38,0.3)' }}>
                      <AlertCircle size={16} />
                      <span>{t('restaurantSettings.billing.paymentOverdue', 'Your payment is overdue. Please update your payment method to avoid service interruption.')}</span>
                      <button onClick={() => setBillingTab('plans')} className="ml-auto underline font-semibold text-xs">{t('restaurantSettings.billing.updateNow', 'Update Now')}</button>
                    </div>
                  )}

                  <div className="card p-6" style={{ borderLeft: `4px solid ${bPlanColor}` }}>
                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                      <div className="flex items-center gap-4">
                        <div className="w-12 h-12 rounded-xl flex items-center justify-center" style={{ backgroundColor: `${bPlanColor}20` }}><Shield size={22} style={{ color: bPlanColor }} /></div>
                        <div>
                          <div className="flex items-center gap-2 mb-0.5">
                            <span className="text-lg font-bold" style={{ color: 'hsl(var(--foreground))' }}>{bPlanName} Plan</span>
                            {billingSubscription?.status === 'trial' ? (
                              <span className="px-2 py-0.5 rounded-full text-xs font-semibold text-white" style={{ backgroundColor: 'hsl(210, 100%, 40%)' }}>
                                {t('restaurantSettings.billing.trialBadge', 'Trial')}
                                {billingSubscription.trialEnd && ` — ${Math.max(0, Math.ceil((new Date(billingSubscription.trialEnd).getTime() - Date.now()) / 86400000))}d left`}
                              </span>
                            ) : (
                              <span className="px-2 py-0.5 rounded-full text-xs font-semibold text-white" style={{ backgroundColor: billingSubscription?.status === 'past_due' ? 'hsl(0,84%,40%)' : 'hsl(142, 72%, 29%)' }}>
                                {billingSubscription?.status === 'past_due' ? t('restaurantSettings.billing.pastDue', 'Past Due') : t('common.active', 'Active')}
                              </span>
                            )}
                          </div>
                          <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{overviewCurrencySymbol}{bPlanPrice}/month</p>
                          {billingSubscription?.currentPeriodEnd && (
                            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                              {billingSubscription.status === 'trial' ? t('restaurantSettings.billing.trialEnds', 'Trial ends') : t('restaurantSettings.billing.renewsOn', 'Renews')} {new Date(billingSubscription.currentPeriodEnd).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                            </p>
                          )}
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <button onClick={() => setBillingTab('plans')} className="btn-primary flex items-center gap-2"><ArrowUpCircle size={15} /> {t('restaurantSettings.billing.upgrade', 'Upgrade Plan')}</button>
                        <button onClick={() => setBillingTab('plans')} className="btn-secondary flex items-center gap-2"><ArrowDownCircle size={15} /> {t('restaurantSettings.billing.change', 'Change Plan')}</button>
                      </div>
                    </div>
                  </div>
                  <div>
                    <h3 className="text-sm font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.billing.usageTitle', 'Usage This Month')}</h3>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      {bUsageEntries.map(({ key, used }) => {
                        const limitVal = (bPlanLimits as Record<string, number>)[limitKeys[key]] ?? 0;
                        const pct = limitVal <= 0 ? 0 : Math.round((used / limitVal) * 100);
                        const isWarning = pct >= 80; const isCritical = pct >= 95;
                        const color = usageColorMap[key];
                        return (
                          <div key={key} className="card p-5">
                            <div className="flex items-center gap-2 mb-3">
                              <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ backgroundColor: `${color}15`, color }}>{usageIcons[key]}</div>
                              <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{usageLabels(t)[key]}</span>
                            </div>
                            <div className="flex items-end justify-between mb-2">
                              <span className="text-xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{limitVal <= 0 ? '∞' : used.toLocaleString()}</span>
                              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{limitVal <= 0 ? t('common.unlimited', 'Unlimited') : t('restaurantSettings.billing.usage.ofLimit', 'of {{limit}} {{unit}}', { limit: limitVal.toLocaleString(), unit: usageUnits(t)[key] })}</span>
                            </div>
                            {limitVal > 0 && (
                              <>
                                <div className="w-full h-2 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                                  <div className="h-full rounded-full transition-all" style={{ width: `${Math.min(pct, 100)}%`, backgroundColor: isCritical ? 'hsl(0, 84%, 60%)' : isWarning ? 'hsl(38, 92%, 50%)' : color }} />
                                </div>
                                <div className="flex justify-between mt-1.5">
                                  <span className="text-xs font-medium" style={{ color: isCritical ? 'hsl(0, 84%, 60%)' : isWarning ? 'hsl(38, 92%, 50%)' : 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.billing.usage.pctUsed', '{{pct}}% used', { pct })}</span>
                                  {isWarning && <button onClick={() => setBillingTab('plans')} className="text-xs font-semibold" style={{ color: bPlanColor }}>{t('restaurantSettings.billing.upgradeNow', 'Upgrade →')}</button>}
                                </div>
                              </>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="card p-5"><p className="text-xs font-semibold uppercase tracking-wider mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.billing.currentPlan', 'Current Plan')}</p><p className="text-2xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{overviewCurrencySymbol}{bPlanPrice}/mo</p></div>
                    <div className="card p-5"><p className="text-xs font-semibold uppercase tracking-wider mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.billing.plan', 'Plan')}</p><p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{bPlanName}</p></div>
                  </div>

                  <div className="card p-5">
                    <h3 className="text-sm font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.billing.billingContact', 'Billing Contact Email')}</h3>
                    <p className="text-xs mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.billing.billingContactDesc', 'Invoices and billing alerts will be sent here. Leave blank to use your account email.')}</p>
                    <div className="flex gap-2">
                      <input
                        type="email"
                        className="input-base flex-1"
                        placeholder="billing@yourrestaurant.com"
                        value={billingContactEmail}
                        onChange={e => setBillingContactEmail(e.target.value)}
                      />
                      <button
                        className="btn-primary flex items-center gap-2"
                        disabled={billingContactSaving}
                        onClick={async () => {
                          setBillingContactSaving(true);
                          setBillingContactSaved(false);
                          try {
                            await saveBillingContact(billingContactEmail.trim() || null);
                            setBillingContactSaved(true);
                            setTimeout(() => setBillingContactSaved(false), 2500);
                          } catch {
                            toast.error(t('restaurantSettings.billing.billingContactFailed', 'Failed to save billing contact'));
                          }
                          setBillingContactSaving(false);
                        }}
                      >
                        {billingContactSaving ? <RefreshCw size={14} className="animate-spin" /> : <Save size={14} />}
                        {billingContactSaved ? t('common.saved', 'Saved!') : t('common.save', 'Save')}
                      </button>
                    </div>
                  </div>
                </>
              )}
            </div>
          )}

          {billingTab === 'plans' && (
            <div className="space-y-5">
              <div className="flex flex-wrap items-center gap-3">
                <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.billing.cycle.label', 'Billing Cycle:')}</span>
                <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  {(['monthly', 'annual'] as const).map(c => (
                    <button key={c} onClick={() => setBillingCycle(c)} className={`px-4 py-1.5 rounded-lg text-sm font-medium capitalize transition-all ${billingCycle === c ? 'bg-white shadow-sm' : ''}`} style={{ color: billingCycle === c ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>
                      {c === 'monthly' ? t('common.monthly', 'monthly') : t('common.annual', 'annual')}{c === 'annual' && <span className="ml-1.5 text-xs font-bold text-green-600">-20%</span>}
                    </button>
                  ))}
                </div>
                {activeGateways.length > 1 && (
                  <>
                    <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.billing.currency.label', 'Currency:')}</span>
                    <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                      {activeGateways.map(gw => (
                        <button
                          key={gw.id}
                          onClick={() => setBillingCurrency(gw.currency)}
                          className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all ${billingCurrency === gw.currency ? 'bg-white shadow-sm' : ''}`}
                          style={{ color: billingCurrency === gw.currency ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
                        >
                          {gw.currency}
                          <span className="ml-1 opacity-60 capitalize">({gw.id})</span>
                        </button>
                      ))}
                    </div>
                  </>
                )}
              </div>
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
                {billingPlans.map(plan => {
                  const pColor = planColors[plan.name] ?? 'hsl(var(--primary))';
                  const basePrice = plan.effectivePriceMonthly ?? plan.priceMonthly;
                  const displayPrice = billingCycle === 'annual' ? Math.round((plan.effectivePriceAnnual ?? plan.priceAnnual) / 12 || basePrice * 0.8) : basePrice;
                  const isCurrent = plan.name === bPlanName; const isUpgrade = plan.priceMonthly > bPlanPrice; const isDowngrade = plan.priceMonthly < bPlanPrice;
                  const isPopular = plan.name === 'Pro';
                  const lims = plan.limits as Record<string, number>;
                  const limLabel = (val: number | undefined, unit: string) =>
                    val == null || val === 0 ? `${t('common.unlimited', 'Unlimited')} ${unit}` : `${val.toLocaleString()} ${unit}`;
                  const features = [
                    limLabel(lims.max_branches, t('restaurantSettings.billing.features.branches', 'branches')),
                    limLabel(lims.conversations_per_month, t('restaurantSettings.billing.features.conversationsUnit', 'AI conversations/mo')),
                    limLabel(lims.concurrent_voice_calls, t('restaurantSettings.billing.features.voiceCallsUnit', 'concurrent voice calls')),
                    limLabel(lims.api_calls_per_minute, t('restaurantSettings.billing.features.apiCallsUnit', 'API calls/min')),
                  ];
                  const currencySymbol = activeGateways.find(gw => gw.currency === billingCurrency)?.currency ?? billingCurrency;
                  const selectedCyclePrice = billingCycle === 'annual'
                    ? Math.round((plan.effectivePriceAnnual ?? plan.priceAnnual) || displayPrice * 12)
                    : displayPrice;
                  return (
                    <div key={plan.id} className={`card p-6 relative flex flex-col ${isPopular ? 'ring-2' : ''}`} style={isPopular ? { '--tw-ring-color': pColor } as React.CSSProperties : {}}>
                      {isPopular && <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 rounded-full text-xs font-bold text-white" style={{ backgroundColor: pColor }}>{t('restaurantSettings.billing.popular', 'Most Popular')}</div>}
                      {isCurrent && <div className="absolute -top-3 right-4 px-3 py-1 rounded-full text-xs font-bold text-white" style={{ backgroundColor: 'hsl(142, 72%, 29%)' }}>{t('restaurantSettings.billing.currentPlan', 'Current Plan')}</div>}
                      <div className="mb-4">
                        <div className="flex items-center gap-2 mb-1">
                          <h3 className="text-lg font-bold" style={{ color: 'hsl(var(--foreground))' }}>{plan.name}</h3>
                          {(plan.trialDays ?? 0) > 0 && !isCurrent && (
                            <span className="badge badge-neutral text-xs">{plan.trialDays}d {t('restaurantSettings.billing.freeTrial', 'free trial')}</span>
                          )}
                        </div>
                        <div className="flex items-end gap-1"><span className="text-3xl font-bold" style={{ color: pColor }}>{currencySymbol} {displayPrice}</span><span className="text-sm mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>/{t('common.mo', 'mo')}</span></div>
                        {billingCycle === 'annual' && <p className="text-xs text-green-600 font-medium mt-0.5">{t('restaurantSettings.billing.saveAnnual', 'Save ${{amount}}/year', { amount: (plan.priceMonthly - displayPrice) * 12 })}</p>}
                      </div>
                      <ul className="space-y-2 mb-6 flex-1">{features.map(f => <li key={f} className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--foreground-secondary))' }}><Check size={14} style={{ color: pColor, flexShrink: 0 }} />{f}</li>)}</ul>
                      {isCurrent ? (
                        <button disabled className="w-full py-2.5 rounded-xl text-sm font-semibold opacity-50 cursor-not-allowed" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.billing.currentPlan', 'Current Plan')}</button>
                      ) : confirmPlan === plan.id ? (
                        <div className="space-y-2">
                          <div className="rounded-xl p-3 space-y-1.5" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                            <div className="flex justify-between text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>
                              <span>{plan.name} ({billingCycle})</span>
                              <span>{currencySymbol} {selectedCyclePrice}</span>
                            </div>
                            {prorationLoading ? (
                              <div className="text-xs animate-pulse" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.loading', 'Loading…')}</div>
                            ) : prorationPreview && !prorationPreview.staticPreview && prorationPreview.lines.length > 0 ? (
                              <>
                                {prorationPreview.lines.map((line, i) => (
                                  <div key={i} className="flex justify-between text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                                    <span className="truncate pr-2">{line.description}</span>
                                    <span className="shrink-0">{line.currency} {line.amount >= 0 ? '+' : ''}{line.amount.toFixed(2)}</span>
                                  </div>
                                ))}
                                <div className="flex justify-between text-xs font-semibold border-t pt-1" style={{ color: 'hsl(var(--foreground))', borderColor: 'hsl(var(--border))' }}>
                                  <span>{t('restaurantSettings.billing.chargeNow', 'Charge now')}</span>
                                  <span>{prorationPreview.currency} {prorationPreview.prorationAmount?.toFixed(2) ?? '—'}</span>
                                </div>
                              </>
                            ) : prorationPreview?.staticPreview ? (
                              <div className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                                {isUpgrade ? t('restaurantSettings.billing.prorationNonUsd', 'You\'ll review the exact charge in the secure checkout page.') : t('restaurantSettings.billing.downgradeNote', 'Takes effect at next billing date')}
                              </div>
                            ) : (
                              <div className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                                {isUpgrade ? t('restaurantSettings.billing.prorationNote', 'Credit for current plan will be applied') : t('restaurantSettings.billing.downgradeNote', 'Takes effect at next billing date')}
                              </div>
                            )}
                            {(() => {
                              const nextDate = isUpgrade
                                ? new Date(Date.now() + (billingCycle === 'annual' ? 365 : 30) * 86400000)
                                : billingSubscription?.currentPeriodEnd
                                  ? new Date(billingSubscription.currentPeriodEnd)
                                  : null;
                              return nextDate ? (
                                <div className="flex justify-between text-xs pt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                                  <span>{isUpgrade ? t('restaurantSettings.billing.estNextBilling', 'Est. next billing') : t('restaurantSettings.billing.effectiveDate', 'Effective date')}</span>
                                  <span>{nextDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</span>
                                </div>
                              ) : null;
                            })()}
                          </div>
                          {(() => {
                            const gw = activeGateways.find(g => g.currency === billingCurrency) ?? activeGateways.find(g => g.id === 'stripe');
                            if (!(gw?.id === 'stripe' && gw?.promoCodesEnabled)) return null;
                            return (
                              <div className="space-y-1">
                                <div className="flex gap-1.5">
                                  <input
                                    type="text"
                                    placeholder={t('restaurantSettings.billing.promoCodePlaceholder', 'Promo code (optional)')}
                                    value={promoCode}
                                    onChange={e => { setPromoCode(e.target.value); setPromoValidated(null); }}
                                    className="flex-1 px-3 py-1.5 rounded-lg text-xs font-mono border"
                                    style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--background))', color: 'hsl(var(--foreground))' }}
                                    onKeyDown={async e => {
                                      if (e.key === 'Enter' && promoCode.trim() && !promoValidating) {
                                        setPromoValidating(true);
                                        const r = await validatePromoCode({ promoCode: promoCode.trim(), planId: plan.id, billingCycle });
                                        setPromoValidating(false);
                                        if (r.valid && r.discountedAmount != null) {
                                          setPromoValidated({ discountedAmount: r.discountedAmount, originalAmount: r.originalAmount ?? 0, currency: r.currency ?? 'usd', description: r.discountDescription ?? '' });
                                        } else {
                                          toast.error(r.error ?? 'Invalid promo code');
                                        }
                                      }
                                    }}
                                  />
                                  <button
                                    disabled={!promoCode.trim() || promoValidating}
                                    onClick={async () => {
                                      setPromoValidating(true);
                                      const r = await validatePromoCode({ promoCode: promoCode.trim(), planId: plan.id, billingCycle });
                                      setPromoValidating(false);
                                      if (r.valid && r.discountedAmount != null) {
                                        setPromoValidated({ discountedAmount: r.discountedAmount, originalAmount: r.originalAmount ?? 0, currency: r.currency ?? 'usd', description: r.discountDescription ?? '' });
                                      } else {
                                        toast.error(r.error ?? 'Invalid promo code');
                                      }
                                    }}
                                    className="px-3 py-1.5 rounded-lg text-xs font-semibold btn-primary disabled:opacity-50"
                                  >
                                    {promoValidating ? '…' : t('restaurantSettings.billing.applyPromo', 'Apply')}
                                  </button>
                                </div>
                                {promoValidated && (
                                  <div className="rounded-lg px-3 py-2 flex items-center justify-between" style={{ backgroundColor: 'rgba(22,163,74,0.08)' }}>
                                    <span className="text-xs font-medium" style={{ color: 'rgb(21,128,61)' }}>
                                      {promoValidated.description || 'Discount applied'}
                                    </span>
                                    <span className="text-xs font-bold" style={{ color: 'rgb(21,128,61)' }}>
                                      {promoValidated.currency.toUpperCase()} {promoValidated.discountedAmount.toFixed(2)}
                                      <span className="font-normal ml-1 line-through opacity-60">{promoValidated.originalAmount.toFixed(2)}</span>
                                    </span>
                                  </div>
                                )}
                              </div>
                            );
                          })()}
                          <div className="flex gap-2">
                            <button onClick={() => { setConfirmPlan(null); setPromoCode(''); setPromoValidated(null); setProrationPreview(null); }} disabled={checkoutLoading} className="flex-1 py-2 rounded-xl text-sm font-semibold btn-secondary">{t('common.cancel', 'Cancel')}</button>
                            <button
                              disabled={checkoutLoading}
                              onClick={async () => {
                                setCheckoutLoading(true);
                                const selectedGateway = activeGateways.find(gw => gw.currency === billingCurrency) ?? activeGateways.find(gw => gw.id === 'stripe') ?? activeGateways[0];
                                try {
                                  if (selectedGateway?.id === 'razorpay') {
                                    const order = await startRazorpayCheckout(plan.id, billingCycle);
                                    await new Promise<void>((resolve, reject) => {
                                      const loadScript = () => new Promise<boolean>(res => {
                                        if ((window as unknown as { Razorpay?: unknown }).Razorpay) { res(true); return; }
                                        const s = document.createElement('script');
                                        s.src = 'https://checkout.razorpay.com/v1/checkout.js';
                                        s.onload = () => res(true); s.onerror = () => res(false);
                                        document.body.appendChild(s);
                                      });
                                      loadScript().then(loaded => {
                                        if (!loaded) { reject(new Error('Failed to load payment gateway')); return; }
                                        const rzp = new (window as unknown as { Razorpay: new (opts: Record<string, unknown>) => { open(): void } }).Razorpay({
                                          key: order.keyId,
                                          subscription_id: order.subscriptionId,
                                          currency: order.currency,
                                          name: 'RestroAgent',
                                          description: `${order.planName} plan`,
                                          handler: async (response: { razorpay_subscription_id: string; razorpay_payment_id: string; razorpay_signature: string }) => {
                                            try {
                                              await verifyRazorpayPayment({
                                                razorpaySubscriptionId: response.razorpay_subscription_id,
                                                razorpayPaymentId: response.razorpay_payment_id,
                                                razorpaySignature: response.razorpay_signature,
                                              });
                                              toast.success(t('restaurantSettings.billing.paymentSuccess', 'Payment successful! Your plan has been upgraded.'));
                                              const sub = await getSubscription();
                                              setBillingSubscription(sub);
                                              setConfirmPlan(null);
                                              resolve();
                                            } catch (err) {
                                              reject(err);
                                            }
                                          },
                                          modal: { ondismiss: () => reject(new Error('cancelled')) },
                                        });
                                        rzp.open();
                                      });
                                    });
                                  } else {
                                    const url = await startCheckout(plan.id, billingCycle, promoCode.trim() || undefined);
                                    const parsed = new URL(url);
                                    if (parsed.protocol !== 'https:' || !(parsed.hostname === 'stripe.com' || parsed.hostname.endsWith('.stripe.com'))) {
                                      throw new Error('Untrusted checkout URL');
                                    }
                                    window.location.href = url;
                                  }
                                } catch (err: unknown) {
                                  const msg = err instanceof Error ? err.message : String(err);
                                  if (msg === 'cancelled') { setConfirmPlan(null); setCheckoutLoading(false); return; }
                                  if (msg.toLowerCase().includes('stripe')) {
                                    toast.error(t('restaurantSettings.billing.stripeNotConfigured', 'Stripe is not configured. Please contact support to upgrade your plan.'));
                                  } else {
                                    toast.error(msg || t('restaurantSettings.billing.checkoutFailed', 'Failed to start checkout'));
                                  }
                                  setConfirmPlan(null);
                                } finally {
                                  setCheckoutLoading(false);
                                }
                              }}
                              className="flex-1 py-2 rounded-xl text-sm font-bold text-white flex items-center justify-center gap-1"
                              style={{ backgroundColor: pColor }}
                            >
                              {checkoutLoading ? <><svg className="animate-spin w-3.5 h-3.5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"/></svg> {t('common.loading', 'Loading…')}</> : t('common.confirm', 'Confirm')}
                            </button>
                          </div>
                        </div>
                      ) : (
                        <button onClick={() => setConfirmPlan(plan.id)} className="w-full py-2.5 rounded-xl text-sm font-bold text-white flex items-center justify-center gap-2 transition-opacity hover:opacity-90" style={{ backgroundColor: pColor }}>
                          {isUpgrade ? <ArrowUpCircle size={15} /> : <ArrowDownCircle size={15} />}{isUpgrade ? t('common.upgrade', 'Upgrade') : t('common.downgrade', 'Downgrade')}
                        </button>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {billingTab === 'invoices' && (
            <div className="max-w-3xl">
              {invoicesLoading ? (
                <div className="flex items-center justify-center py-12 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <RefreshCw size={16} className="animate-spin" /> {t('restaurantSettings.billing.invoices.loading', 'Loading invoices…')}
                </div>
              ) : billingInvoices.length > 0 ? (
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.billing.invoices.title', 'Invoice History')}</h3>
                    <button
                      onClick={() => {
                        billingInvoices.forEach((inv, idx) => {
                          const url = inv.pdfUrl ?? inv.hostedUrl;
                          if (!url) return;
                          setTimeout(() => window.open(url, '_blank', 'noopener'), idx * 250);
                        });
                      }}
                      disabled={!billingInvoices.some(i => i.pdfUrl || i.hostedUrl)}
                      className="btn-secondary flex items-center gap-2 text-xs disabled:opacity-50"
                    >
                      <Download size={13} /> {t('restaurantSettings.billing.invoices.downloadAll', 'Download All')}
                    </button>
                  </div>
                  {(() => {
                    const toggleSort = (field: 'date' | 'amount' | 'status') => {
                      if (invoiceSortField === field) { setInvoiceSortDir(d => d === 'asc' ? 'desc' : 'asc'); }
                      else { setInvoiceSortField(field); setInvoiceSortDir('desc'); }
                    };
                    const sortedInvoices = [...billingInvoices].sort((a, b) => {
                      let cmp = 0;
                      if (invoiceSortField === 'date') cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
                      else if (invoiceSortField === 'amount') cmp = a.amount - b.amount;
                      else if (invoiceSortField === 'status') cmp = (a.status ?? '').localeCompare(b.status ?? '');
                      return invoiceSortDir === 'asc' ? cmp : -cmp;
                    });
                    const SortIcon = ({ field }: { field: 'date' | 'amount' | 'status' }) => (
                      invoiceSortField === field
                        ? (invoiceSortDir === 'asc' ? <ChevronUp size={11} className="inline ml-0.5" /> : <ChevronDown size={11} className="inline ml-0.5" />)
                        : null
                    );
                    return (
                  <div className="card overflow-hidden">
                    <table className="w-full text-sm">
                      <thead>
                        <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                          <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Invoice</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider cursor-pointer select-none" style={{ color: 'hsl(var(--muted-foreground))' }} onClick={() => toggleSort('date')}>Date <SortIcon field="date" /></th>
                          <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Period</th>
                          <th className="text-right px-4 py-3 text-xs font-semibold uppercase tracking-wider cursor-pointer select-none" style={{ color: 'hsl(var(--muted-foreground))' }} onClick={() => toggleSort('amount')}>Amount <SortIcon field="amount" /></th>
                          <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider cursor-pointer select-none" style={{ color: 'hsl(var(--muted-foreground))' }} onClick={() => toggleSort('status')}>Status <SortIcon field="status" /></th>
                          <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Currency</th>
                          <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Gateway</th>
                          <th className="px-4 py-3"></th>
                        </tr>
                      </thead>
                      <tbody>
                        {sortedInvoices.map((inv, i) => (
                          <tr key={inv.id} style={{ borderBottom: i < sortedInvoices.length - 1 ? '1px solid hsl(var(--border))' : undefined }}>
                            <td className="px-4 py-3 font-mono text-xs" style={{ color: 'hsl(var(--foreground))' }}>{inv.number ?? `INV-${String(i + 1).padStart(4, '0')}`}</td>
                            <td className="px-4 py-3 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{new Date(inv.createdAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</td>
                            <td className="px-4 py-3 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{new Date(inv.periodStart).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} – {new Date(inv.periodEnd).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</td>
                            <td className="px-4 py-3 text-right font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{inv.currency?.toUpperCase() === 'USD' ? '$' : ''}{inv.amount.toFixed(2)}{inv.currency?.toUpperCase() !== 'USD' ? ` ${inv.currency?.toUpperCase()}` : ''}</td>
                            <td className="px-4 py-3">
                              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold" style={{ backgroundColor: inv.status === 'paid' ? 'rgba(22,163,74,0.1)' : 'rgba(202,138,4,0.1)', color: inv.status === 'paid' ? 'rgb(21,128,61)' : 'rgb(161,98,7)' }}>
                                {inv.status === 'paid' ? '✓ Paid' : inv.status ?? 'Pending'}
                              </span>
                            </td>
                            <td className="px-4 py-3 text-xs font-mono font-semibold" style={{ color: 'hsl(var(--muted-foreground))' }}>
                              {inv.currency?.toUpperCase() ?? '—'}
                            </td>
                            <td className="px-4 py-3">
                              <span className="badge badge-neutral text-xs capitalize">
                                {('gateway' in inv ? (inv as { gateway: string }).gateway : 'stripe') ?? 'stripe'}
                              </span>
                            </td>
                            <td className="px-4 py-3">
                              <div className="flex items-center gap-3 justify-end">
                                {inv.pdfUrl && <a href={inv.pdfUrl} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-xs font-medium" style={{ color: 'hsl(var(--primary))' }}><Download size={12} /> PDF</a>}
                                {inv.hostedUrl && <a href={inv.hostedUrl} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-xs font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}><ExternalLink size={12} /> View</a>}
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  );
                  })()}
                </div>
              ) : (
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.billing.invoices.title', 'Invoice History')}</h3>
                    {showSampleInvoice && (
                      <button onClick={() => { document.body.classList.add('invoice-printing'); window.addEventListener('afterprint', () => document.body.classList.remove('invoice-printing'), { once: true }); window.print(); }} className="no-print btn-secondary flex items-center gap-2 text-xs"><Download size={13} /> {t('restaurantSettings.billing.invoices.print', 'Print / Save PDF')}</button>
                    )}
                  </div>
                  {!showSampleInvoice && (
                    <div className="card p-12 text-center space-y-3">
                      <Receipt size={32} className="mx-auto" style={{ color: 'hsl(var(--muted-foreground))' }} />
                      <div>
                        <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.billing.invoices.noInvoices', 'No invoices yet')}</p>
                        <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.billing.invoices.noInvoicesSub', 'Invoices will appear here after your first billing cycle.')}</p>
                      </div>
                      <button onClick={() => setShowSampleInvoice(true)} className="btn-secondary text-xs inline-flex items-center gap-1.5 mx-auto"><Eye size={13} /> {t('restaurantSettings.billing.invoices.viewSample', 'View Sample Invoice')}</button>
                    </div>
                  )}
                  {showSampleInvoice && (
                  <div id="invoice-print-area" className="card p-8 space-y-6">
                    <div className="flex items-start justify-between">
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <div className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(22, 89%, 48%)' }}><Zap size={14} className="text-white" /></div>
                          <span className="text-base font-bold" style={{ color: 'hsl(var(--foreground))' }}>RestroAgent</span>
                        </div>
                        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>AI-Powered Restaurant Management</p>
                        <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>support@restroagent.com</p>
                      </div>
                      <div className="text-right">
                        <p className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>INVOICE</p>
                        <p className="text-sm font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{(() => { const now = new Date(); return `INV-${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}-0001`; })()}</p>
                        <span className="inline-flex items-center mt-1 px-2 py-0.5 rounded-full text-xs font-semibold" style={{ backgroundColor: 'rgba(22,163,74,0.1)', color: 'rgb(21,128,61)' }}>✓ Sample</span>
                      </div>
                    </div>
                    <div style={{ borderTop: '2px solid hsl(var(--border))' }} />
                    <div className="grid grid-cols-2 gap-6">
                      <div>
                        <p className="text-xs font-semibold uppercase tracking-wider mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>Bill To</p>
                        <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{profileName || 'Your Restaurant'}</p>
                        {profileAddress && <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{profileAddress}</p>}
                        {userRecord?.email && <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{userRecord.email}</p>}
                      </div>
                      <div>
                        <div className="space-y-2">
                          <div className="flex justify-between text-xs">
                            <span style={{ color: 'hsl(var(--muted-foreground))' }}>Invoice Date</span>
                            <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</span>
                          </div>
                          <div className="flex justify-between text-xs">
                            <span style={{ color: 'hsl(var(--muted-foreground))' }}>Billing Period</span>
                            <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{(() => { const now = new Date(); const end = new Date(now.getFullYear(), now.getMonth() + 1, 0); return `${now.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} – ${end.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}`; })()}</span>
                          </div>
                          <div className="flex justify-between text-xs">
                            <span style={{ color: 'hsl(var(--muted-foreground))' }}>Billing Cycle</span>
                            <span className="font-medium capitalize" style={{ color: 'hsl(var(--foreground))' }}>{billingCycle}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="overflow-hidden rounded-xl" style={{ border: '1px solid hsl(var(--border))' }}>
                      <table className="w-full text-sm">
                        <thead>
                          <tr style={{ backgroundColor: 'hsl(var(--muted))' }}>
                            <th className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Description</th>
                            <th className="text-right px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Qty</th>
                            <th className="text-right px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Unit Price</th>
                            <th className="text-right px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>Amount</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr style={{ borderTop: '1px solid hsl(var(--border))' }}>
                            <td className="px-4 py-3">
                              <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{bPlanName} Plan — {billingCycle === 'annual' ? 'Annual' : 'Monthly'} Subscription</p>
                              <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>RestroAgent AI restaurant management platform</p>
                            </td>
                            <td className="px-4 py-3 text-right text-sm" style={{ color: 'hsl(var(--foreground))' }}>1</td>
                            <td className="px-4 py-3 text-right text-sm" style={{ color: 'hsl(var(--foreground))' }}>{overviewCurrencySymbol}{bPlanPrice.toFixed(2)}</td>
                            <td className="px-4 py-3 text-right font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{overviewCurrencySymbol}{bPlanPrice.toFixed(2)}</td>
                          </tr>
                          {billingCycle === 'annual' && (
                            <tr style={{ borderTop: '1px solid hsl(var(--border))' }}>
                              <td className="px-4 py-3">
                                <p className="font-medium text-sm" style={{ color: 'rgb(21,128,61)' }}>Annual Discount (20%)</p>
                              </td>
                              <td className="px-4 py-3 text-right text-sm" style={{ color: 'hsl(var(--foreground))' }}>1</td>
                              <td className="px-4 py-3 text-right text-sm" style={{ color: 'rgb(21,128,61)' }}>-{overviewCurrencySymbol}{(bPlanPrice * 0.2).toFixed(2)}</td>
                              <td className="px-4 py-3 text-right font-semibold text-sm" style={{ color: 'rgb(21,128,61)' }}>-{overviewCurrencySymbol}{(bPlanPrice * 0.2).toFixed(2)}</td>
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </div>
                    <div className="flex justify-end">
                      <div className="w-64 space-y-2">
                        {(() => {
                          const subtotal = billingCycle === 'annual' ? bPlanPrice * 0.8 : bPlanPrice;
                          return (
                            <>
                              <div className="flex justify-between text-sm">
                                <span style={{ color: 'hsl(var(--muted-foreground))' }}>Subtotal</span>
                                <span style={{ color: 'hsl(var(--foreground))' }}>${subtotal.toFixed(2)}</span>
                              </div>
                              <div className="flex justify-between text-sm">
                                <span style={{ color: 'hsl(var(--muted-foreground))' }}>Tax (0%)</span>
                                <span style={{ color: 'hsl(var(--foreground))' }}>$0.00</span>
                              </div>
                              <div className="flex justify-between text-sm font-bold pt-2" style={{ borderTop: '2px solid hsl(var(--border))' }}>
                                <span style={{ color: 'hsl(var(--foreground))' }}>Total Due</span>
                                <span style={{ color: 'hsl(var(--primary))' }}>${subtotal.toFixed(2)} USD</span>
                              </div>
                            </>
                          );
                        })()}
                      </div>
                    </div>
                    <div className="text-center pt-2" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Thank you for your business. For billing questions contact support@restroagent.com</p>
                    </div>
                  </div>
                  )}
                  {showSampleInvoice && (
                    <div className="mt-3 text-center no-print">
                      <button onClick={() => setShowSampleInvoice(false)} className="text-xs underline" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.billing.invoices.hideSample', 'Hide sample')}</button>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* ── Notifications ── */}
      {activeTab === 'notifications' && (
        <div className="max-w-2xl space-y-4">
          {notifLoading ? (
            <div className="flex items-center justify-center py-12 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <RefreshCw size={16} className="animate-spin" /> {t('restaurantSettings.notifications.loading', 'Loading preferences…')}
            </div>
          ) : (
            <>
              {[...new Set(notifPrefs.map(p => p.category))].map(cat => (
                <div key={cat} className="card p-5">
                  <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{cat}</h3>
                  <div className="space-y-3">
                    {notifPrefs.filter(p => p.category === cat).map(pref => (
                      <div key={pref.id} className="flex items-center justify-between py-2" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        <div className="flex-1 mr-4">
                          <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{pref.event}</p>
                          <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{pref.description}</p>
                        </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('common.inApp', 'App')}</span>
                            <button onClick={() => toggleNotifPref(pref.id, 'inApp')}>{pref.inApp ? <ToggleRight size={20} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={20} style={{ color: 'hsl(var(--muted-foreground))' }} />}</button>
                          </div>
                          <div className="flex items-center gap-1.5">
                            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.email', 'Email')}</span>
                            <button onClick={() => toggleNotifPref(pref.id, 'email')}>{pref.email ? <ToggleRight size={20} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={20} style={{ color: 'hsl(var(--muted-foreground))' }} />}</button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
              <div className="flex justify-end">
                <DemoDisabled>
                  <button onClick={handleNotifSave} disabled={notifSaving} className="btn-primary flex items-center gap-2">
                    {notifSaving ? <RefreshCw size={15} className="animate-spin" /> : notifSaved ? <CheckCircle2 size={15} /> : <Save size={15} />}
                    {notifSaved ? t('common.saved', 'Saved!') : notifSaving ? t('common.saving', 'Saving…') : t('restaurantSettings.notifications.save', 'Save Preferences')}
                  </button>
                </DemoDisabled>
              </div>
            </>
          )}
        </div>
      )}

      {/* ── Templates ── */}
      {activeTab === 'templates' && (
        <div className="flex rounded-xl overflow-hidden" style={{ border: '1px solid hsl(var(--border))', minHeight: '600px' }}>
          {/* Left: Template Selector */}
          <div className="w-52 shrink-0 flex flex-col py-4 px-3 gap-1" style={{ borderRight: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--surface))' }}>
            <p className="text-xs font-semibold uppercase tracking-wider px-2 mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.templates.title', 'Templates')}</p>
            {templatesList(t).map(tpl => (
              <button key={tpl.id} onClick={() => setActiveTemplate(tpl.id)} className="flex items-start gap-3 px-3 py-3 rounded-xl text-left transition-all" style={activeTemplate === tpl.id ? { backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' } : { color: 'hsl(var(--foreground-secondary))' }}>
                <span className="mt-0.5 shrink-0" style={{ color: activeTemplate === tpl.id ? 'hsl(var(--primary))' : tpl.color }}>{tpl.icon}</span>
                <div><p className="text-sm font-medium leading-tight">{tpl.label}</p><p className="text-xs mt-0.5 leading-snug opacity-70">{tpl.description}</p></div>
              </button>
            ))}
          </div>
          {/* Center: Editor */}
          <div className="flex-1 flex flex-col min-w-0">
            <div className="flex items-center gap-1 px-5 pt-4 pb-0 shrink-0">
              {channels(t).map(ch => {
                const isComingSoon = ch.id === 'sms' || ch.id === 'whatsapp';
                return (
                  <button key={ch.id} onClick={() => setActiveChannel(ch.id)} className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-t-lg border-b-2 transition-all" style={activeChannel === ch.id ? { borderBottomColor: 'hsl(var(--primary))', color: 'hsl(var(--primary))', backgroundColor: 'hsl(var(--primary-light))' } : { borderBottomColor: 'transparent', color: 'hsl(var(--muted-foreground))' }}>
                    {ch.icon}{ch.label}
                    {isComingSoon && <span style={{ fontSize: '10px', fontWeight: 600, letterSpacing: '0.02em', padding: '1px 5px', borderRadius: '4px', backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))', marginLeft: '2px' }}>{t('common.soon', 'Soon')}</span>}
                  </button>
                );
              })}
              <div className="flex-1" />
              <button onClick={() => setShowPreview(v => !v)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-all" style={{ borderColor: showPreview ? 'hsl(var(--primary))' : 'hsl(var(--border))', color: showPreview ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))', backgroundColor: showPreview ? 'hsl(var(--primary-light))' : 'transparent' }}>
                <Eye size={13} /> {t('common.preview', 'Preview')}
              </button>
            </div>
            <div className="flex flex-1 min-h-0" style={{ borderTop: '1px solid hsl(var(--border))' }}>
              <div className="flex-1 flex flex-col">
                <div>
                  <p className="text-xs font-semibold mb-2 flex items-center gap-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}><Tag size={12} /> {t('restaurantSettings.templates.variables.title', 'Variable Placeholders — click to insert, or copy')}</p>
                  <div className="flex flex-wrap gap-1.5">
                    {currentTpl.variables.map(v => (
                      <div key={v.tag} className="flex items-center rounded-lg overflow-hidden" style={{ border: '1px solid hsl(var(--border))' }}>
                        <button onClick={() => handleInsertTag(v.tag)} className="px-2.5 py-1 text-xs font-mono font-semibold transition-colors hover:opacity-80" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>{v.tag}</button>
                        <button onClick={() => handleCopyTag(v.tag)} className="px-2 py-1 transition-colors hover:opacity-70" style={{ backgroundColor: 'hsl(var(--surface))', color: 'hsl(var(--muted-foreground))' }}>
                          {copiedTag === v.tag ? <CheckCircle2 size={11} style={{ color: 'hsl(142, 72%, 29%)' }} /> : <Copy size={11} />}
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="flex-1 flex flex-col">
                  <textarea value={currentContent} onChange={e => handleContentChange(e.target.value)} className="flex-1 w-full pl-4 pr-4 py-4 text-sm rounded-xl border outline-none resize-none font-mono leading-relaxed" style={{ backgroundColor: 'hsl(var(--surface))', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))', minHeight: '200px' }} placeholder={t('restaurantSettings.templates.editor.placeholder', 'Enter your message template here...')} spellCheck={false} />
                  <p className="text-xs mt-1.5 text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.templates.charCount', '{{count}} characters', { count: currentContent.length })}{activeChannel === 'sms' && currentContent.length > 160 && <span className="ml-2" style={{ color: 'hsl(22, 89%, 48%)' }}>({t('restaurantSettings.templates.smsSegments', '{{count}} SMS segments', { count: Math.ceil(currentContent.length / 160) })})</span>}</p>
                </div>
                <div className="flex items-center gap-3">
                  <button onClick={handleTemplateSave} className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold text-white transition-all hover:opacity-90" style={{ backgroundColor: isSaved ? 'hsl(142, 72%, 29%)' : 'hsl(var(--primary))' }}>
                    {isSaved ? <CheckCircle2 size={15} /> : <Save size={15} />}{isSaved ? t('common.saved', 'Saved!') : t('restaurantSettings.templates.save', 'Save Template')}
                  </button>
                  <button onClick={handleTemplateReset} className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium border transition-all hover:opacity-80" style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground-secondary))' }}>
                    <RotateCcw size={14} /> {t('restaurantSettings.templates.reset', 'Reset to Default')}
                  </button>
                </div>
              </div>
              {showPreview && (
                <div className="w-64 shrink-0 flex flex-col" style={{ borderLeft: '1px solid hsl(var(--border))' }}>
                  <div className="px-4 py-3 shrink-0" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                    <p className="text-xs font-semibold flex items-center gap-1.5" style={{ color: 'hsl(var(--foreground))' }}><Eye size={13} /> {t('restaurantSettings.templates.preview.title', 'Live Preview')}</p>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.templates.preview.subtitle', 'Variables replaced with example values')}</p>
                  </div>
                  <div className="flex-1 overflow-y-auto p-4">
                    {activeChannel === 'sms' && <div className="flex flex-col gap-2"><div className="rounded-2xl rounded-tl-sm px-4 py-3 text-xs leading-relaxed max-w-[90%]" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }} dangerouslySetInnerHTML={{ __html: renderPreview(currentContent, currentTpl.variables) }} /><p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>SMS · {t('restaurantSettings.templates.charCount', '{{count}} chars', { count: currentContent.length })}</p></div>}
                    {activeChannel === 'whatsapp' && <div className="rounded-2xl rounded-tl-sm px-4 py-3 text-xs leading-relaxed" style={{ backgroundColor: 'hsl(142, 72%, 95%)', color: 'hsl(var(--foreground))' }} dangerouslySetInnerHTML={{ __html: renderPreview(currentContent, currentTpl.variables) }} />}
                    {activeChannel === 'email' && <div className="rounded-xl p-4 text-xs leading-relaxed" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}><div className="pb-3 mb-3" style={{ borderBottom: '1px solid hsl(var(--border))' }}><p className="font-semibold text-xs" style={{ color: 'hsl(var(--foreground))' }}>{currentTpl.label} — {t('common.restaurantName', 'The Rustic Fork')}</p><p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>noreply@rustricfork.com</p></div><div dangerouslySetInnerHTML={{ __html: renderPreview(currentContent, currentTpl.variables) }} /></div>}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ── Webhooks ── */}
      {activeTab === 'webhooks' && (
        <div>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
            {[
              { label: t('restaurantSettings.webhooks.stats.active', 'Active Endpoints'), value: webhooks.filter(w => w.status === 'active').length, color: 'hsl(142, 72%, 29%)' },
              { label: t('restaurantSettings.webhooks.stats.deliveries', 'Total Deliveries'), value: webhooks.reduce((s, w) => s + (w.totalDeliveries ?? 0), 0).toLocaleString(), color: 'hsl(210, 100%, 40%)' },
              { label: t('restaurantSettings.webhooks.stats.failed', 'Failed (24h)'), value: '—', color: 'hsl(0, 84%, 44%)' },
              { label: t('restaurantSettings.webhooks.stats.successRate', 'Avg Success Rate'), value: webhooks.length > 0 ? `${(webhooks.reduce((s, w) => s + (w.successRate ?? 100), 0) / webhooks.length).toFixed(1)}%` : '—', 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>
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.webhooks.title', 'Webhook Endpoints')}</h3>
            <button className="btn-primary text-sm" onClick={() => setShowAddWebhook(!showAddWebhook)}><Plus size={15} /> {t('restaurantSettings.webhooks.add', 'Add Endpoint')}</button>
          </div>
          {showAddWebhook && (
            <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('restaurantSettings.webhooks.addForm.title', 'New Webhook Endpoint')}</h4>
                <button onClick={() => { setShowAddWebhook(false); setSettingsWebhookErrors({}); setSettingsWebhookTouched({}); }}><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('restaurantSettings.webhooks.addForm.url', 'Endpoint URL *')}</label>
                  <input
                    type="url"
                    placeholder={t('restaurantSettings.webhooks.addForm.urlPlaceholder', 'https://your-app.com/webhooks')}
                    value={newWebhook.url}
                    onChange={e => handleSettingsWebhookUrlChange(e.target.value)}
                    onBlur={() => { setSettingsWebhookTouched(prev => ({ ...prev, url: true })); setSettingsWebhookErrors(prev => ({ ...prev, url: validateSettingsWebhookUrl(newWebhook.url) })); }}
                    className="input-base w-full font-mono"
                    style={{
                      borderColor: settingsWebhookTouched.url && settingsWebhookErrors.url ? 'hsl(0, 84%, 44%)' : undefined,
                      boxShadow: settingsWebhookTouched.url && settingsWebhookErrors.url ? '0 0 0 2px hsl(0, 84%, 44%, 0.15)' : undefined,
                    }}
                  />
                  {settingsWebhookTouched.url && settingsWebhookErrors.url && (
                    <p className="flex items-center gap-1 text-xs mt-1.5 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
                      <Info size={12} />{settingsWebhookErrors.url}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.webhooks.addForm.events', 'Subscribe to Events *')}</label>
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                    {allWebhookEvents.map(event => (
                      <label key={event} className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={newWebhook.events.includes(event)} onChange={() => toggleWebhookEvent(event)} className="rounded" />
                        <span className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>{event}</span>
                      </label>
                    ))}
                  </div>
                  {settingsWebhookTouched.events && settingsWebhookErrors.events && (
                    <p className="flex items-center gap-1 text-xs mt-2 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
                      <Info size={12} />{settingsWebhookErrors.events}
                    </p>
                  )}
                </div>
                <div className="flex gap-3">
                  <button className="btn-primary" onClick={handleSettingsWebhookSave} disabled={webhookSaving}>
                    {webhookSaving ? <RefreshCw size={15} className="animate-spin" /> : <Save size={15} />} {t('restaurantSettings.webhooks.addForm.save', 'Save Endpoint')}
                  </button>
                  <button className="btn-secondary" onClick={() => { setShowAddWebhook(false); setSettingsWebhookErrors({}); setSettingsWebhookTouched({}); }}>{t('common.cancel', 'Cancel')}</button>
                </div>
              </div>
            </div>
          )}
          {webhooksLoading && (
            <div className="flex items-center justify-center py-10 gap-2 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <RefreshCw size={16} className="animate-spin" /> {t('restaurantSettings.webhooks.loading', 'Loading webhooks…')}
            </div>
          )}
          {webhooksError && (
            <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))' }}>
              {webhooksError}
              <button className="ml-auto" onClick={() => setWebhooksError(null)}><X size={13} /></button>
            </div>
          )}
          <div className="space-y-3 mb-8">
            {!webhooksLoading && webhooks.length === 0 && (
              <div className="text-center py-10 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.webhooks.empty', 'No webhook endpoints yet. Add one above.')}</p>
              </div>
            )}
            {webhooks.map(webhook => {
              const isRevealed = revealedWebhookKeys.has(webhook.id);
              const events = Array.isArray(webhook.events) ? webhook.events : [];
              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" 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%)' }}><Webhook size={16} /></div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <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" 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%)' }}>{webhook.status === 'active' ? t('common.active', 'active') : t('common.inactive', 'inactive')}</span>
                      </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('restaurantSettings.webhooks.secret', 'Secret:')}</span>
                          <span className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>{isRevealed ? webhook.secret : '••••••••••••••••'}</span>
                          <button onClick={() => toggleWebhookKey(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>
                        </div>
                        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                          {t('restaurantSettings.webhooks.stats', '{{rate}}% success · {{deliveries}} deliveries', { rate: (webhook.successRate ?? 100).toFixed(1), deliveries: (webhook.totalDeliveries ?? 0).toLocaleString() })}
                        </span>
                      </div>
                    </div>
                    <div className="flex items-center gap-1 shrink-0">
                      <button
                        className="p-1.5 rounded-lg transition-colors text-xs font-semibold px-2"
                        title={webhook.status === 'active' ? t('common.deactivate', 'Deactivate') : t('common.activate', 'Activate')}
                        onClick={() => handleToggleWebhookStatus(webhook.id, webhook.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%)' }}
                      >
                        {webhook.status === 'active' ? t('common.deactivate', 'Deactivate') : t('common.activate', 'Activate')}
                      </button>
                      <button className="p-1.5 rounded-lg hover:bg-red-50 transition-colors" title={t('common.delete', 'Delete')} onClick={() => handleDeleteWebhook(webhook.id)}><Trash2 size={14} style={{ color: 'hsl(var(--danger))' }} /></button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          {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('restaurantSettings.webhooks.logs.title', 'Delivery Logs')}</h3>
                {logsLoading && <RefreshCw 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))' }}>
                    <RefreshCw size={16} className="animate-spin" /> {t('restaurantSettings.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('restaurantSettings.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('restaurantSettings.webhooks.logs.headers.event', 'Event'),
                              t('restaurantSettings.webhooks.logs.headers.endpoint', 'Endpoint'),
                              t('restaurantSettings.webhooks.logs.headers.status', 'Status'),
                              t('restaurantSettings.webhooks.logs.headers.response', 'Response'),
                              t('restaurantSettings.webhooks.logs.headers.duration', 'Duration'),
                              t('restaurantSettings.webhooks.logs.headers.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 = log.status === 'success'
                              ? { color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)', icon: <CheckCircle size={12} /> }
                              : { color: 'hsl(0, 84%, 44%)', bg: 'hsl(0, 84%, 97%)', icon: <XCircle size={12} /> };
                            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 === 'success' ? t('common.success', 'success') : t('common.failure', 'failure')}
                                  </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>
          )}
        </div>
      )}

      {/* ── REST API ── */}
      {activeTab === 'rest-api' && (
        <div>
          {newKeyBanner && (
            <div className="mb-5 p-4 rounded-xl" style={{ backgroundColor: 'hsl(var(--success-bg))', border: '1px solid hsl(var(--success-border))' }}>
              <p className="text-sm font-semibold mb-1" style={{ color: 'hsl(var(--success))' }}>{t('restaurantSettings.apiKeys.generatedBanner', 'API key generated — copy it now')}</p>
              <p className="text-xs mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.apiKeys.onlyTimeToSee', 'This is the only time you will see the full key.')}</p>
              <div className="flex items-center gap-2">
                <code className="text-xs font-mono flex-1 p-2 rounded" style={{ backgroundColor: 'hsl(var(--surface))', color: 'hsl(var(--foreground))' }}>{newKeyBanner}</code>
                <button className="btn-secondary text-xs" onClick={() => navigator.clipboard.writeText(newKeyBanner).catch(() => {})}><Copy size={13} /> {t('common.copy', 'Copy')}</button>
                <button onClick={() => setNewKeyBanner(null)}><X size={15} style={{ color: 'hsl(var(--muted-foreground))' }} /></button>
              </div>
            </div>
          )}
          {apiKeysError && (
            <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))' }}>
              {apiKeysError}
              <button className="ml-auto" onClick={() => setApiKeysError(null)}><X size={13} /></button>
            </div>
          )}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
            {[
              { label: t('restaurantSettings.apiKeys.stats.activeKeys', 'Active API Keys'), value: apiKeys.filter(k => k.status === 'active').length, color: 'hsl(142, 72%, 29%)' },
              { label: t('restaurantSettings.apiKeys.stats.callsMonth', 'API Calls (Month)'), value: totalApiCalls.toLocaleString(), color: 'hsl(210, 100%, 40%)' },
              { label: t('restaurantSettings.apiKeys.stats.version', 'API Version'), value: 'v1.0', color: 'hsl(var(--primary))' },
              { label: t('restaurantSettings.apiKeys.stats.baseUrl', 'Base URL'), value: apiBaseUrlDisplay, color: 'hsl(231, 40%, 45%)' },
            ].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-lg 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>
          <div className="rounded-2xl p-5 mb-6" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <h3 className="text-sm font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.apiKeys.usageChart', 'API Usage — Last 7 Days')}</h3>
            <SafeChart height={140}>
              <AreaChart data={usageData}>
                <defs><linearGradient id="apiGrad" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor="hsl(22, 89%, 48%)" stopOpacity={0.2} /><stop offset="95%" stopColor="hsl(22, 89%, 48%)" stopOpacity={0} /></linearGradient></defs>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" />
                <XAxis dataKey="day" tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} />
                <Tooltip contentStyle={{ fontSize: 12, borderRadius: 8, border: '1px solid hsl(220, 13%, 91%)' }} />
                <Area type="monotone" dataKey="calls" stroke="hsl(22, 89%, 48%)" strokeWidth={2} fill="url(#apiGrad)" />
              </AreaChart>
            </SafeChart>
          </div>
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('restaurantSettings.apiKeys.sectionHeading', 'API Keys')}</h3>
            <button className="btn-primary text-sm" onClick={() => setShowAddApiKey(!showAddApiKey)}><Plus size={15} /> {t('restaurantSettings.apiKeys.generateNew', 'Generate New Key')}</button>
          </div>
          {showAddApiKey && (
            <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('restaurantSettings.apiKeys.addForm.heading', 'Generate New API Key')}</h4>
                <button onClick={() => setShowAddApiKey(false)}><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('restaurantSettings.apiKeys.addForm.nameLabel', 'Key Name *')}</label><input type="text" placeholder={t('restaurantSettings.apiKeys.addForm.namePlaceholder', 'e.g. My POS Integration')} value={newApiKey.name} onChange={e => setNewApiKey(prev => ({ ...prev, name: e.target.value }))} className="input-base w-full" /></div>
                <div>
                  <label className="block text-xs font-semibold mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('restaurantSettings.apiKeys.addForm.permissionsLabel', 'Permissions *')}</label>
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                    {allPermissions.map(perm => (
                      <label key={perm} className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={newApiKey.permissions.includes(perm)} onChange={() => togglePermission(perm)} className="rounded" />
                        <span className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>{perm}</span>
                      </label>
                    ))}
                  </div>
                </div>
                <div className="flex gap-3">
                  <button className="btn-primary" onClick={handleGenerateApiKey} disabled={apiKeySaving || !newApiKey.name.trim()}>
                    {apiKeySaving ? <RefreshCw size={15} className="animate-spin" /> : <Key size={15} />} {t('restaurantSettings.apiKeys.generateKeyBtn', 'Generate Key')}
                  </button>
                  <button className="btn-secondary" onClick={() => setShowAddApiKey(false)}>{t('common.cancel', 'Cancel')}</button>
                </div>
              </div>
            </div>
          )}
          {apiKeysLoading && (
            <div className="flex items-center justify-center py-10 gap-2 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <RefreshCw size={16} className="animate-spin" /> {t('restaurantSettings.apiKeys.loading', 'Loading API keys…')}
            </div>
          )}
          <div className="space-y-3 mb-8">
            {!apiKeysLoading && apiKeys.length === 0 && (
              <div className="text-center py-10 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('restaurantSettings.apiKeys.emptyState', 'No API keys yet. Generate one above.')}</p>
              </div>
            )}
            {apiKeys.map(apiKey => {
              const isRevealed = revealedApiKeys.has(apiKey.id);
              const isCopied = copiedKeyId === apiKey.id;
              const isRevoked = apiKey.status === 'revoked';
              return (
                <div key={apiKey.id} className="rounded-2xl p-4" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', opacity: isRevoked ? 0.6 : 1 }}>
                  <div className="flex items-start gap-4">
                    <div className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0" style={{ backgroundColor: isRevoked ? 'hsl(220, 9%, 96%)' : 'hsl(var(--primary-light))', color: isRevoked ? 'hsl(220, 9%, 46%)' : 'hsl(var(--primary))' }}><Key size={16} /></div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{apiKey.name}</p>
                        {isRevoked && <span className="text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)' }}>{t('restaurantSettings.apiKeys.revokedBadge', 'Revoked')}</span>}
                      </div>
                      <div className="flex items-center gap-2 mb-2">
                        <code className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>{apiKey.keyPreview}</code>
                        <button onClick={() => copyApiKey(apiKey.id, apiKey.keyPreview)} className="p-0.5">{isCopied ? <CheckCircle size={12} style={{ color: 'hsl(142, 72%, 29%)' }} /> : <Copy size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />}</button>
                      </div>
                      <div className="flex flex-wrap gap-1 mb-2">{(Array.isArray(apiKey.permissions) ? apiKey.permissions : []).map(p => <span key={p} className="text-xs font-mono px-1.5 py-0.5 rounded" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>{p}</span>)}</div>
                      <div className="flex items-center gap-4 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        <span>{t('restaurantSettings.apiKeys.created', 'Created')} {new Date(apiKey.createdAt).toLocaleDateString()}</span>
                        {apiKey.lastUsedAt && <span>{t('restaurantSettings.apiKeys.lastUsed', 'Last used')}: {new Date(apiKey.lastUsedAt).toLocaleDateString()}</span>}
                        <span>{(apiKey.callsThisMonth ?? 0).toLocaleString()} {t('restaurantSettings.apiKeys.callsThisMonth', 'calls this month')}</span>
                      </div>
                    </div>
                    {!isRevoked && <button className="flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-lg transition-colors shrink-0" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 85%)' }} onClick={() => revokeApiKey(apiKey.id)}><Trash2 size={12} /> {t('restaurantSettings.apiKeys.revokeBtn', 'Revoke')}</button>}
                  </div>
                </div>
              );
            })}
          </div>
          <div>
            <button className="flex items-center gap-2 w-full text-left mb-3" onClick={() => setShowDocs(!showDocs)}>
              <Code size={16} style={{ color: 'hsl(var(--primary))' }} />
              <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('restApi.reference.title', 'API Endpoint Reference')}</h3>
              <span className="text-xs ml-1" style={{ color: 'hsl(var(--muted-foreground))' }}>({apiEndpoints(t).length} {t('restApi.reference.endpoints', 'endpoints')})</span>
              <div className="ml-auto">{showDocs ? <ChevronUp size={15} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <ChevronDown size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />}</div>
            </button>
            {showDocs && (
              <div className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="px-4 py-3 flex items-center gap-3" style={{ backgroundColor: 'hsl(231, 40%, 10%)', borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
                  <Globe size={14} className="text-white/60" />
                  <code className="text-xs text-white/80 font-mono">{t('restApi.reference.baseUrlPrefix', 'Base URL:')} {apiBaseUrlFull}</code>
                  <div className="ml-auto flex items-center gap-1.5"><Lock size={12} className="text-white/40" /><span className="text-xs text-white/40">{t('restApi.reference.auth', 'Bearer token required')}</span></div>
                </div>
                <div className="divide-y" style={{ borderColor: 'hsl(var(--border))' }}>
                  {apiEndpoints(t).map((ep, idx) => {
                    const mc = methodColors[ep.method] || methodColors.GET;
                    return (
                      <div key={idx} className="flex items-center gap-4 px-4 py-3">
                        <span className="text-xs font-mono font-bold px-2 py-0.5 rounded shrink-0 w-14 text-center" style={{ backgroundColor: mc.bg, color: mc.color }}>{ep.method}</span>
                        <code className="text-xs font-mono flex-1" style={{ color: 'hsl(var(--foreground))' }}>{ep.path}</code>
                        <span className="text-xs hidden sm:block" style={{ color: 'hsl(var(--muted-foreground))' }}>{ep.description}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ── Marketplace ── */}
      {activeTab === 'provider-keys' && (
        <ProviderKeysTab />
      )}

      {/* ── Email (SMTP) ── */}
      {activeTab === 'email-smtp' && canManageSmtp && (
        <EmailSmtpTab />
      )}

    </>
  );
}
