'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useSearchParams } from 'next/navigation';
import { MAIN_NAV_ITEMS, MORE_NAV_ITEMS, SAAS_ADMIN_NAV_ITEMS } from '@/lib/nav.config';
import { APP_CONFIG } from '@/config/app';
import { useBranding } from '@/context/BrandingContext';
import AppLogo from '@/components/common/AppLogo';
import { apiUrl } from '@/lib/utils/asset';

interface AppLayoutProps {
  children: React.ReactNode;
  currentRoute?: string;
  onAddPixel?: () => void;
  showAddPixelButton?: boolean;
}

export default function AppLayout({
  children,
  currentRoute,
}: AppLayoutProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const { branding } = useBranding();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  // Immediate reactive state for active menu selection on first click (0ms latency)
  const [optimisticRoute, setOptimisticRoute] = useState<string | null>(null);

  // Synchronize on pathname / currentRoute change
  useEffect(() => {
    setOptimisticRoute(null);
  }, [pathname, currentRoute]);

  // Synchronize on browser history navigation (Back/Forward)
  useEffect(() => {
    const handlePopState = () => {
      setOptimisticRoute(null);
    };
    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, []);

  const activeRoute = optimisticRoute || currentRoute || pathname || '/';

  const checkIsActive = (itemHref: string) => {
    let current = (activeRoute || '/').split('?')[0];
    if (current.startsWith('/meta-connector')) current = current.replace('/meta-connector', '') || '/';
    if (current.startsWith('/meta_connector')) current = current.replace('/meta_connector', '') || '/';

    let target = itemHref.split('?')[0];
    if (target.startsWith('/meta-connector')) target = target.replace('/meta-connector', '') || '/';
    if (target.startsWith('/meta_connector')) target = target.replace('/meta_connector', '') || '/';

    if (target === '/') {
      return current === '/' || current === '';
    }
    if (target === '/pixel') {
      return current === '/pixel' || current.startsWith('/pixel/');
    }
    return current === target || current.startsWith(`${target}/`);
  };

  const [storeInfo, setStoreInfo] = useState<{
    domain: string;
    plan: string;
    subscription_status?: string;
    trial_days_remaining?: number | null;
  }>({
    domain: '',
    plan: 'growth',
    subscription_status: 'active',
    trial_days_remaining: null,
  });

  useEffect(() => {
    const currentShop = searchParams?.get('shop') || searchParams?.get('shopify_domain');
    const shopsEndpoint = currentShop ? `/api/shops?shop=${encodeURIComponent(currentShop)}` : '/api/shops';
    fetch(apiUrl(shopsEndpoint))
      .then((r) => r.json())
      .then((data) => {
        if (data.success && data.store) {
          setStoreInfo({
            domain: data.store.domain || '',
            plan: data.store.plan || 'growth',
            subscription_status: data.store.subscription_status || 'active',
            trial_days_remaining: data.store.trial_days_remaining ?? null,
          });
        }
      })
      .catch(() => {});
  }, [searchParams]);

  const isSaasAdmin = (pathname && pathname.startsWith('/saas-admin')) || currentRoute === '/saas-admin';

  const getHref = (path: string) => {
    const qs = searchParams?.toString();
    let cleanPath = (path || '/').trim();
    // Strip all repeated subpath prefixes
    cleanPath = cleanPath.replace(/^(\/meta[-_]connector)+/i, '');
    if (!cleanPath.startsWith('/')) cleanPath = `/${cleanPath}`;
    const clean = cleanPath;
    if (!qs) return clean;
    return clean.includes('?') ? `${clean}&${qs}` : `${clean}?${qs}`;
  };

  const trackingItems = MAIN_NAV_ITEMS.filter((i) => i.section === 'tracking');
  const reportsItems = MAIN_NAV_ITEMS.filter((i) => i.section === 'reports');

  // Standard Built for Shopify Embedded App:
  // Strictly follows Shopify App Design Guidelines (https://shopify.dev/docs/apps/design)
  // No custom brand headers or secondary top navigation inside the embedded frame.
  // App Bridge provides native navigation (<s-app-nav>) and title bar (<ui-title-bar>).
  // saas-admin does NOT use Polaris and maintains its independent admin panel design.
  if (!isSaasAdmin) {
    return (
      <main className="min-h-screen bg-[#f1f1f1] text-[#303030] font-sans antialiased selection:bg-[#303030] selection:text-white">
        <div className="max-w-6xl w-full mx-auto px-4 sm:px-6 py-5 sm:py-6">
          {children}
        </div>
      </main>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50/70 text-slate-900 font-sans flex flex-col antialiased selection:bg-theme selection:text-white">
      {/* ---------------------------------------------------- */}
      {/* TOP ELEVATED BRAND & STATUS HEADER                   */}
      {/* ---------------------------------------------------- */}
      <header className="sticky top-0 z-40 bg-white/95 backdrop-blur-xl border-b border-slate-200/80 shadow-[0_1px_4px_rgba(0,0,0,0.02)]">
        <div className="max-w-7xl mx-auto px-3.5 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16 gap-2">
            {/* Left: Brand Identity */}
            <div className="flex items-center gap-2.5 sm:gap-3 min-w-0">
              <Link
                href={getHref('/pixel')}
                onClick={() => setOptimisticRoute('/pixel')}
                className="flex items-center gap-2.5 sm:gap-3 group min-w-0"
              >
                <AppLogo size="md" fallbackIcon="fa-brands fa-meta" />
                <div className="min-w-0">
                  <div className="flex items-center gap-1.5 sm:gap-2">
                    <span className="font-extrabold text-xs sm:text-sm text-slate-900 tracking-tight group-hover:text-theme transition-colors truncate">
                      {branding.appName}
                    </span>
                    <span
                      style={{ display: 'none' }}
                      className="hidden sm:inline-flex px-2 py-0.5 rounded-full text-[10px] font-extrabold uppercase tracking-wider bg-theme/10 text-theme border border-theme/20 shadow-2xs shrink-0"
                    >
                      CAPI Engine
                    </span>
                  </div>
                  <p className="text-[10px] sm:text-[11px] text-slate-400 font-medium hidden md:block truncate">
                    Advantage+ Catalog &bull; Server-Side CAPI &bull; Multi-Pixel
                  </p>
                </div>
              </Link>
            </div>

            {/* Right: Store Context & Actions */}
            <div className="flex items-center gap-1.5 sm:gap-3 shrink-0">
              {/* Store Identifier Pill */}
              <div style={{ display: 'none' }}>
                {storeInfo.domain ? (
                  <div className="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200/80 text-xs shadow-2xs">
                    <span className="relative flex h-2 w-2">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                      <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500" />
                    </span>
                    <span className="font-bold text-slate-700 max-w-[150px] md:max-w-[200px] truncate" title={storeInfo.domain}>
                      {storeInfo.domain}
                    </span>
                  </div>
                ) : (
                  <div className="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200/50 text-xs shadow-2xs animate-pulse">
                    <span className="h-2 w-2 rounded-full bg-slate-300" />
                    <div className="h-3 w-28 bg-slate-200 rounded" />
                  </div>
                )}
              </div>

              {/* Active Plan Pill */}
              <Link
                href={getHref('/pricing')}
                onClick={() => setOptimisticRoute('/pricing')}
                style={{ display: 'none' }}
                className="inline-flex items-center gap-1.5 px-2.5 sm:px-3 py-1.5 rounded-xl text-[11px] sm:text-xs font-bold bg-gradient-to-r bg-theme/10 hover:bg-theme/15 text-theme border border-theme/20 transition-all shadow-2xs whitespace-nowrap"
              >
                <i className="fa-solid fa-wand-magic-sparkles text-[10px] sm:text-xs text-theme" />
                <span className="capitalize">{storeInfo.plan} Plan</span>
                {storeInfo.subscription_status === 'trial' && (
                  <span className="text-[9px] sm:text-[10px] bg-theme text-white px-1.5 py-0.2 rounded-md font-extrabold">
                    Trial
                  </span>
                )}
              </Link>

              {/* Live XML Feed Link */}
              <a
                href={apiUrl(`/api/catalog/feed/meta.xml?shop=${encodeURIComponent(storeInfo.domain || '')}`)}
                target="_blank"
                rel="noreferrer"
                style={{ display: 'none' }}
                className="hidden lg:inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-semibold bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 transition-colors shadow-2xs"
                title="Open Live Catalog XML Feed"
              >
                <i className="fa-solid fa-rss text-xs text-amber-500" />
                <span>Feed XML</span>
                <i className="fa-solid fa-arrow-up-right-from-square text-[10px] text-slate-400" />
              </a>

              {/* Help Center Header Quick Link */}
              <Link
                href={getHref('/help')}
                onClick={() => setOptimisticRoute('/help')}
                className="inline-flex items-center gap-1.5 px-2.5 sm:px-3 py-1.5 rounded-xl text-xs font-semibold bg-white hover:bg-slate-50 border border-slate-200/80 text-slate-700 transition-colors shadow-2xs"
                title="Open Help Center & Step-by-Step Guides"
              >
                <i className="fa fa-book-open text-xs text-slate-500" />
                <span className="hidden sm:inline">Help &amp; Guides</span>
              </Link>

              {/* Mobile Menu Toggle Button */}
              {isSaasAdmin && (
                <button
                  type="button"
                  onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                  className="md:hidden p-2 rounded-xl text-slate-600 hover:text-slate-900 hover:bg-slate-100 transition-colors cursor-pointer border border-slate-200/80"
                  aria-label="Toggle Navigation Menu"
                >
                  {mobileMenuOpen ? <i className="fa-solid fa-xmark text-base" /> : <i className="fa-solid fa-bars text-base" />}
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Mobile Navigation Dropdown */}
        {mobileMenuOpen && isSaasAdmin && (
          <div className="md:hidden border-t border-slate-200/80 bg-white px-4 py-4 space-y-4 shadow-xl max-h-[85vh] overflow-y-auto animate-in slide-in-from-top-2 duration-200">
            {/* Store details on mobile */}
            {storeInfo.domain && (
              <div className="flex items-center justify-between p-2.5 rounded-xl bg-slate-50 border border-slate-200/80 text-xs">
                <div className="flex items-center gap-2 min-w-0">
                  <span className="relative flex h-2 w-2 shrink-0">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                    <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500" />
                  </span>
                  <span className="font-bold text-slate-700 truncate">{storeInfo.domain}</span>
                </div>
                <a
                  href={apiUrl(`/api/catalog/feed/meta.xml?shop=${encodeURIComponent(storeInfo.domain || '')}`)}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex items-center gap-1 text-[11px] font-semibold text-theme hover:underline shrink-0"
                >
                  <i className="fa-solid fa-rss text-amber-500" />
                  <span>Feed XML</span>
                </a>
              </div>
            )}

            {isSaasAdmin ? (
              <div className="space-y-1">
                <div className="text-[10px] font-bold uppercase tracking-wider text-purple-600 px-2 mb-1 flex items-center gap-1.5">
                  <i className="fa-solid fa-crown text-[10px] text-purple-600" />
                  <span>SaaS Administration</span>
                </div>
                {SAAS_ADMIN_NAV_ITEMS.map((item) => {
                  const isActive = checkIsActive(item.href);
                  return (
                    <Link
                      key={item.id}
                      href={getHref(item.href)}
                      onClick={() => {
                        setOptimisticRoute(item.href);
                        setMobileMenuOpen(false);
                      }}
                      className={`flex items-center justify-between px-3.5 py-2.5 rounded-xl text-xs font-semibold transition-all ${
                        isActive
                          ? 'bg-purple-900 text-white font-bold shadow-sm'
                          : 'text-slate-700 hover:bg-purple-50'
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <i className={`${item.faIcon || 'fa-solid fa-circle'} w-4 text-center text-xs ${isActive ? 'text-white' : 'text-purple-600'}`} />
                        <span>{item.label}</span>
                      </div>
                      {item.badge && (
                        <span className="text-[9px] px-2 py-0.5 rounded-full bg-purple-100 text-purple-800 font-bold">
                          {item.badge}
                        </span>
                      )}
                    </Link>
                  );
                })}

                <div className="pt-2 border-t border-slate-100">
                  <Link
                    href={getHref('/pixel')}
                    onClick={() => {
                      setOptimisticRoute('/pixel');
                      setMobileMenuOpen(false);
                    }}
                    className="flex items-center justify-between px-3.5 py-2.5 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-100"
                  >
                    <div className="flex items-center gap-2.5">
                      <i className="fa-solid fa-store w-4 text-center text-xs text-slate-500" />
                      <span>Single Store View</span>
                    </div>
                    <i className="fa-solid fa-chevron-right text-[10px] text-slate-400" />
                  </Link>
                </div>
              </div>
            ) : (
              <>
                <div className="space-y-1">
                  <div className="text-[10px] font-bold uppercase tracking-wider text-slate-400 px-2 mb-1 flex items-center gap-1.5">
                    <i className="fa-solid fa-satellite-dish text-[10px] text-theme" />
                    <span>Core Tracking</span>
                  </div>
                  {trackingItems.map((item) => {
                    const isActive = checkIsActive(item.href);
                    return (
                      <Link
                        key={item.id}
                        href={getHref(item.href)}
                        style={item.id === 'events' ? { display: 'none' } : undefined}
                        onClick={() => {
                          setOptimisticRoute(item.href);
                          setMobileMenuOpen(false);
                        }}
                        className={`flex items-center justify-between px-3.5 py-2.5 rounded-xl text-xs font-semibold transition-all ${
                          isActive
                            ? 'bg-slate-900 text-white font-bold shadow-sm'
                            : 'text-slate-700 hover:bg-slate-100'
                        }`}
                      >
                        <div className="flex items-center gap-2.5">
                          <i className={`${item.faIcon || 'fa-solid fa-circle'} w-4 text-center text-xs ${isActive ? 'text-theme' : 'text-slate-500'}`} />
                          <span>{item.label}</span>
                        </div>
                        {item.badge && (
                          <span className={`text-[9px] px-2 py-0.5 rounded-full font-bold uppercase ${isActive ? 'bg-emerald-500/20 text-emerald-300' : 'bg-emerald-50 text-emerald-700 border border-emerald-200/60'}`}>
                            {item.badge}
                          </span>
                        )}
                      </Link>
                    );
                  })}
                </div>

                <div style={{ display: 'none' }} className="space-y-1 pt-2 border-t border-slate-100">
                  <div className="text-[10px] font-bold uppercase tracking-wider text-slate-400 px-2 mb-1 flex items-center gap-1.5">
                    <i className="fa-solid fa-chart-pie text-[10px] text-theme" />
                    <span>Reports &amp; Intelligence</span>
                  </div>
                  {reportsItems.map((item) => {
                    const isActive = checkIsActive(item.href);
                    return (
                      <Link
                        key={item.id}
                        href={getHref(item.href)}
                        onClick={() => {
                          setOptimisticRoute(item.href);
                          setMobileMenuOpen(false);
                        }}
                        className={`flex items-center justify-between px-3.5 py-2.5 rounded-xl text-xs font-semibold transition-all ${
                          isActive
                            ? 'bg-slate-900 text-white font-bold shadow-sm'
                            : 'text-slate-700 hover:bg-slate-100'
                        }`}
                      >
                        <div className="flex items-center gap-2.5">
                          <i className={`${item.faIcon || 'fa-solid fa-chart-simple'} w-4 text-center text-xs ${isActive ? 'text-theme' : 'text-slate-500'}`} />
                          <span>{item.label}</span>
                        </div>
                      </Link>
                    );
                  })}
                </div>

                <div className="space-y-1 pt-2 border-t border-slate-100">
                  <div className="text-[10px] font-bold uppercase tracking-wider text-slate-400 px-2 mb-1 flex items-center gap-1.5">
                    <i className="fa-solid fa-gear text-[10px] text-slate-400" />
                    <span>System</span>
                  </div>
                  {MORE_NAV_ITEMS.map((item) => {
                    const isActive = checkIsActive(item.href);
                    return (
                      <Link
                        key={item.id}
                        href={getHref(item.href)}
                        style={item.id === 'diagnostics' ? { display: 'none' } : undefined}
                        onClick={() => {
                          setOptimisticRoute(item.href);
                          setMobileMenuOpen(false);
                        }}
                        className={`flex items-center justify-between px-3.5 py-2.5 rounded-xl text-xs font-semibold transition-all ${
                          isActive
                            ? 'bg-slate-900 text-white font-bold shadow-sm'
                            : 'text-slate-700 hover:bg-slate-100'
                        }`}
                      >
                        <div className="flex items-center gap-2.5">
                          <i className={`${item.faIcon || 'fa-solid fa-circle'} w-4 text-center text-xs ${isActive ? 'text-theme' : 'text-slate-500'}`} />
                          <span>{item.label}</span>
                        </div>
                      </Link>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        )}
      </header>

      {/* ---------------------------------------------------- */}
      {/* MAIN LAYOUT WRAPPER                                  */}
      {/* ---------------------------------------------------- */}
      <div className="flex-1 max-w-7xl w-full mx-auto p-3.5 sm:p-6 lg:p-8 flex flex-col md:flex-row gap-5 lg:gap-6 items-start">
        {/* LEFT SIDEBAR NAVIGATION (DESKTOP) */}
        <aside
          style={!isSaasAdmin ? { display: 'none' } : undefined}
          className="hidden md:block w-60 lg:w-64 shrink-0 bg-white rounded-3xl border border-slate-200/80 shadow-[0_2px_8px_rgba(0,0,0,0.03)] p-3.5 space-y-4 sticky top-20"
        >
          {isSaasAdmin ? (
            /* ==================================================== */
            /* SAAS ADMIN EXCLUSIVE NAVIGATION                      */
            /* ==================================================== */
            <>
              <div className="space-y-1">
                <div className="px-3 py-1.5 text-[10px] font-extrabold uppercase tracking-wider text-purple-600 flex items-center gap-1.5">
                  <i className="fa-solid fa-crown text-[10px] text-purple-600" />
                  <span>SaaS Administration</span>
                </div>
                {SAAS_ADMIN_NAV_ITEMS.map((item) => {
                  const isActive = checkIsActive(item.href);

                  return (
                    <Link
                      key={item.id}
                      href={getHref(item.href)}
                      onClick={() => setOptimisticRoute(item.href)}
                      className={`w-full flex items-center justify-between px-3.5 py-2.5 rounded-2xl text-xs font-bold transition-all ${
                        isActive
                          ? 'bg-purple-900 text-white shadow-sm shadow-purple-900/20'
                          : 'text-slate-600 hover:bg-purple-50 hover:text-purple-900'
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <i className={`${item.faIcon || 'fa-solid fa-circle'} w-4 text-center text-xs ${isActive ? 'text-white' : 'text-purple-600'}`} />
                        <span>{item.label}</span>
                      </div>
                      {item.badge && (
                        <span
                          className={`text-[9px] px-2 py-0.5 rounded-full font-extrabold uppercase tracking-wider ${
                            isActive
                              ? 'bg-purple-500/30 text-purple-200 border border-purple-400/40'
                              : 'bg-purple-50 text-purple-700 border border-purple-200'
                          }`}
                        >
                          {item.badge}
                        </span>
                      )}
                    </Link>
                  );
                })}
              </div>

              {/* Quick switch to merchant store */}
              <div className="pt-2 border-t border-slate-100 space-y-1">
                <div className="px-3 py-1 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">
                  Store App
                </div>
                <Link
                  href={getHref('/pixel')}
                  onClick={() => setOptimisticRoute('/pixel')}
                  className="w-full flex items-center justify-between px-3.5 py-2 rounded-2xl text-xs font-semibold text-slate-600 hover:bg-slate-100 hover:text-slate-900 transition-colors"
                >
                  <div className="flex items-center gap-2.5">
                    <i className="fa-solid fa-store w-4 text-center text-xs text-slate-500" />
                    <span>Single Store View</span>
                  </div>
                  <i className="fa-solid fa-chevron-right text-[10px] text-slate-400" />
                </Link>
              </div>
            </>
          ) : (
            /* ==================================================== */
            /* SINGLE STORE CONFIGURATION & MERCHANT VIEW NAVIGATION */
            /* ==================================================== */
            <>
              {/* SECTION 1: CORE TRACKING */}
              <div className="space-y-1">
                <div className="px-3 py-1 text-[10px] font-extrabold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                  <i className="fa-solid fa-satellite-dish text-[10px] text-theme" />
                  <span>Core Tracking</span>
                </div>
                {trackingItems.map((item) => {
                  const isActive = checkIsActive(item.href);

                  return (
                    <Link
                      key={item.id}
                      href={getHref(item.href)}
                      style={item.id === 'events' ? { display: 'none' } : undefined}
                      onClick={() => setOptimisticRoute(item.href)}
                      className={`w-full flex items-center justify-between px-3.5 py-2.5 rounded-2xl text-xs font-semibold transition-all ${
                        isActive
                          ? 'bg-slate-900 text-white shadow-md shadow-slate-900/15 font-bold'
                          : 'text-slate-600 hover:bg-slate-100/90 hover:text-slate-900'
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <i className={`${item.faIcon || 'fa-solid fa-circle'} w-4 text-center text-xs ${isActive ? 'text-theme' : 'text-slate-500'}`} />
                        <span>{item.label}</span>
                      </div>
                      {item.badge && (
                        <span
                          className={`text-[9px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider ${
                            isActive
                              ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-400/30'
                              : 'bg-emerald-50 text-emerald-700 border border-emerald-200/60'
                          }`}
                        >
                          {item.badge}
                        </span>
                      )}
                    </Link>
                  );
                })}
              </div>

              {/* SECTION 2: INTELLIGENCE & REPORTS */}
              <div style={{ display: 'none' }} className="space-y-1 pt-2 border-t border-slate-100">
                <div className="px-3 py-1 text-[10px] font-extrabold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                  <i className="fa-solid fa-chart-pie text-[10px] text-theme" />
                  <span>Intelligence &amp; Reports</span>
                </div>
                {reportsItems.map((item) => {
                  const isActive = checkIsActive(item.href);

                  return (
                    <Link
                      key={item.id}
                      href={getHref(item.href)}
                      onClick={() => setOptimisticRoute(item.href)}
                      className={`w-full flex items-center justify-between px-3.5 py-2.5 rounded-2xl text-xs font-semibold transition-all ${
                        isActive
                          ? 'bg-slate-900 text-white shadow-md shadow-slate-900/15 font-bold'
                          : 'text-slate-600 hover:bg-slate-100/90 hover:text-slate-900'
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <i className={`${item.faIcon || 'fa-solid fa-chart-simple'} w-4 text-center text-xs ${isActive ? 'text-theme' : 'text-slate-500'}`} />
                        <span>{item.label}</span>
                      </div>
                    </Link>
                  );
                })}
              </div>

              {/* SECTION 3: SYSTEM & CONFIGURATION (SINGLE STORE CONFIG) */}
              <div className="space-y-1 pt-2 border-t border-slate-100">
                <div className="px-3 py-1 text-[10px] font-extrabold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                  <i className="fa-solid fa-gear text-[10px] text-slate-400" />
                  <span>System</span>
                </div>
                {MORE_NAV_ITEMS.map((item) => {
                  const isActive = checkIsActive(item.href);

                  return (
                    <Link
                      key={item.id}
                      href={getHref(item.href)}
                      style={item.id === 'diagnostics' ? { display: 'none' } : undefined}
                      onClick={() => setOptimisticRoute(item.href)}
                      className={`w-full flex items-center justify-between px-3.5 py-2.5 rounded-2xl text-xs font-semibold transition-all ${
                        isActive
                          ? 'bg-slate-900 text-white shadow-md shadow-slate-900/15 font-bold'
                          : 'text-slate-600 hover:bg-slate-100/90 hover:text-slate-900'
                      }`}
                    >
                      <div className="flex items-center gap-2.5">
                        <i className={`${item.faIcon || 'fa-solid fa-circle'} w-4 text-center text-xs ${isActive ? 'text-theme' : 'text-slate-500'}`} />
                        <span>{item.label}</span>
                      </div>
                    </Link>
                  );
                })}
              </div>
            </>
          )}
        </aside>

        {/* RIGHT MAIN CONTENT AREA */}
        <main className="flex-1 w-full min-w-0">{children}</main>
      </div>

      {/* ---------------------------------------------------- */}
      {/* ELEVATED FOOTER                                      */}
      {/* ---------------------------------------------------- */}
      <footer className="mt-auto py-5 sm:py-6 border-t border-slate-200/80 bg-white/90 text-center text-xs text-slate-500 backdrop-blur-md">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col sm:flex-row items-center justify-between gap-3 text-center sm:text-left">
          <div className="flex flex-wrap items-center justify-center sm:justify-start gap-2">
            <i className="fa-solid fa-shield-halved text-emerald-600 text-sm" />
            <span className="font-bold text-slate-700">{branding.appName}</span>
            <span className="text-slate-300 hidden sm:inline">&bull;</span>
            <span className="text-slate-500 hidden sm:inline">Shopify App Bridge</span>
          </div>
          <div className="flex flex-wrap items-center justify-center sm:justify-end gap-x-4 gap-y-2 text-slate-500 font-medium text-xs">
            <Link href={getHref('/privacy')} className="hover:text-theme transition-colors">
              <i className="fa-solid fa-user-shield mr-1 text-[11px]" />
              Privacy
            </Link>
            <Link href={getHref('/terms')} className="hover:text-theme transition-colors">
              <i className="fa-solid fa-file-contract mr-1 text-[11px]" />
              Terms
            </Link>
            <a
              href={`mailto:${APP_CONFIG.supportEmail}`}
              className="text-theme hover:underline font-semibold"
              title="Email Support"
            >
              <i className="fa-solid fa-envelope mr-1 text-[11px]" />
              {APP_CONFIG.supportEmail}
            </a>
            <a
              href={`tel:${APP_CONFIG.supportPhoneRaw}`}
              className="text-slate-600 hover:text-slate-900 font-semibold"
              title="Call Support"
            >
              <i className="fa-solid fa-phone mr-1 text-[11px] text-emerald-600" />
              {APP_CONFIG.supportPhone}
            </a>
          </div>
        </div>
      </footer>
    </div>
  );
}

