'use client';

import React, { useState, useEffect, useRef, Suspense } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import AppLayout from '@/components/layout/AppLayout';
import { SHOPIFY_CONFIG } from '@/config/shopify';
import { apiUrl, appRoute } from '@/lib/utils/asset';
import { scrollToFirstError, useFormErrorScroll } from '@/lib/utils/scroll-to-error';

interface ShopifyAppConfig {
  name: string;
  handle: string;
  clientId: string;
  apiVersion: string;
  appUrl: string;
  embedded: boolean;
  hmacStatus: string;
  scopes: string[];
  grantedScopes?: string[];
  requiredScopes?: string[];
  hasAllRequiredScopes?: boolean;
  reauthUrl?: string;
  webhooks: Array<{ topic: string; uri: string; status: string }>;
  gdprEndpoints: {
    customersDataRequest: string;
    customersRedact: string;
    shopRedact: string;
  };
}

function SettingsContent() {
  const searchParams = useSearchParams();
  const queryShop = searchParams?.get('shop') || searchParams?.get('shopify_domain') || '';
  const getHref = (path: string) => appRoute(path, queryShop);

  const [activeTab, setActiveTab] = useState<'shopify' | 'meta' | 'endpoints'>('shopify');
  const [activeShop, setActiveShop] = useState<string>(queryShop || SHOPIFY_CONFIG.defaultShopDomain);

  const [shopifyConfig, setShopifyConfig] = useState<ShopifyAppConfig | null>(null);
  const [shopDetails, setShopDetails] = useState<any>(null);

  const [shopifyTokenInput, setShopifyTokenInput] = useState('');
  const [isSavingShopifyToken, setIsSavingShopifyToken] = useState(false);
  const [shopifyTokenFeedback, setShopifyTokenFeedback] = useState<{
    type: 'success' | 'error';
    message: string;
  } | null>(null);

  const [metaStatus, setMetaStatus] = useState<'connected' | 'disconnected'>('disconnected');
  const [formData, setFormData] = useState({
    businessId: '',
    businessName: '',
    catalogId: '',
    catalogName: '',
    pixelId: '',
    pixelName: '',
    accessToken: '',
    testEventCode: '',
  });

  const [endpoints, setEndpoints] = useState({
    xmlFeedUrl: '',
    csvFeedUrl: '',
    capiWebhookUrl: '',
  });

  const [isLoading, setIsLoading] = useState(true);
  const [fetchError, setFetchError] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [isDisconnectingMeta, setIsDisconnectingMeta] = useState(false);
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  // Auto-scroll to error whenever settings form has an error
  useFormErrorScroll(saveError);
  useFormErrorScroll(shopifyTokenFeedback?.type === 'error' ? shopifyTokenFeedback.message : null);

  // Fetch settings from server
  const fetchSettings = async () => {
    setIsLoading(true);
    setFetchError(null);
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 9000);

    try {
      const targetShop = queryShop || activeShop || SHOPIFY_CONFIG.defaultShopDomain;
      const url = targetShop
        ? `/api/settings?shop=${encodeURIComponent(targetShop)}`
        : '/api/settings';

      const res = await fetch(apiUrl(url), {
        signal: controller.signal,
        headers: {
          Accept: 'application/json',
        },
      });

      clearTimeout(timeoutId);

      if (!res.ok && res.status >= 500) {
        throw new Error(`Server returned error status: ${res.status}`);
      }

      const data = await res.json();
      if (data.success) {
        if (data.shopifyApp) setShopifyConfig(data.shopifyApp);
        if (data.shop) {
          setShopDetails(data.shop);
          if (data.shop.domain) setActiveShop(data.shop.domain);
        } else if (targetShop) {
          setActiveShop(targetShop);
        }

        if (data.meta) {
          setFormData({
            businessId: data.meta.businessId || '',
            businessName: data.meta.businessName || '',
            catalogId: data.meta.catalogId || '',
            catalogName: data.meta.catalogName || '',
            pixelId: data.meta.pixelId || '',
            pixelName: data.meta.pixelName || '',
            accessToken: '',
            testEventCode: data.meta.testEventCode || '',
          });

          const isMetaConnected = Boolean(
            data.meta.status === 'connected' ||
            data.meta.businessId ||
            data.meta.pixelId ||
            data.meta.catalogId ||
            data.meta.hasAccessToken
          );
          setMetaStatus(isMetaConnected ? 'connected' : 'disconnected');
        }

        if (data.endpoints) setEndpoints(data.endpoints);
      } else {
        setFetchError(data.error || 'Failed to load configuration settings from server.');
      }
    } catch (err: any) {
      clearTimeout(timeoutId);
      const isTimeout = err?.name === 'AbortError';
      const msg = isTimeout
        ? 'Connection timed out while loading configuration. Please check your network and retry.'
        : (err?.message || 'Failed to load configuration settings.');
      console.error('Failed to load settings:', err);
      setFetchError(msg);
    } finally {
      clearTimeout(timeoutId);
      setIsLoading(false);
    }
  };

  // Mount effect & query shop dependency
  useEffect(() => {
    fetchSettings();

    // Listen for Meta OAuth popup success
    const handleAuthMessage = (event: MessageEvent) => {
      if (event.data?.type === 'META_AUTH_SUCCESS') {
        fetchSettings();
      }
    };
    window.addEventListener('message', handleAuthMessage);

    let bc: BroadcastChannel | null = null;
    try {
      if (typeof BroadcastChannel !== 'undefined') {
        bc = new BroadcastChannel('meta_auth_channel');
        bc.onmessage = (event) => {
          if (event.data?.type === 'META_AUTH_SUCCESS') {
            fetchSettings();
          }
        };
      }
    } catch {}

    const handleStorageEvent = (event: StorageEvent) => {
      if (event.key === 'meta_auth_success') {
        fetchSettings();
      }
    };
    window.addEventListener('storage', handleStorageEvent);

    return () => {
      window.removeEventListener('message', handleAuthMessage);
      window.removeEventListener('storage', handleStorageEvent);
      if (bc) bc.close();
    };
  }, [queryShop]);

  const handleReauthorizeShopify = async () => {
    const shop = activeShop || shopDetails?.domain || shopDetails?.shopify_domain || queryShop;
    if (shopifyConfig?.reauthUrl && shopifyConfig.reauthUrl.includes('/admin/oauth/authorize')) {
      if (window.top && window.top !== window) {
        window.top.location.href = shopifyConfig.reauthUrl;
      } else {
        window.location.href = shopifyConfig.reauthUrl;
      }
      return;
    }

    try {
      if (shop) {
        const res = await fetch(apiUrl(`/api/auth/shopify?shop=${encodeURIComponent(shop)}&format=json`));
        const data = await res.json();
        if (data.url) {
          if (window.top && window.top !== window) {
            window.top.location.href = data.url;
          } else {
            window.location.href = data.url;
          }
          return;
        }
      }
    } catch {}

    if (shop) {
      const apiKey = shopifyConfig?.clientId || process.env.NEXT_PUBLIC_SHOPIFY_API_KEY || 'd6d73fa2d424638f91826f822d89c51f';
      const redirectUri = encodeURIComponent(apiUrl('/api/auth/shopify/callback'));
      const scopes = encodeURIComponent('read_products,write_products,read_inventory,read_customer_events');
      const directUrl = `https://${shop}/admin/oauth/authorize?client_id=${apiKey}&scope=${scopes}&redirect_uri=${redirectUri}`;
      if (window.top && window.top !== window) {
        window.top.location.href = directUrl;
      } else {
        window.location.href = directUrl;
      }
    }
  };

  const openMetaOAuthPopup = () => {
    const width = 650;
    const height = 750;
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2;
    const shopDomain = activeShop || queryShop || SHOPIFY_CONFIG.defaultShopDomain;
    const authUrl = apiUrl(`/api/auth/meta?shop=${encodeURIComponent(shopDomain)}`);
    window.open(authUrl, 'meta_oauth_popup', `width=${width},height=${height},top=${top},left=${left},resizable=yes,scrollbars=yes,status=yes`);
  };

  const handleSaveShopifyToken = async (e: React.FormEvent) => {
    e.preventDefault();
    const tokenVal = shopifyTokenInput.trim();
    if (!tokenVal) return;

    if (tokenVal.startsWith('shpss_')) {
      setShopifyTokenFeedback({
        type: 'error',
        message: 'The token you entered starts with "shpss_", which is a Shopify API Secret Key, NOT an Access Token. A Shopify Admin API Access Token must start with "shpat_".',
      });
      return;
    }

    setIsSavingShopifyToken(true);
    setShopifyTokenFeedback(null);

    try {
      const res = await fetch(apiUrl('/api/settings'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          shopDomain: activeShop || queryShop,
          shopifyAccessToken: tokenVal,
        }),
      });

      const data = await res.json();
      if (data.success) {
        setShopifyTokenFeedback({
          type: 'success',
          message: 'Shopify Admin Access Token successfully saved and encrypted (AES-256-GCM).',
        });
        setShopifyTokenInput('');
        await fetchSettings();
      } else {
        setShopifyTokenFeedback({
          type: 'error',
          message: data.error || 'Failed to save Shopify API token.',
        });
      }
    } catch (err: any) {
      setShopifyTokenFeedback({
        type: 'error',
        message: err instanceof Error ? err.message : 'Network error saving token',
      });
    } finally {
      setIsSavingShopifyToken(false);
    }
  };

  const handleSaveMeta = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    setSaveSuccess(false);
    setSaveError(null);
    try {
      const res = await fetch(apiUrl('/api/settings'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          shopDomain: activeShop || queryShop,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setSaveSuccess(true);
        const hasAnyMeta = Boolean(formData.businessId || formData.pixelId || formData.catalogId || formData.accessToken);
        if (hasAnyMeta) setMetaStatus('connected');
        setTimeout(() => setSaveSuccess(false), 3000);
      } else {
        setSaveError(data.error || 'Failed to save Meta credentials.');
      }
    } catch (err: any) {
      console.error(err);
      setSaveError(err?.message || 'Network error saving Meta credentials.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDisconnectMeta = async () => {
    if (!confirm('Are you sure you want to disconnect your Meta credentials? Your Shopify connection will remain intact.')) {
      return;
    }
    setIsDisconnectingMeta(true);
    try {
      const res = await fetch(apiUrl('/api/meta/connect'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          shopDomain: activeShop || queryShop,
          disconnect: true,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setMetaStatus('disconnected');
        setFormData({
          businessId: '',
          businessName: '',
          catalogId: '',
          catalogName: '',
          pixelId: '',
          pixelName: '',
          accessToken: '',
          testEventCode: '',
        });
        await fetchSettings();
      }
    } catch (err) {
      console.error('Failed to disconnect Meta:', err);
    } finally {
      setIsDisconnectingMeta(false);
    }
  };

  const handleCopy = (text: string, key: string) => {
    if (!text) return;
    navigator.clipboard.writeText(text);
    setCopiedKey(key);
    setTimeout(() => setCopiedKey(null), 2000);
  };

  return (
    <AppLayout currentRoute="/settings">
      <ui-title-bar title="Settings & Configuration" />
      <div className="space-y-6">
        {/* Header & Store Selector */}
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-slate-200/80 pb-4">
          <div>
            <div className="flex items-center gap-2 text-xs font-semibold text-theme uppercase tracking-wider">
              <i className="fa-solid fa-gear text-xs" />
              <span>App Configuration &amp; Partner Settings</span>
            </div>
            <h1 className="text-2xl font-bold text-slate-900 tracking-tight mt-1">
              Shopify &amp; Meta Configuration
            </h1>
            <p className="text-xs text-slate-500">
              View and manage Shopify App Bridge configurations, API access scopes, webhooks, and Meta credentials.
            </p>
          </div>

          {/* Verified Store Badge */}
          <div className="flex items-center gap-2 bg-white border border-slate-200/80 rounded-xl px-3 py-1.5 shadow-2xs text-xs">
            <i className="fa-solid fa-store text-emerald-600 text-xs" />
            <span className="font-semibold text-slate-800">{activeShop || SHOPIFY_CONFIG.defaultShopDomain}</span>
            <span className="text-[10px] text-emerald-700 bg-emerald-50 border border-emerald-200/60 px-2 py-0.5 rounded-full font-bold uppercase">
              {shopDetails?.plan || 'Growth'}
            </span>
          </div>
        </div>

        {/* Configuration Tabs */}
        <div className="flex items-center gap-2 border-b border-slate-200/80 pb-2 text-xs font-semibold overflow-x-auto max-w-full">
          <button
            onClick={() => setActiveTab('shopify')}
            className={`px-3.5 py-2 rounded-xl flex items-center gap-2 transition-all cursor-pointer shrink-0 ${
              activeTab === 'shopify'
                ? 'bg-theme text-white font-bold shadow-sm'
                : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
            }`}
          >
            <i className="fa-solid fa-store text-sm" />
            <span>Shopify App Configuration</span>
            <span className="px-1.5 py-0.2 rounded-full text-[9px] bg-emerald-500 text-white font-bold">
              Live
            </span>
          </button>

          <button
            onClick={() => setActiveTab('meta')}
            className={`px-3.5 py-2 rounded-xl flex items-center gap-2 transition-all cursor-pointer shrink-0 ${
              activeTab === 'meta'
                ? 'bg-theme text-white font-bold shadow-sm'
                : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
            }`}
          >
            <i className="fa-solid fa-building text-sm" />
            <span>Meta Assets &amp; CAPI</span>
            <span
              className={`px-1.5 py-0.2 rounded-full text-[9px] font-bold ${
                metaStatus === 'connected'
                  ? 'bg-emerald-500 text-white'
                  : 'bg-slate-200 text-slate-700'
              }`}
            >
              {metaStatus === 'connected' ? 'Connected' : 'Manual / Idle'}
            </span>
          </button>

          <button
            onClick={() => setActiveTab('endpoints')}
            className={`px-3.5 py-2 rounded-xl flex items-center gap-2 transition-all cursor-pointer shrink-0 ${
              activeTab === 'endpoints'
                ? 'bg-theme text-white font-bold shadow-sm'
                : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
            }`}
          >
            <i className="fa-solid fa-network-wired text-sm" />
            <span>Feeds &amp; Webhooks</span>
          </button>
        </div>

        {/* Documentation & Help Guides Pill Bar */}
        <div className="flex flex-wrap items-center gap-2 text-xs bg-indigo-50/70 border border-indigo-100 rounded-xl p-2.5 px-3.5">
          <span className="font-bold text-indigo-950 flex items-center gap-1.5">
            <i className="fa-solid fa-book-open text-indigo-600" />
            <span>Setup Guides:</span>
          </span>
          <Link
            href={getHref('/help?guide=app-checklist')}
            target="_blank"
            className="px-2.5 py-1 rounded-lg bg-white border border-indigo-200 text-indigo-700 hover:bg-indigo-600 hover:text-white transition-colors font-medium text-[11px] inline-flex items-center gap-1"
          >
            <span>App Checklist</span>
            <i className="fa-solid fa-arrow-up-right-from-square text-[9px]" />
          </Link>
          <Link
            href={getHref('/help?guide=advanced-settings')}
            target="_blank"
            className="px-2.5 py-1 rounded-lg bg-white border border-indigo-200 text-indigo-700 hover:bg-indigo-600 hover:text-white transition-colors font-medium text-[11px] inline-flex items-center gap-1"
          >
            <span>Advanced Tracking (COD / Renewals)</span>
            <i className="fa-solid fa-arrow-up-right-from-square text-[9px]" />
          </Link>
          <Link
            href={getHref('/help?guide=bot-fraud-protection')}
            target="_blank"
            className="px-2.5 py-1 rounded-lg bg-white border border-indigo-200 text-indigo-700 hover:bg-indigo-600 hover:text-white transition-colors font-medium text-[11px] inline-flex items-center gap-1"
          >
            <span>Bot &amp; Fraud Shield</span>
            <i className="fa-solid fa-arrow-up-right-from-square text-[9px]" />
          </Link>
          <Link
            href={getHref('/help?guide=consent-tracking')}
            target="_blank"
            className="px-2.5 py-1 rounded-lg bg-white border border-indigo-200 text-indigo-700 hover:bg-indigo-600 hover:text-white transition-colors font-medium text-[11px] inline-flex items-center gap-1"
          >
            <span>Consent &amp; GDPR Mode</span>
            <i className="fa-solid fa-arrow-up-right-from-square text-[9px]" />
          </Link>
        </div>

        {/* Error State with Retry Button */}
        {!isLoading && fetchError && (
          <div className="bg-white rounded-2xl border border-rose-200 p-6 sm:p-8 text-center space-y-4 shadow-sm">
            <div className="w-12 h-12 rounded-2xl bg-rose-50 border border-rose-200 text-rose-600 flex items-center justify-center mx-auto text-xl">
              <i className="fa-solid fa-triangle-exclamation" />
            </div>
            <div>
              <h3 className="font-bold text-slate-900 text-base">Unable to Load Configuration</h3>
              <p className="text-xs text-slate-500 mt-1 max-w-md mx-auto">{fetchError}</p>
            </div>
            <div className="pt-2 flex items-center justify-center gap-3">
              <button
                type="button"
                onClick={fetchSettings}
                className="px-4 py-2 rounded-xl bg-theme hover:bg-theme-hover text-white text-xs font-bold shadow-sm transition flex items-center gap-2 cursor-pointer"
              >
                <i className="fa-solid fa-arrows-rotate text-xs" />
                <span>Retry Loading</span>
              </button>
              <button
                type="button"
                onClick={handleReauthorizeShopify}
                className="px-4 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold transition flex items-center gap-2 cursor-pointer"
              >
                <i className="fa-solid fa-shield-halved text-xs" />
                <span>Re-authenticate Shopify</span>
              </button>
            </div>
          </div>
        )}

        {/* Loading State */}
        {isLoading ? (
          <div className="py-20 text-center text-slate-400 flex items-center justify-center gap-2 bg-white rounded-2xl border border-slate-200/80 shadow-2xs">
            <i className="fa-solid fa-arrows-rotate text-lg fa-spin text-theme" />
            <span className="text-sm font-medium text-slate-600">Loading configuration...</span>
          </div>
        ) : !fetchError && (
          <>
            {/* TAB 1: SHOPIFY APP CONFIGURATION */}
            {activeTab === 'shopify' && (
              <div className="space-y-6">
                {/* App Overview Card */}
                <div className="bg-white p-4 sm:p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-100 pb-4">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-700 flex items-center justify-center font-bold shrink-0">
                        <i className="fa-solid fa-store text-base" />
                      </div>
                      <div>
                        <h3 className="font-bold text-slate-900 text-sm">
                          {shopifyConfig?.name || 'Meta Commerce & Pixel Connector'}
                        </h3>
                        <p className="text-xs text-slate-400 break-all">
                          App Handle: <code className="text-slate-600 font-mono">{shopifyConfig?.handle || 'meta-commerce-pixel-connector'}</code> · API v{shopifyConfig?.apiVersion || SHOPIFY_CONFIG.apiVersion}
                        </p>
                      </div>
                    </div>
                    <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200 self-start sm:self-auto shrink-0">
                      <i className="fa-solid fa-circle-check text-emerald-600 text-xs" /> Embedded App Active
                    </span>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
                    <div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200/80">
                      <span className="text-slate-400 font-medium">Connected Shopify Store Domain</span>
                      <div className="font-semibold text-slate-900 mt-1 flex items-center gap-2">
                        <span>{activeShop}</span>
                        <a
                          href={`https://${activeShop}/admin`}
                          target="_blank"
                          rel="noreferrer"
                          className="text-theme hover:text-theme-hover"
                          title="Open Shopify Admin"
                        >
                          <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                        </a>
                      </div>
                    </div>

                    <div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200/80">
                      <span className="text-slate-400 font-medium">Shopify Security & HMAC Verification</span>
                      <div className="font-semibold text-emerald-700 mt-1 flex items-center gap-1.5">
                        <i className="fa-solid fa-lock text-emerald-600 text-xs" />
                        <span>{shopifyConfig?.hmacStatus || 'Timing-Safe Verified (crypto.timingSafeEqual)'}</span>
                      </div>
                    </div>

                    <div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200/80">
                      <span className="text-slate-400 font-medium">Active Subscription Tier</span>
                      <div className="font-semibold text-slate-900 mt-1 capitalize flex items-center gap-1.5">
                        <i className="fa-solid fa-wand-magic-sparkles text-theme text-xs" />
                        <span>{shopDetails?.plan || 'Growth'} Plan</span>
                      </div>
                    </div>

                    <div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200/80">
                      <span className="text-slate-400 font-medium">Shopify GraphQL Admin API Status</span>
                      <div className="font-semibold text-slate-900 mt-1 flex items-center gap-1.5">
                        {shopDetails?.hasShopifyToken ? (
                          <>
                            <i className="fa-solid fa-circle-check text-emerald-600 text-xs" />
                            <span className="text-emerald-700">Token Connected &amp; Ready</span>
                          </>
                        ) : (
                          <>
                            <i className="fa-solid fa-circle-exclamation text-amber-500 text-xs" />
                            <span className="text-amber-700">Custom API Token / OAuth Required</span>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                {/* Custom API Token Form Card */}
                <div className="bg-white p-4 sm:p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
                  <div className="border-b border-slate-100 pb-3">
                    <h3 className="font-semibold text-sm text-slate-900">
                      Custom Shopify Admin API Access Token
                    </h3>
                    <p className="text-xs text-slate-500 mt-0.5">
                      Configure a custom Admin API access token for automated background synchronization and GraphQL webhooks.
                    </p>
                  </div>

                  <form onSubmit={handleSaveShopifyToken} className="space-y-3">
                    <div>
                      <label className="text-xs font-semibold text-slate-700 block">
                        Admin API Access Token (Starts with <code className="font-mono text-theme">shpat_</code>)
                      </label>
                      <div className="flex flex-col sm:flex-row gap-2 mt-1">
                        <input
                          type="password"
                          value={shopifyTokenInput}
                          onChange={(e) => setShopifyTokenInput(e.target.value)}
                          placeholder="shpat_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                          className="flex-1 p-2.5 rounded-xl border border-slate-200 text-xs font-mono focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                        />
                        <button
                          type="submit"
                          disabled={isSavingShopifyToken || !shopifyTokenInput.trim()}
                          className="px-4 py-2.5 rounded-xl bg-theme hover:bg-theme-hover text-white text-xs font-bold shadow-xs transition flex items-center justify-center gap-2 disabled:opacity-50 cursor-pointer shrink-0"
                        >
                          <i className={`fa-solid ${isSavingShopifyToken ? 'fa-spinner fa-spin' : 'fa-lock'} text-xs`} />
                          <span>{isSavingShopifyToken ? 'Encrypting & Saving...' : 'Save & Encrypt Token'}</span>
                        </button>
                      </div>
                      <p className="text-[11px] text-slate-400 mt-1">
                        Tokens are encrypted in your MySQL database using AES-256-GCM authenticated encryption.
                      </p>
                    </div>

                    {shopifyTokenFeedback && (
                      <div
                        className={`p-3 rounded-xl text-xs flex items-center gap-2 ${
                          shopifyTokenFeedback.type === 'success'
                            ? 'bg-emerald-50 border border-emerald-200 text-emerald-800'
                            : 'bg-rose-50 border border-rose-200 text-rose-800'
                        }`}
                      >
                        <i
                          className={`fa-solid ${
                            shopifyTokenFeedback.type === 'success'
                              ? 'fa-circle-check text-emerald-600'
                              : 'fa-circle-exclamation text-rose-600'
                          } text-xs shrink-0`}
                        />
                        <span>{shopifyTokenFeedback.message}</span>
                      </div>
                    )}
                  </form>
                </div>

                {/* Granted Access Scopes Card */}
                <div className="bg-white p-4 sm:p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-100 pb-3">
                    <div>
                      <h3 className="font-semibold text-sm text-slate-900">Authorized Shopify Access Scopes</h3>
                      <p className="text-xs text-slate-500 mt-0.5">
                        Permissions granted by your store for Meta Catalog Sync and Marketing:
                      </p>
                    </div>
                    <button
                      type="button"
                      onClick={handleReauthorizeShopify}
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-theme hover:bg-theme-hover text-white rounded-xl text-xs font-semibold transition-colors shadow-xs shrink-0 self-start sm:self-auto cursor-pointer"
                    >
                      <i className="fa-solid fa-arrows-rotate text-xs" />
                      <span>Re-authorize Permissions on Shopify</span>
                    </button>
                  </div>

                  {shopifyConfig?.hasAllRequiredScopes === false && (
                    <div className="p-3 bg-amber-50 border border-amber-200 rounded-xl text-xs text-amber-900 flex items-start gap-2.5">
                      <i className="fa-solid fa-triangle-exclamation text-amber-600 mt-0.5 shrink-0" />
                      <div>
                        <p className="font-semibold">Missing required permission: &quot;read_products&quot;</p>
                        <p className="text-[11px] text-amber-700 mt-0.5">
                          Your store currently lacks permission to read catalog products. Click &quot;Re-authorize Permissions on Shopify&quot; above to approve full access in 1 click.
                        </p>
                      </div>
                    </div>
                  )}

                  <div className="flex flex-wrap gap-2 text-xs">
                    {(shopifyConfig?.scopes || SHOPIFY_CONFIG.scopesArray).map((scope, i) => (
                      <div
                        key={i}
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-theme/10 border border-theme/20 text-theme font-mono font-medium"
                      >
                        <i className="fa-solid fa-check text-theme text-xs" />
                        <span>{scope}</span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Webhooks & GDPR Compliance */}
                <div className="bg-white p-4 sm:p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
                  <div className="border-b border-slate-100 pb-3">
                    <h3 className="font-semibold text-sm text-slate-900">Registered Shopify Webhooks &amp; GDPR Endpoints</h3>
                    <p className="text-xs text-slate-500 mt-0.5">
                      Shopify lifecycle listeners active on your store domain:
                    </p>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-xs">
                    {(shopifyConfig?.webhooks || [
                      { topic: 'products/create', uri: '/api/webhooks/shopify', status: 'Active' },
                      { topic: 'products/update', uri: '/api/webhooks/shopify', status: 'Active' },
                      { topic: 'products/delete', uri: '/api/webhooks/shopify', status: 'Active' },
                      { topic: 'app/uninstalled', uri: '/api/webhooks/shopify', status: 'Active' },
                    ]).map((hook, idx) => (
                      <div key={idx} className="p-3 rounded-xl bg-slate-50 border border-slate-200/80 flex items-center justify-between">
                        <div>
                          <span className="font-mono font-bold text-slate-800">{hook.topic}</span>
                          <p className="text-[10px] text-slate-400 mt-0.5 font-mono truncate max-w-[220px]">{hook.uri}</p>
                        </div>
                        <span className="text-[10px] px-2 py-0.5 rounded-full font-bold bg-emerald-100 text-emerald-800 shrink-0">
                          {hook.status}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* TAB 2: META ASSETS & CREDENTIALS */}
            {activeTab === 'meta' && (
              <div className="space-y-6">
                {/* Meta Connection Status Card */}
                <div className="bg-white p-4 sm:p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-100 pb-4">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-xl bg-blue-50 border border-blue-200 text-blue-600 flex items-center justify-center font-bold shrink-0">
                        <i className="fa-brands fa-meta text-lg" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <h3 className="font-bold text-slate-900 text-sm">Meta Business &amp; CAPI Status</h3>
                          <span
                            className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${
                              metaStatus === 'connected'
                                ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                                : 'bg-slate-100 text-slate-600 border border-slate-200'
                            }`}
                          >
                            {metaStatus === 'connected' ? 'Connected' : 'Not Connected'}
                          </span>
                        </div>
                        <p className="text-xs text-slate-400 mt-0.5">
                          {metaStatus === 'connected'
                            ? 'Meta catalog synchronization and server-side Conversions API are active.'
                            : 'Connect your Facebook Business Account or provide manual API credentials below.'}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 self-start sm:self-auto shrink-0">
                      <button
                        type="button"
                        onClick={openMetaOAuthPopup}
                        className="px-3.5 py-1.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs shadow-xs transition flex items-center gap-1.5 cursor-pointer"
                      >
                        <i className="fa-brands fa-facebook text-xs" />
                        <span>{metaStatus === 'connected' ? 'Reconnect Facebook' : 'Connect Facebook Login'}</span>
                      </button>

                      {metaStatus === 'connected' && (
                        <button
                          type="button"
                          onClick={handleDisconnectMeta}
                          disabled={isDisconnectingMeta}
                          className="px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-rose-50 text-slate-600 hover:text-rose-600 text-xs font-semibold border border-slate-200 hover:border-rose-200 transition flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
                        >
                          <i className="fa-solid fa-power-off text-xs" />
                          <span>{isDisconnectingMeta ? 'Disconnecting...' : 'Disconnect'}</span>
                        </button>
                      )}
                    </div>
                  </div>

                  {/* Quick Summary of Configured Assets */}
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                    <div className="p-3 rounded-xl bg-slate-50 border border-slate-200/80">
                      <span className="text-slate-400 font-medium">Business Portfolio</span>
                      <p className="font-semibold text-slate-800 mt-0.5 truncate">
                        {formData.businessName || formData.businessId || 'Not configured'}
                      </p>
                    </div>
                    <div className="p-3 rounded-xl bg-slate-50 border border-slate-200/80">
                      <span className="text-slate-400 font-medium">Catalog ID</span>
                      <p className="font-mono font-semibold text-slate-800 mt-0.5 truncate">
                        {formData.catalogId || 'Not configured'}
                      </p>
                    </div>
                    <div className="p-3 rounded-xl bg-slate-50 border border-slate-200/80">
                      <span className="text-slate-400 font-medium">Pixel Dataset ID</span>
                      <p className="font-mono font-semibold text-slate-800 mt-0.5 truncate">
                        {formData.pixelId || 'Not configured'}
                      </p>
                    </div>
                  </div>
                </div>

                {/* Credentials Edit Form */}
                <form onSubmit={handleSaveMeta} className="space-y-6">
                  <div className="bg-white p-4 sm:p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
                    <div className="flex items-center gap-2 border-b border-slate-100 pb-3">
                      <i className="fa-solid fa-sliders text-theme text-sm" />
                      <h3 className="font-semibold text-sm text-slate-900">Meta Business &amp; Commerce Credentials</h3>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
                      <div>
                        <label className="font-semibold text-slate-700">Meta Business Manager ID</label>
                        <input
                          type="text"
                          value={formData.businessId}
                          onChange={(e) => setFormData({ ...formData, businessId: e.target.value })}
                          className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                          placeholder="e.g. 104928374928174"
                        />
                      </div>

                      <div>
                        <label className="font-semibold text-slate-700">Business Portfolio Name</label>
                        <input
                          type="text"
                          value={formData.businessName}
                          onChange={(e) => setFormData({ ...formData, businessName: e.target.value })}
                          className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 text-xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                          placeholder="e.g. My Commerce Store"
                        />
                      </div>

                      <div>
                        <label className="font-semibold text-slate-700">Meta Catalog ID</label>
                        <input
                          type="text"
                          value={formData.catalogId}
                          onChange={(e) => setFormData({ ...formData, catalogId: e.target.value })}
                          className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                          placeholder="e.g. 849302847592834"
                        />
                      </div>

                      <div>
                        <label className="font-semibold text-slate-700">Catalog Name</label>
                        <input
                          type="text"
                          value={formData.catalogName}
                          onChange={(e) => setFormData({ ...formData, catalogName: e.target.value })}
                          className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 text-xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                          placeholder="e.g. Shopify Live Products"
                        />
                      </div>

                      <div>
                        <label className="font-semibold text-slate-700">Meta Pixel Dataset ID</label>
                        <input
                          type="text"
                          value={formData.pixelId}
                          onChange={(e) => setFormData({ ...formData, pixelId: e.target.value })}
                          className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                          placeholder="e.g. 948302847592812"
                        />
                      </div>

                      <div>
                        <label className="font-semibold text-slate-700">Pixel Name</label>
                        <input
                          type="text"
                          value={formData.pixelName}
                          onChange={(e) => setFormData({ ...formData, pixelName: e.target.value })}
                          className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 text-xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                          placeholder="e.g. Primary Store Pixel"
                        />
                      </div>
                    </div>

                    <div className="pt-2">
                      <label className="text-xs font-semibold text-slate-700 block">
                        Meta Graph API System User Access Token
                      </label>
                      <input
                        type="password"
                        value={formData.accessToken}
                        onChange={(e) => setFormData({ ...formData, accessToken: e.target.value })}
                        className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 text-xs font-mono focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                        placeholder="EAAxxxxxxxxxxxxxxxxxxxx (Leave empty to keep existing encrypted token)"
                      />
                    </div>

                    <div>
                      <label className="text-xs font-semibold text-slate-700 block">
                        Meta Conversions API (CAPI) Test Event Code
                      </label>
                      <input
                        type="text"
                        value={formData.testEventCode}
                        onChange={(e) => setFormData({ ...formData, testEventCode: e.target.value })}
                        className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 text-xs font-mono uppercase focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme bg-white"
                        placeholder="TEST12345"
                      />
                      <p className="text-[11px] text-slate-400 mt-1">
                        Find this in Meta Events Manager &gt; Test Events tab to verify server-side events in real time.
                      </p>
                    </div>

                    {saveError && (
                      <div
                        data-error-banner
                        role="alert"
                        className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs flex items-center gap-2"
                      >
                        <i className="fa-solid fa-circle-exclamation text-rose-600 text-xs shrink-0" />
                        <span>{saveError}</span>
                      </div>
                    )}

                    <div className="pt-4 flex flex-wrap items-center justify-between gap-3 border-t border-slate-100">
                      <button
                        type="submit"
                        disabled={isSaving}
                        className="px-5 py-2.5 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-sm hover:shadow-md transition flex items-center gap-2 cursor-pointer disabled:opacity-50"
                      >
                        <i className={`fa-solid ${isSaving ? 'fa-spinner fa-spin' : 'fa-floppy-disk'} text-xs`} />
                        <span>{isSaving ? 'Saving...' : 'Save Meta Credentials'}</span>
                      </button>

                      {saveSuccess && (
                        <span className="text-xs font-semibold text-emerald-600 flex items-center gap-1">
                          <i className="fa-solid fa-circle-check text-xs" /> Saved successfully
                        </span>
                      )}
                    </div>
                  </div>
                </form>
              </div>
            )}

            {/* TAB 3: INTEGRATION FEEDS & WEBHOOKS */}
            {activeTab === 'endpoints' && (
              <div className="space-y-6">
                <div className="bg-white p-4 sm:p-6 rounded-2xl border border-slate-200 shadow-sm space-y-4">
                  <div className="border-b border-slate-100 pb-3">
                    <h3 className="font-semibold text-sm text-slate-900">Live Dynamic Meta Catalog Feeds</h3>
                    <p className="text-xs text-slate-500 mt-0.5">
                      Feeds dynamically render all verified variants directly from your MySQL database.
                    </p>
                  </div>

                  <div className="space-y-4 text-xs">
                    <div>
                      <label className="font-semibold text-slate-700">Meta XML (RSS 2.0) Product Catalog Feed</label>
                      <div className="flex flex-col sm:flex-row sm:items-center gap-2 mt-1">
                        <input
                          type="text"
                          readOnly
                          value={endpoints.xmlFeedUrl || apiUrl(`/api/catalog/feed/meta.xml?shop=${activeShop}`)}
                          className="flex-1 p-2.5 rounded-xl bg-slate-50 border border-slate-200 font-mono text-slate-700 text-xs break-all"
                        />
                        <button
                          onClick={() => handleCopy(endpoints.xmlFeedUrl || apiUrl(`/api/catalog/feed/meta.xml?shop=${activeShop}`), 'xml')}
                          className="px-3.5 py-2.5 rounded-xl bg-white border border-slate-200 hover:bg-slate-50 font-semibold text-slate-700 flex items-center justify-center gap-1.5 cursor-pointer shrink-0"
                        >
                          {copiedKey === 'xml' ? (
                            <i className="fa-solid fa-check text-emerald-600 text-xs" />
                          ) : (
                            <i className="fa-regular fa-copy text-xs" />
                          )}
                          <span>Copy</span>
                        </button>
                      </div>
                    </div>

                    <div>
                      <label className="font-semibold text-slate-700">Meta CSV Bulk Catalog Feed</label>
                      <div className="flex flex-col sm:flex-row sm:items-center gap-2 mt-1">
                        <input
                          type="text"
                          readOnly
                          value={endpoints.csvFeedUrl || apiUrl(`/api/catalog/feed/meta.csv?shop=${activeShop}`)}
                          className="flex-1 p-2.5 rounded-xl bg-slate-50 border border-slate-200 font-mono text-slate-700 text-xs break-all"
                        />
                        <button
                          onClick={() => handleCopy(endpoints.csvFeedUrl || apiUrl(`/api/catalog/feed/meta.csv?shop=${activeShop}`), 'csv')}
                          className="px-3.5 py-2.5 rounded-xl bg-white border border-slate-200 hover:bg-slate-50 font-semibold text-slate-700 flex items-center justify-center gap-1.5 cursor-pointer shrink-0"
                        >
                          {copiedKey === 'csv' ? (
                            <i className="fa-solid fa-check text-emerald-600 text-xs" />
                          ) : (
                            <i className="fa-regular fa-copy text-xs" />
                          )}
                          <span>Copy</span>
                        </button>
                      </div>
                    </div>

                    <div>
                      <label className="font-semibold text-slate-700">Shopify Conversions API Webhook Listener</label>
                      <div className="flex flex-col sm:flex-row sm:items-center gap-2 mt-1">
                        <input
                          type="text"
                          readOnly
                          value={endpoints.capiWebhookUrl || apiUrl('/api/webhooks/shopify')}
                          className="flex-1 p-2.5 rounded-xl bg-slate-50 border border-slate-200 font-mono text-slate-700 text-xs break-all"
                        />
                        <button
                          onClick={() => handleCopy(endpoints.capiWebhookUrl || apiUrl('/api/webhooks/shopify'), 'webhook')}
                          className="px-3.5 py-2.5 rounded-xl bg-white border border-slate-200 hover:bg-slate-50 font-semibold text-slate-700 flex items-center justify-center gap-1.5 cursor-pointer shrink-0"
                        >
                          {copiedKey === 'webhook' ? (
                            <i className="fa-solid fa-check text-emerald-600 text-xs" />
                          ) : (
                            <i className="fa-regular fa-copy text-xs" />
                          )}
                          <span>Copy</span>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </AppLayout>
  );
}

export default function SettingsPage() {
  return (
    <Suspense
      fallback={
        <AppLayout currentRoute="/settings">
          <div className="py-20 text-center text-slate-400 flex items-center justify-center gap-2">
            <i className="fa-solid fa-arrows-rotate text-lg fa-spin text-theme" />
            <span>Loading configuration...</span>
          </div>
        </AppLayout>
      }
    >
      <SettingsContent />
    </Suspense>
  );
}
