-- Add ALL missing Arabic translations for Widget Settings and Storefront pages
-- This script inserts/updates translations for all keys used in these pages

DO $$
DECLARE
    _lang_code text := 'ar';
BEGIN

    -- First, ensure all translation keys exist
    INSERT INTO translation_keys (key, category, description, default_value) VALUES
        -- Widget Settings keys
        ('widgetSettings.saved', 'widget', 'Settings saved', 'Widget settings saved'),
        ('widgetSettings.failedToSave', 'widget', 'Failed to save', 'Failed to save'),
        ('widgetSettings.imageTooLarge', 'widget', 'Image too large error', 'Image must be 2 MB or smaller'),
        ('widgetSettings.iconUploaded', 'widget', 'Icon uploaded', 'Icon uploaded — save to apply'),
        ('widgetSettings.embedCopied', 'widget', 'Embed copied', 'Embed code copied!'),
        ('widgetSettings.status.enabled', 'widget', 'Widget enabled', 'Widget is enabled'),
        ('widgetSettings.status.disabled', 'widget', 'Widget disabled', 'Widget is disabled'),
        ('widgetSettings.status.enabledSubtitle', 'widget', 'Enabled subtitle', 'Visitors on your website will see the chat bubble'),
        ('widgetSettings.status.disabledSubtitle', 'widget', 'Disabled subtitle', 'The widget will not appear on your website'),
        ('widgetSettings.tabs.appearance', 'widget', 'Appearance tab', 'Appearance'),
        ('widgetSettings.tabs.behavior', 'widget', 'AI Agent tab', 'AI Agent'),
        ('widgetSettings.tabs.installation', 'widget', 'Embed tab', 'Embed'),
        ('widgetSettings.appearance.brandingTitle', 'widget', 'Branding title', 'Branding'),
        ('widgetSettings.appearance.botNameLabel', 'widget', 'Bot name label', 'Bot / Widget Name'),
        ('widgetSettings.appearance.botNamePlaceholder', 'widget', 'Bot name placeholder', 'AI Assistant'),
        ('widgetSettings.appearance.botNameSubtitle', 'widget', 'Bot name subtitle', 'Displayed in the chat header'),
        ('widgetSettings.appearance.botIconLabel', 'widget', 'Bot icon label', 'Bot Icon'),
        ('widgetSettings.appearance.botIconAlt', 'widget', 'Bot icon alt', 'Bot icon'),
        ('widgetSettings.appearance.uploadIcon', 'widget', 'Upload icon button', 'Upload Icon'),
        ('widgetSettings.appearance.iconSubtitle', 'widget', 'Icon subtitle', 'PNG, JPEG, GIF or WEBP · Max 2 MB · Save to apply'),
        ('widgetSettings.appearance.accentColorLabel', 'widget', 'Accent color label', 'Accent Color'),
        ('widgetSettings.appearance.positionLabel', 'widget', 'Position label', 'Widget Position'),
        ('widgetSettings.appearance.bottomRight', 'widget', 'Bottom right', '↘ Bottom Right'),
        ('widgetSettings.appearance.bottomLeft', 'widget', 'Bottom left', '↙ Bottom Left'),
        ('widgetSettings.appearance.messagingTitle', 'widget', 'Messaging title', 'Messaging'),
        ('widgetSettings.appearance.welcomeMessageLabel', 'widget', 'Welcome message label', 'Welcome Message'),
        ('widgetSettings.appearance.welcomeMessagePlaceholder', 'widget', 'Welcome placeholder', 'Hi! How can we help you today?'),
        ('widgetSettings.appearance.placeholderLabel', 'widget', 'Placeholder label', 'Input Placeholder'),
        ('widgetSettings.appearance.placeholderPlaceholder', 'widget', 'Placeholder placeholder', 'Type your message...'),
        ('widgetSettings.appearance.autoOpenLabel', 'widget', 'Auto-open label', 'Auto-open Delay'),
        ('widgetSettings.appearance.autoOpenSubtitle', 'widget', 'Auto-open subtitle', '0 disables auto-open'),
        ('widgetSettings.agent.selectTitle', 'widget', 'Select agent title', 'Select AI Agent'),
        ('widgetSettings.agent.selectSubtitle', 'widget', 'Select agent subtitle', 'Choose which AI agent powers this chat widget. Only active agents with the "chat" channel are shown.'),
        ('widgetSettings.agent.noAgentsTitle', 'widget', 'No agents title', 'No chat agents configured'),
        ('widgetSettings.agent.noAgentsSubtitle', 'widget', 'No agents subtitle', 'Go to AI Agent Config and create an agent with the "chat" channel enabled, then return here to select it.'),
        ('widgetSettings.agent.autoSelect', 'widget', 'Auto-select option', 'Auto-select (Recommended)'),
        ('widgetSettings.agent.autoSelectSubtitle', 'widget', 'Auto-select subtitle', 'Automatically uses your default chat agent. Best for most restaurants.'),
        ('widgetSettings.agent.pinnedTitle', 'widget', 'Pinned agent title', 'Pinned Agent Active'),
        ('widgetSettings.agent.pinnedSubtitle', 'widget', 'Pinned agent subtitle', 'All widget conversations will use {name}. Save to apply.'),
        ('widgetSettings.previewHint', 'widget', 'Preview hint', 'Save settings, then click Refresh to preview changes'),
        ('widgetSettings.configSummary', 'widget', 'Config summary', 'Configuration'),
        ('widgetSettings.position', 'widget', 'Position', 'Position'),
        ('widgetSettings.autoOpen', 'widget', 'Auto-open', 'Auto-open'),
        ('widgetSettings.autoOpenAfter', 'widget', 'Auto-open after', 'After {{sec}}s'),
        ('widgetSettings.aiAgent', 'widget', 'AI Agent', 'AI Agent'),
        ('widgetSettings.botIcon', 'widget', 'Bot Icon', 'Bot Icon'),
        ('widgetSettings.botIconCustom', 'widget', 'Custom icon', 'Custom'),
        ('widgetSettings.botIconDefault', 'widget', 'Default icon', 'Default emoji'),

        -- Widget keys (without Settings prefix)
        ('widget.setupSteps', 'widget', 'Setup steps title', 'Setup Steps'),
        ('widget.step1Title', 'widget', 'Step 1 title', 'Copy the embed code above'),
        ('widget.step1Desc', 'widget', 'Step 1 desc', 'Use the copy button to copy your unique snippet'),
        ('widget.step2Title', 'widget', 'Step 2 title', 'Paste before </body> on your site'),
        ('widget.step2Desc', 'widget', 'Step 2 desc', 'Add it to every page where you want the widget to appear'),
        ('widget.step3Title', 'widget', 'Step 3 title', 'Save — done!'),
        ('widget.step3Desc', 'widget', 'Step 3 desc', 'The widget loads automatically with your configured settings and chosen AI agent'),
        ('widget.capabilities', 'widget', 'Capabilities title', 'Widget Capabilities'),
        ('widget.cap.aiChat', 'widget', 'AI Chat capability', 'AI Chat'),
        ('widget.cap.aiChatDesc', 'widget', 'AI Chat desc', 'Instant AI-powered responses'),
        ('widget.cap.orderTaking', 'widget', 'Order Taking capability', 'Order Taking'),
        ('widget.cap.orderTakingDesc', 'widget', 'Order Taking desc', 'Customers can place orders'),
        ('widget.cap.tableBooking', 'widget', 'Table Booking capability', 'Table Booking'),
        ('widget.cap.tableBookingDesc', 'widget', 'Table Booking desc', 'Reserve tables through chat'),
        ('widget.cap.knowledgeBase', 'widget', 'Knowledge Base capability', 'Knowledge Base'),
        ('widget.cap.knowledgeBaseDesc', 'widget', 'Knowledge Base desc', 'Answers from your KB'),
        ('widget.cap.mobileReady', 'widget', 'Mobile Ready capability', 'Mobile Ready'),
        ('widget.cap.mobileReadyDesc', 'widget', 'Mobile Ready desc', 'Full-screen on small screens'),
        ('widget.cap.anyWebsite', 'widget', 'Any Website capability', 'Any Website'),
        ('widget.cap.anyWebsiteDesc', 'widget', 'Any Website desc', 'Works on any HTML site'),
        ('widget.using', 'widget', 'Using label', 'Using'),
        ('widget.customAgent', 'widget', 'Custom agent', 'Custom agent'),
        ('widget.autoSelectedDefaultAgent', 'widget', 'Auto-selected default', 'Auto-selected default agent'),
        ('widget.saveSettings', 'widget', 'Save settings button', 'Save Settings'),
        ('widget.reloadPreview', 'widget', 'Reload preview', 'Reload preview'),
        ('widget.refresh', 'widget', 'Refresh button', 'Refresh'),
        ('widget.livePreview', 'widget', 'Live preview', 'Live widget preview'),
        ('widget.callConnected', 'widget', 'Call connected', 'Call connected'),
        ('widget.callEnded', 'widget', 'Call ended', 'Call ended'),

        -- Storefront Editor keys
        ('storefront.editor.banner', 'storefront', 'Banner label', 'Storefront banner message'),
        ('storefront.editor.bannerPlaceholder', 'storefront', 'Banner placeholder', 'Holiday hours, special promo, etc.'),
        ('storefront.editor.delivery', 'storefront', 'Delivery label', 'Accept delivery'),
        ('storefront.editor.dineIn', 'storefront', 'Dine-in label', 'Accept dine-in (QR table)'),
        ('storefront.editor.downloadPdf', 'storefront', 'Download PDF button', 'Print-ready PDF'),
        ('storefront.editor.enabled', 'storefront', 'Enabled label', 'Storefront enabled'),
        ('storefront.editor.manageTables', 'storefront', 'Manage tables button', 'Manage tables'),
        ('storefront.editor.minOrder', 'storefront', 'Min order label', 'Minimum order'),
        ('storefront.editor.payInPersonNote', 'storefront', 'Pay in person note', 'Storefront orders are pay-in-person (cash on delivery / pay at counter).'),
        ('storefront.editor.qrCaption', 'storefront', 'QR caption', 'Branch storefront'),
        ('storefront.editor.qrDesignHelp', 'storefront', 'QR design help', 'This style is used for every table QR card and the printed PDF. Changes preview live.'),
        ('storefront.editor.qrDesignTitle', 'storefront', 'QR design title', 'QR design'),
        ('storefront.editor.restaurantSlugMissing', 'storefront', 'Restaurant slug missing', 'Set a restaurant slug in Settings before designing the QR.'),
        ('storefront.editor.save', 'storefront', 'Save button', 'Save storefront & QR'),
        ('storefront.editor.settingsTitle', 'storefront', 'Settings title', 'Storefront settings'),
        ('storefront.editor.slug', 'storefront', 'Slug label', 'Branch slug'),
        ('storefront.editor.slugHelp', 'storefront', 'Slug help', 'Used in the public URL — lowercase letters, digits, hyphens.'),
        ('storefront.editor.slugPlaceholder', 'storefront', 'Slug placeholder', 'downtown'),
        ('storefront.editor.takeaway', 'storefront', 'Takeaway label', 'Accept takeaway / pickup'),

        -- Common keys that might be missing
        ('common.uploading', 'common', 'Uploading', 'Uploading…'),
        ('common.remove', 'common', 'Remove', 'Remove'),
        ('common.characters', 'common', 'Characters', 'characters'),
        ('common.off', 'common', 'Off', 'Off'),
        ('common.enabled', 'common', 'Enabled', 'Enabled'),
        ('common.disabled', 'common', 'Disabled', 'Disabled'),
        ('common.active', 'common', 'Active', 'Active'),
        ('common.default', 'common', 'Default', 'Default')
    ON CONFLICT (key) DO NOTHING;

    -- Now insert/update all Arabic translations
    INSERT INTO translations (lang_code, key_id, value)
    SELECT
        _lang_code,
        tk.id,
        v.arabic_value
    FROM (
        VALUES
            -- Widget Settings translations
            ('widgetSettings.saved', 'تم حفظ إعدادات الأداة'),
            ('widgetSettings.failedToSave', 'فشل في الحفظ'),
            ('widgetSettings.imageTooLarge', 'يجب أن تكون الصورة 2 ميجابايت أو أقل'),
            ('widgetSettings.iconUploaded', 'تم رفع الأيقونة — احفظ للتطبيق'),
            ('widgetSettings.embedCopied', 'تم نسخ رمز التضمين!'),
            ('widgetSettings.status.enabled', 'الأداة مفعلة'),
            ('widgetSettings.status.disabled', 'الأداة معطلة'),
            ('widgetSettings.status.enabledSubtitle', 'سيظهر الزوار لموقعك فقاعة الدردشة'),
            ('widgetSettings.status.disabledSubtitle', 'لن تظهر الأداة على موقعك'),
            ('widgetSettings.tabs.appearance', 'المظهر'),
            ('widgetSettings.tabs.behavior', 'الوكيل الذكي'),
            ('widgetSettings.tabs.installation', 'تضمين'),
            ('widgetSettings.appearance.brandingTitle', 'العلامة التجارية'),
            ('widgetSettings.appearance.botNameLabel', 'اسم البوت / الأداة'),
            ('widgetSettings.appearance.botNamePlaceholder', 'مساعد الذكاء الاصطناعي'),
            ('widgetSettings.appearance.botNameSubtitle', 'يظهر في رأس الدردشة'),
            ('widgetSettings.appearance.botIconLabel', 'أيقونة البوت'),
            ('widgetSettings.appearance.botIconAlt', 'أيقونة البوت'),
            ('widgetSettings.appearance.uploadIcon', 'رفع الأيقونة'),
            ('widgetSettings.appearance.iconSubtitle', 'PNG أو JPEG أو GIF أو WEBP · بحد أقصى 2 ميجابايت · احفظ للتطبيق'),
            ('widgetSettings.appearance.accentColorLabel', 'لون التمييز'),
            ('widgetSettings.appearance.positionLabel', 'موضع الأداة'),
            ('widgetSettings.appearance.bottomRight', '↘ أسفل اليمين'),
            ('widgetSettings.appearance.bottomLeft', '↙ أسفل اليسار'),
            ('widgetSettings.appearance.messagingTitle', 'المراسلة'),
            ('widgetSettings.appearance.welcomeMessageLabel', 'رسالة الترحيب'),
            ('widgetSettings.appearance.welcomeMessagePlaceholder', 'مرحباً! كيف يمكننا مساعدتك اليوم؟'),
            ('widgetSettings.appearance.placeholderLabel', 'عنصر نائب الإدخال'),
            ('widgetSettings.appearance.placeholderPlaceholder', 'اكتب رسالتك...'),
            ('widgetSettings.appearance.autoOpenLabel', 'تأخير الفتح التلقائي'),
            ('widgetSettings.appearance.autoOpenSubtitle', '0 يُعطل الفتح التلقائي'),
            ('widgetSettings.agent.selectTitle', 'اختر الوكيل الذكي'),
            ('widgetSettings.agent.selectSubtitle', 'اختر الوكيل الذكي الذي يشغل هذه الأداة. يظهر فقط الوكلاء النشطون الذين لديهم قناة "الدردشة".'),
            ('widgetSettings.agent.noAgentsTitle', 'لم يتم تكوين وكلاء الدردشة'),
            ('widgetSettings.agent.noAgentsSubtitle', 'اذهب إلى إعداد الوكيل الذكي وأنشئ وكيلاً مع تفعيل قناة "الدردشة"، ثم عد هنا لتحديده.'),
            ('widgetSettings.agent.autoSelect', 'التحديد التلقائي (موصى به)'),
            ('widgetSettings.agent.autoSelectSubtitle', 'يستخدم وكيل الدردشة الافتراضي تلقائياً. الأفضل لمعظم المطاعم.'),
            ('widgetSettings.agent.pinnedTitle', 'الوكيل المثبت نشط'),
            ('widgetSettings.agent.pinnedSubtitle', 'ستستخدم جميع محادثات الأداة {name}. احفظ للتطبيق.'),
            ('widgetSettings.previewHint', 'احفظ الإعدادات، ثم انقر فوق تحديث لمعاينة التغييرات'),
            ('widgetSettings.configSummary', 'التكوين'),
            ('widgetSettings.position', 'الموضع'),
            ('widgetSettings.autoOpen', 'الفتح التلقائي'),
            ('widgetSettings.autoOpenAfter', 'بعد {{sec}} ثانية'),
            ('widgetSettings.aiAgent', 'الوكيل الذكي'),
            ('widgetSettings.botIcon', 'أيقونة البوت'),
            ('widgetSettings.botIconCustom', 'مخصص'),
            ('widgetSettings.botIconDefault', 'رمز تعبيري افتراضي'),

            -- Widget translations
            ('widget.setupSteps', 'خطوات الإعداد'),
            ('widget.step1Title', 'انسخ رمز التضمين أعلاه'),
            ('widget.step1Desc', 'استخدم زر النسخ لنسخ المقتطف الفريد الخاص بك'),
            ('widget.step2Title', 'الصق قبل </body> على موقعك'),
            ('widget.step2Desc', 'أضفه إلى كل صفحة تريد أن تظهر فيها الأداة'),
            ('widget.step3Title', 'حفظ — تم!'),
            ('widget.step3Desc', 'يتم تحميل الأداة تلقائياً باستخدام إعداداتك المكونة والوكيل الذكي المختار'),
            ('widget.capabilities', 'قدرات الأداة'),
            ('widget.cap.aiChat', 'دردشة ذكاء اصطناعي'),
            ('widget.cap.aiChatDesc', 'ردود فورية مدعومة بالذكاء الاصطناعي'),
            ('widget.cap.orderTaking', 'تلقى الطلبات'),
            ('widget.cap.orderTakingDesc', 'يمكن للعملاء تقديم الطلبات'),
            ('widget.cap.tableBooking', 'حجز الطاولات'),
            ('widget.cap.tableBookingDesc', 'احجز الطاولات عبر الدردشة'),
            ('widget.cap.knowledgeBase', 'قاعدة المعرفة'),
            ('widget.cap.knowledgeBaseDesc', 'إجابات من قاعدة المعرفة الخاصة بك'),
            ('widget.cap.mobileReady', 'جاهز للجوال'),
            ('widget.cap.mobileReadyDesc', 'ملء الشاشة على الشاشات الصغيرة'),
            ('widget.cap.anyWebsite', 'أي موقع ويب'),
            ('widget.cap.anyWebsiteDesc', 'يعمل على أي موقع HTML'),
            ('widget.using', 'باستخدام'),
            ('widget.customAgent', 'وكيل مخصص'),
            ('widget.autoSelectedDefaultAgent', 'الوكيل الافتراضي المحدد تلقائياً'),
            ('widget.saveSettings', 'حفظ الإعدادات'),
            ('widget.reloadPreview', 'إعادة تحميل المعاينة'),
            ('widget.refresh', 'تحديث'),
            ('widget.livePreview', 'معاينة الأداة مباشرة'),
            ('widget.callConnected', 'تم تواصل المكالمة'),
            ('widget.callEnded', 'انتهت المكالمة'),

            -- Storefront translations
            ('storefront.editor.banner', 'رسالة لافتة واجهة المتجر'),
            ('storefront.editor.bannerPlaceholder', 'ساعات العطلة، عروض خاصة، إلخ.'),
            ('storefront.editor.delivery', 'قبول التوصيل'),
            ('storefront.editor.dineIn', 'قبول الطعام في المكان (رمز الطاولة)'),
            ('storefront.editor.downloadPdf', 'ملف PDF جاهز للطباعة'),
            ('storefront.editor.enabled', 'واجهة المتجر مفعلة'),
            ('storefront.editor.manageTables', 'إدارة الطاولات'),
            ('storefront.editor.minOrder', 'الحد الأدنى للطلب'),
            ('storefront.editor.payInPersonNote', 'طلبات واجهة المتجر دفع عند الاستلام (نقداً عند التوصيل / الدفع في الطاولة).'),
            ('storefront.editor.qrCaption', 'واجهة المتجر للفرع'),
            ('storefront.editor.qrDesignHelp', 'يُستخدم هذا النمط لكل بطاقة رمز طاولة وملف PDF المطبوع. يتغير المعاينة مباشرة.'),
            ('storefront.editor.qrDesignTitle', 'تصميم الرمز'),
            ('storefront.editor.restaurantSlugMissing', 'عيّن رابط المطعم في الإعدادات قبل تصميم الرمز.'),
            ('storefront.editor.save', 'حفظ واجهة المتجر والرمز'),
            ('storefront.editor.settingsTitle', 'إعدادات واجهة المتجر'),
            ('storefront.editor.slug', 'رابط الفرع'),
            ('storefront.editor.slugHelp', 'يُستخدم في الرابط العام — أحرف صغيرة وأرقام وشرطات.'),
            ('storefront.editor.slugPlaceholder', 'وسط المدينة'),
            ('storefront.editor.takeaway', 'قبول الاستلام'),

            -- Common translations
            ('common.uploading', 'جارٍ الرفع...'),
            ('common.remove', 'إزالة'),
            ('common.characters', 'أحرف'),
            ('common.off', 'إيقاف'),
            ('common.enabled', 'مفعّل'),
            ('common.disabled', 'معطّل'),
            ('common.active', 'نشط'),
            ('common.default', 'افتراضي')
    ) AS v(key, arabic_value)
    JOIN translation_keys tk ON tk.key = v.key
    ON CONFLICT (lang_code, key_id) DO UPDATE SET value = EXCLUDED.value;

    RAISE NOTICE 'Widget and Storefront Arabic translations added successfully';
END $$;
