'use client';

import React, { useState, useEffect, useRef } from 'react';
import { AdminRole } from '@/types';
import { useBranding } from '@/context/BrandingContext';
import { normalizeAssetUrl } from '@/lib/utils/asset';

interface BrandingSettingsProps {
  adminUser: {
    id: string;
    name: string;
    email: string;
    role: AdminRole;
  } | null;
}

export default function BrandingSettingsSection({ adminUser }: BrandingSettingsProps) {
  const { branding: globalBranding, refreshBranding } = useBranding();

  // Branding Form State
  const [appName, setAppName] = useState('DigiPixora — Meta Pixel & Ads');
  const [logoUrl, setLogoUrl] = useState<string | null>(normalizeAssetUrl('/images/logo.png'));
  const [faviconUrl, setFaviconUrl] = useState<string | null>(normalizeAssetUrl('/favicon.ico'));
  const [isSuperAdmin, setIsSuperAdmin] = useState(adminUser?.role === 'super_admin');
  const [lastUpdated, setLastUpdated] = useState<string | null>(null);
  const [lastUpdatedBy, setLastUpdatedBy] = useState<string | null>(null);

  // Local File Staging & Previews
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [logoPreview, setLogoPreview] = useState<string | null>(null);
  const [faviconFile, setFaviconFile] = useState<File | null>(null);
  const [faviconPreview, setFaviconPreview] = useState<string | null>(null);

  // Loading & Action States
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isResetting, setIsResetting] = useState(false);
  const [feedback, setFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
  const [showResetModal, setShowResetModal] = useState(false);

  // File Input Refs
  const logoInputRef = useRef<HTMLInputElement>(null);
  const faviconInputRef = useRef<HTMLInputElement>(null);

  // Keep isSuperAdmin synced with adminUser role
  useEffect(() => {
    setIsSuperAdmin(adminUser?.role === 'super_admin');
  }, [adminUser]);

  // Fetch current branding settings from backend API
  const fetchBranding = async () => {
    try {
      setIsLoading(true);
      const res = await fetch('/api/saas-admin/branding?t=' + Date.now());
      if (res.ok) {
        const data = await res.json();
        if (data.success && data.branding) {
          setAppName(data.branding.appName || 'DigiPixora — Meta Pixel & Ads');
          setLogoUrl(normalizeAssetUrl(data.branding.logoUrl || '/images/logo.png'));
          setFaviconUrl(normalizeAssetUrl(data.branding.faviconUrl || '/favicon.ico'));
          setLastUpdated(data.branding.updatedAt || null);
          setLastUpdatedBy(data.branding.updatedBy || null);
          if (data.isSuperAdmin !== undefined) {
            setIsSuperAdmin(data.isSuperAdmin);
          }
        }
      }
    } catch (err: any) {
      console.error('Failed to fetch branding settings:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchBranding();
  }, []);

  // Handle Logo file selection & frontend validation
  const handleLogoFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFeedback(null);
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate size (max 2MB)
    if (file.size > 2 * 1024 * 1024) {
      setFeedback({
        type: 'error',
        message: `Logo file size (${(file.size / (1024 * 1024)).toFixed(2)} MB) exceeds the 2MB limit.`,
      });
      return;
    }

    // Validate format
    const validFormats = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/svg+xml'];
    if (!validFormats.includes(file.type.toLowerCase()) && !file.name.match(/\.(png|jpe?g|webp|svg)$/i)) {
      setFeedback({
        type: 'error',
        message: 'Unsupported logo format. Please upload PNG, JPG, JPEG, SVG, or WebP.',
      });
      return;
    }

    setLogoFile(file);
    const previewUrl = URL.createObjectURL(file);
    setLogoPreview(previewUrl);
  };

  // Handle Favicon file selection & frontend validation
  const handleFaviconFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFeedback(null);
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate size (max 512KB)
    if (file.size > 512 * 1024) {
      setFeedback({
        type: 'error',
        message: `Favicon file size (${(file.size / 1024).toFixed(1)} KB) exceeds the 512KB limit.`,
      });
      return;
    }

    // Validate format
    const validFormats = [
      'image/x-icon',
      'image/vnd.microsoft.icon',
      'image/png',
      'image/svg+xml',
      'image/jpeg',
      'image/webp',
    ];
    if (!validFormats.includes(file.type.toLowerCase()) && !file.name.match(/\.(ico|png|svg|webp|jpe?g)$/i)) {
      setFeedback({
        type: 'error',
        message: 'Unsupported favicon format. Please upload .ico, .png, or .svg.',
      });
      return;
    }

    setFaviconFile(file);
    const previewUrl = URL.createObjectURL(file);
    setFaviconPreview(previewUrl);
  };

  // Upload an asset file to backend
  const uploadAsset = async (file: File, type: 'logo' | 'favicon'): Promise<string> => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);

    const res = await fetch('/api/saas-admin/branding/upload', {
      method: 'POST',
      body: formData,
    });

    const data = await res.json();
    if (!res.ok || !data.success) {
      throw new Error(data.error || `Failed to upload ${type}`);
    }

    return data.url;
  };

  // Save changes handler
  const handleSaveChanges = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!isSuperAdmin) {
      setFeedback({ type: 'error', message: 'Access denied: Only Super Administrators can save branding.' });
      return;
    }

    if (!appName.trim() || appName.trim().length < 2) {
      setFeedback({ type: 'error', message: 'Application Name must be at least 2 characters long.' });
      return;
    }

    try {
      setIsSaving(true);
      setFeedback(null);

      let finalLogoUrl = logoUrl;
      let finalFaviconUrl = faviconUrl;

      // 1. Upload new logo if staged
      if (logoFile) {
        finalLogoUrl = await uploadAsset(logoFile, 'logo');
      }

      // 2. Upload new favicon if staged
      if (faviconFile) {
        finalFaviconUrl = await uploadAsset(faviconFile, 'favicon');
      }

      // 3. Save branding configuration
      const res = await fetch('/api/saas-admin/branding', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          appName: appName.trim(),
          logoUrl: finalLogoUrl,
          faviconUrl: finalFaviconUrl,
        }),
      });

      const data = await res.json();
      if (!res.ok || !data.success) {
        throw new Error(data.error || 'Failed to update branding settings.');
      }

      // 4. Update local state
      setLogoUrl(finalLogoUrl);
      setFaviconUrl(finalFaviconUrl);
      setLogoFile(null);
      setLogoPreview(null);
      setFaviconFile(null);
      setFaviconPreview(null);
      setLastUpdated(data.branding.updatedAt || new Date().toISOString());
      setLastUpdatedBy(data.branding.updatedBy);

      // 5. Broadcast to global branding context
      window.dispatchEvent(
        new CustomEvent('app:branding_updated', {
          detail: {
            appName: data.branding.appName,
            logoUrl: data.branding.logoUrl,
            faviconUrl: data.branding.faviconUrl,
            updatedAt: data.branding.updatedAt,
          },
        })
      );
      await refreshBranding();

      setFeedback({
        type: 'success',
        message: 'Application branding updated successfully! All pages now reflect the new identity.',
      });
    } catch (err: any) {
      setFeedback({ type: 'error', message: err.message || 'An unexpected error occurred while saving.' });
    } finally {
      setIsSaving(false);
    }
  };

  // Reset to default handler
  const handleResetToDefault = async () => {
    if (!isSuperAdmin) return;
    try {
      setIsResetting(true);
      setShowResetModal(false);
      setFeedback(null);

      const res = await fetch('/api/saas-admin/branding/reset', {
        method: 'POST',
      });
      const data = await res.json();

      if (!res.ok || !data.success) {
        throw new Error(data.error || 'Failed to reset branding.');
      }

      setAppName('DigiPixora — Meta Pixel & Ads');
      setLogoUrl(null);
      setFaviconUrl(null);
      setLogoFile(null);
      setLogoPreview(null);
      setFaviconFile(null);
      setFaviconPreview(null);
      setLastUpdated(data.branding.updatedAt || new Date().toISOString());
      setLastUpdatedBy(data.branding.updatedBy);

      // Broadcast update
      window.dispatchEvent(
        new CustomEvent('app:branding_updated', {
          detail: {
            appName: 'DigiPixora — Meta Pixel & Ads',
            logoUrl: null,
            faviconUrl: null,
          },
        })
      );
      await refreshBranding();

      setFeedback({
        type: 'success',
        message: 'Branding restored to original default (DigiPixora — Meta Pixel & Ads).',
      });
    } catch (err: any) {
      setFeedback({ type: 'error', message: err.message || 'Error resetting branding.' });
    } finally {
      setIsResetting(false);
    }
  };

  // Staged logo display (either local preview, saved URL, or fallback)
  const activeLogoSrc = logoPreview || normalizeAssetUrl(logoUrl);
  const activeFaviconSrc = faviconPreview || normalizeAssetUrl(faviconUrl || '/favicon.ico');

  return (
    <div className="space-y-6">
      {/* Section Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-slate-200/80">
        <div>
          <div className="flex items-center gap-2">
            <h1 className="text-xl font-extrabold text-slate-900 tracking-tight">
              App Branding Management
            </h1>
            <span className="text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-theme/10 text-theme border border-theme/20">
              Live Dynamic Hub
            </span>
          </div>
          <p className="text-xs text-slate-400 mt-0.5">
            Dynamically update application name, logo, and favicon across all tenant dashboards and headers without code redeployments.
          </p>
        </div>

        {/* RBAC Permission Status Pill */}
        <div className="flex items-center gap-2">
          {isSuperAdmin ? (
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-xs font-bold bg-purple-50 text-purple-700 border border-purple-200 shadow-2xs">
              <i className="fa-solid fa-crown text-[11px]" />
              <span>Super Admin Access</span>
            </span>
          ) : (
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-xs font-bold bg-amber-50 text-amber-800 border border-amber-200 shadow-2xs">
              <i className="fa-solid fa-lock text-[11px]" />
              <span>Read-Only ({adminUser?.role.replace('_', ' ') || 'Admin'})</span>
            </span>
          )}
        </div>
      </div>

      {/* Feedback Toast */}
      {feedback && (
        <div
          className={`p-4 rounded-2xl border text-xs font-semibold flex items-center justify-between gap-3 shadow-2xs animate-in fade-in duration-200 ${
            feedback.type === 'success'
              ? 'bg-emerald-50 border-emerald-200 text-emerald-800'
              : 'bg-rose-50 border-rose-200 text-rose-800'
          }`}
        >
          <div className="flex items-center gap-2.5">
            <i
              className={`text-sm ${
                feedback.type === 'success' ? 'fa-solid fa-circle-check text-emerald-600' : 'fa-solid fa-circle-exclamation text-rose-600'
              }`}
            />
            <span>{feedback.message}</span>
          </div>
          <button
            type="button"
            onClick={() => setFeedback(null)}
            className="text-slate-400 hover:text-slate-600 p-1"
          >
            <i className="fa-solid fa-xmark text-xs" />
          </button>
        </div>
      )}

      {/* Main Settings Form */}
      <form onSubmit={handleSaveChanges} className="space-y-6 w-full">
            {/* CARD 1: APPLICATION NAME */}
            <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 text-xs font-bold text-slate-900 uppercase tracking-wider">
                  <i className="fa-solid fa-font text-theme" />
                  <span>Application Name</span>
                </div>
                <span className="text-[11px] text-slate-400 font-mono">
                  {appName.length}/100 chars
                </span>
              </div>

              <div className="space-y-1.5">
                <label htmlFor="app_name_input" className="block text-xs font-bold text-slate-700">
                  Global Application Display Name <span className="text-theme">*</span>
                </label>
                <input
                  id="app_name_input"
                  type="text"
                  value={appName}
                  onChange={(e) => setAppName(e.target.value)}
                  disabled={!isSuperAdmin || isSaving}
                  placeholder="e.g. DigiPixora — Meta Pixel & Ads"
                  maxLength={100}
                  className="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-xs text-slate-900 font-semibold focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme shadow-2xs transition-all disabled:bg-slate-50 disabled:text-slate-500"
                />
                <p className="text-[11px] text-slate-400 leading-relaxed">
                  Default: <strong className="text-slate-700">DigiPixora — Meta Pixel &amp; Ads</strong>. This name dynamically appears across the browser tab, header bars, login portals, navigation sidebars, and email communication.
                </p>
              </div>
            </div>

            {/* CARD 2: APPLICATION LOGO UPLOAD */}
            <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 text-xs font-bold text-slate-900 uppercase tracking-wider">
                  <i className="fa-solid fa-image text-theme" />
                  <span>Application Logo</span>
                </div>
                <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider bg-slate-100 px-2 py-0.5 rounded-md">
                  PNG &bull; JPG &bull; SVG &bull; WebP (Max 2MB)
                </span>
              </div>

              {/* Logo Preview Row */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {/* Active Logo */}
                <div className="p-4 rounded-xl border border-slate-200 bg-slate-50/70 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-[11px] font-bold text-slate-500 uppercase tracking-wider">
                      Currently Active Logo
                    </span>
                    {logoUrl ? (
                      <span className="text-[10px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
                        Custom Upload
                      </span>
                    ) : (
                      <span className="text-[10px] font-bold text-slate-600 bg-slate-200/80 px-2 py-0.5 rounded-full">
                        Default Icon
                      </span>
                    )}
                  </div>
                  <div className="h-20 flex items-center justify-center p-2 rounded-lg bg-white border border-slate-200/80 shadow-2xs">
                    {logoUrl ? (
                      <img
                        src={logoUrl}
                        alt="Current Logo"
                        className="max-h-full max-w-full object-contain"
                      />
                    ) : (
                      <div className="w-12 h-12 rounded-2xl bg-theme flex items-center justify-center text-white text-xl font-black shadow-sm">
                        {appName ? appName.charAt(0).toUpperCase() : 'D'}
                      </div>
                    )}
                  </div>
                  {logoUrl && isSuperAdmin && (
                    <button
                      type="button"
                      onClick={() => {
                        setLogoUrl(null);
                        setLogoFile(null);
                        setLogoPreview(null);
                      }}
                      className="text-[11px] text-rose-600 hover:text-rose-700 font-semibold inline-flex items-center gap-1 cursor-pointer"
                    >
                      <i className="fa-solid fa-trash-can text-[10px]" />
                      <span>Revert to Default Brand Icon</span>
                    </button>
                  )}
                </div>

                {/* Staged New Logo Preview */}
                <div className="p-4 rounded-xl border border-dashed border-slate-300 bg-white space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-[11px] font-bold text-slate-500 uppercase tracking-wider">
                      New Logo Staging
                    </span>
                    {logoFile && (
                      <span className="text-[10px] font-bold text-theme bg-theme/10 px-2 py-0.5 rounded-full border border-theme/20">
                        Ready to Save
                      </span>
                    )}
                  </div>
                  <div className="h-20 flex items-center justify-center p-2 rounded-lg bg-slate-50 border border-slate-100">
                    {logoPreview ? (
                      <img
                        src={logoPreview}
                        alt="New Logo Preview"
                        className="max-h-full max-w-full object-contain"
                      />
                    ) : (
                      <div className="text-center text-slate-400 text-xs">
                        <i className="fa-regular fa-image text-xl mb-1 text-slate-300 block" />
                        <span>No new image staged</span>
                      </div>
                    )}
                  </div>
                  {logoFile && (
                    <div className="flex items-center justify-between text-[11px]">
                      <span className="font-semibold text-slate-700 truncate max-w-[150px]">
                        {logoFile.name}
                      </span>
                      <button
                        type="button"
                        onClick={() => {
                          setLogoFile(null);
                          setLogoPreview(null);
                          if (logoInputRef.current) logoInputRef.current.value = '';
                        }}
                        className="text-slate-400 hover:text-slate-700 font-semibold cursor-pointer"
                      >
                        Cancel
                      </button>
                    </div>
                  )}
                </div>
              </div>

              {/* File Upload Selector */}
              {isSuperAdmin && (
                <div>
                  <input
                    ref={logoInputRef}
                    type="file"
                    accept=".png,.jpg,.jpeg,.svg,.webp"
                    onChange={handleLogoFileChange}
                    className="hidden"
                    id="logo-file-input"
                  />
                  <label
                    htmlFor="logo-file-input"
                    className="w-full flex items-center justify-center gap-2 p-3.5 rounded-xl border-2 border-dashed border-slate-300 hover:border-theme bg-slate-50/60 hover:bg-theme/5 cursor-pointer transition-colors text-xs font-semibold text-slate-700"
                  >
                    <i className="fa-solid fa-cloud-arrow-up text-theme text-sm" />
                    <span>Choose New Logo File (PNG, JPG, SVG, WebP)</span>
                  </label>
                </div>
              )}
            </div>

            {/* CARD 3: BROWSER FAVICON MANAGEMENT */}
            <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 text-xs font-bold text-slate-900 uppercase tracking-wider">
                  <i className="fa-solid fa-globe text-theme" />
                  <span>Browser Favicon</span>
                </div>
                <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider bg-slate-100 px-2 py-0.5 rounded-md">
                  ICO &bull; PNG &bull; SVG (Max 512KB)
                </span>
              </div>

              {/* Favicon Browser Tab Simulation */}
              <div className="space-y-2">
                <span className="text-[11px] font-bold text-slate-500 uppercase tracking-wider block">
                  Simulated Browser Tab Preview
                </span>
                <div className="bg-slate-200/70 p-3 rounded-2xl border border-slate-300/80">
                  <div className="max-w-xs inline-flex items-center gap-2.5 px-3.5 py-1.5 rounded-xl bg-white shadow-2xs border border-slate-200 text-xs">
                    <img
                      src={activeFaviconSrc}
                      alt="Favicon Preview"
                      className="w-4 h-4 rounded object-contain shrink-0"
                      onError={(e) => {
                        (e.target as HTMLImageElement).src = normalizeAssetUrl('/favicon.ico');
                      }}
                    />
                    <span className="font-semibold text-slate-800 text-[11px] truncate max-w-[180px]">
                      {appName} - Dashboard
                    </span>
                    <i className="fa-solid fa-xmark text-[10px] text-slate-400 ml-auto" />
                  </div>
                </div>
              </div>

              {/* Favicon Upload Selector */}
              {isSuperAdmin && (
                <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
                  <input
                    ref={faviconInputRef}
                    type="file"
                    accept=".ico,.png,.svg,.webp,.jpg,.jpeg"
                    onChange={handleFaviconFileChange}
                    className="hidden"
                    id="favicon-file-input"
                  />
                  <label
                    htmlFor="favicon-file-input"
                    className="flex-1 flex items-center justify-center gap-2 p-2.5 rounded-xl border border-slate-200 hover:border-theme bg-white hover:bg-slate-50 cursor-pointer text-xs font-semibold text-slate-700 transition-colors shadow-2xs"
                  >
                    <i className="fa-solid fa-arrow-up-from-bracket text-theme text-xs" />
                    <span>Upload Browser Favicon (.ico, .png, .svg)</span>
                  </label>
                  {(faviconPreview || faviconUrl) && (
                    <button
                      type="button"
                      onClick={() => {
                        setFaviconUrl(null);
                        setFaviconFile(null);
                        setFaviconPreview(null);
                        if (faviconInputRef.current) faviconInputRef.current.value = '';
                      }}
                      className="px-3 py-2 rounded-xl border border-slate-200 text-xs font-semibold text-slate-600 hover:text-rose-600 transition-colors cursor-pointer shrink-0"
                    >
                      Clear Custom Favicon
                    </button>
                  )}
                </div>
              )}
            </div>

            {/* CARD 4: APPLY BRANDING CHANGES (Added directly below Browser Favicon) */}
            <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1 pb-3 border-b border-slate-100">
                <span className="text-xs font-bold text-slate-900 uppercase tracking-wider flex items-center gap-1.5">
                  <i className="fa-solid fa-floppy-disk text-theme" />
                  <span>Apply Branding Changes</span>
                </span>
                {lastUpdated && (
                  <span className="text-[11px] text-slate-400">
                    Last updated: <span className="font-mono text-slate-600">{new Date(lastUpdated).toLocaleString()}</span>
                    {lastUpdatedBy ? ` by ${lastUpdatedBy}` : ''}
                  </span>
                )}
              </div>

              <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-1">
                <button
                  type="submit"
                  disabled={!isSuperAdmin || isSaving}
                  className="flex-1 py-2.5 px-4 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-xs hover:shadow-md transition-all flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSaving ? (
                    <>
                      <i className="fa-solid fa-arrows-rotate fa-spin text-xs" />
                      <span>Saving Branding Globally...</span>
                    </>
                  ) : (
                    <>
                      <i className="fa-solid fa-floppy-disk text-xs" />
                      <span>Save Changes Globally</span>
                    </>
                  )}
                </button>

                <button
                  type="button"
                  disabled={!isSuperAdmin || isResetting}
                  onClick={() => setShowResetModal(true)}
                  className="py-2.5 px-4 rounded-xl text-xs font-semibold border border-slate-200 hover:border-rose-300 text-slate-600 hover:text-rose-600 hover:bg-rose-50/50 transition-colors flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i className="fa-solid fa-rotate-left text-xs" />
                  <span>Reset to Default Branding</span>
                </button>
              </div>

              {!isSuperAdmin && (
                <p className="text-[11px] text-amber-700 bg-amber-50 p-2.5 rounded-xl border border-amber-200 font-medium">
                  <i className="fa-solid fa-lock mr-1" />
                  You are logged in as a <strong>{adminUser?.role.replace('_', ' ')}</strong>. Super Administrator privileges are required to save or reset global branding.
                </p>
              )}
            </div>
      </form>

      {/* CONFIRMATION RESET MODAL */}
      {showResetModal && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-3xl max-w-sm w-full p-6 shadow-2xl border border-slate-200 space-y-4 text-center animate-in zoom-in-95 duration-150">
            <div className="w-12 h-12 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center mx-auto text-xl">
              <i className="fa-solid fa-triangle-exclamation" />
            </div>

            <div className="space-y-1">
              <h3 className="font-extrabold text-base text-slate-900">
                Reset Branding to Default?
              </h3>
              <p className="text-xs text-slate-500 leading-relaxed">
                This will restore the Application Name to{' '}
                <strong className="text-slate-800">DigiPixora — Meta Pixel &amp; Ads</strong> and remove any custom uploaded logo and favicon across all tenant pages.
              </p>
            </div>

            <div className="grid grid-cols-2 gap-3 pt-2">
              <button
                type="button"
                onClick={() => setShowResetModal(false)}
                className="py-2.5 rounded-xl text-xs font-semibold border border-slate-200 text-slate-700 hover:bg-slate-50 cursor-pointer"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={handleResetToDefault}
                disabled={isResetting}
                className="py-2.5 rounded-xl text-xs font-bold bg-amber-600 hover:bg-amber-700 text-white shadow-sm flex items-center justify-center gap-1.5 cursor-pointer"
              >
                {isResetting && <i className="fa-solid fa-arrows-rotate fa-spin text-xs" />}
                <span>Confirm Reset</span>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
