'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';

import { PricingPlan, FeatureDefinition } from '@/types';
import AppLayout from '@/components/layout/AppLayout';
import { APP_CONFIG } from '@/config/app';
import { appRoute } from '@/lib/utils/asset';

export default function PricingPage() {
  const [plans, setPlans] = useState<PricingPlan[]>([]);
  const [featureDefinitions, setFeatureDefinitions] = useState<FeatureDefinition[]>([]);
  const [activeShop, setActiveShop] = useState<string>('');
  const getHref = (path: string) => appRoute(path, activeShop);
  const [shops, setShops] = useState<Array<{ id: string; domain: string; plan: string; status?: string; custom_sku_limit?: number | null; trial_days?: number }>>([]);
  const [currentUsage, setCurrentUsage] = useState<{
    skuCount: number;
    activePlanId: string;
    planName: string;
    skuLimit: number | null;
    subscriptionStatus?: string;
    customLimit?: number | null;
    trialDays?: number;
    trialDaysRemaining?: number | null;
  }>({
    skuCount: 0,
    activePlanId: '',
    planName: '',
    skuLimit: null,
    subscriptionStatus: 'active',
    customLimit: null,
    trialDays: 0,
    trialDaysRemaining: null,
  });

  const [isLoading, setIsLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [toastMessage, setToastMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [activationBanner, setActivationBanner] = useState<string | null>(null);
  const [disabledPlanModal, setDisabledPlanModal] = useState<PricingPlan | null>(null);

  // Admin Customizer State
  const [isAdminOpen, setIsAdminOpen] = useState(false);
  const [adminTab, setAdminTab] = useState<'plans' | 'stores'>('plans');
  const [editingPlan, setEditingPlan] = useState<PricingPlan | null>(null);
  const [newFeatureText, setNewFeatureText] = useState('');
  const [isSavingAdmin, setIsSavingAdmin] = useState(false);

  // Store-specific Admin State
  const [selectedStoreDomain, setSelectedStoreDomain] = useState('');
  const [selectedStorePlan, setSelectedStorePlan] = useState('growth');
  const [selectedStoreCustomSku, setSelectedStoreCustomSku] = useState('');
  const [selectedStoreTrialDays, setSelectedStoreTrialDays] = useState(14);
  const [selectedStoreStatus, setSelectedStoreStatus] = useState('active');
  const [isSavingStore, setIsSavingStore] = useState(false);

  const fetchPlansAndUsage = async (shopDomain?: string, sync: boolean = false) => {
    try {
      setIsLoading(true);
      const shopRes = await fetch('/api/shops');
      const shopData = await shopRes.json();
      const currentDomain = shopDomain || activeShop || (shopData.success && shopData.store?.domain) || '';

      const syncQuery = sync ? '&sync=true' : '';
      const res = await fetch(`/api/plans?shop=${encodeURIComponent(currentDomain)}${syncQuery}`);
      const data = await res.json();
      if (data.success) {
        setPlans(data.plans || []);
        if (data.featureDefinitions) {
          setFeatureDefinitions(data.featureDefinitions);
        }
        if (data.shops && data.shops.length > 0) {
          setShops(data.shops);
        } else if (shopData.success && shopData.store) {
          setShops([shopData.store]);
        }

        if (data.usage) {
          setCurrentUsage(data.usage);
        }

        const resolvedDomain = currentDomain || data.shop?.domain || (data.shops && data.shops[0]?.domain) || '';
        if (resolvedDomain && resolvedDomain !== activeShop) {
          setActiveShop(resolvedDomain);
          setSelectedStoreDomain(resolvedDomain);
          setSelectedStorePlan(data.usage?.activePlanId || 'growth');
          setSelectedStoreCustomSku(data.usage?.customLimit ? String(data.usage.customLimit) : '');
          setSelectedStoreTrialDays(data.usage?.trialDays ?? 14);
          setSelectedStoreStatus(data.usage?.subscriptionStatus || 'active');
        }
      }
    } catch (err) {
      console.error('Failed to load plans:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const urlParams = new URLSearchParams(window.location.search);
      const isSync = urlParams.get('sync') === 'true';
      const isActivated = urlParams.get('activated') === 'true' || urlParams.get('plan_switched') === 'true';
      const chargeId = urlParams.get('charge_id');
      const planName = urlParams.get('plan');

      if (isActivated || chargeId || isSync) {
        setActivationBanner(
          planName
            ? `🎉 Subscription Activated! Your store is now active on the ${planName.toUpperCase()} plan.`
            : '🎉 Subscription Verified & Active! Your plan quotas and feature entitlements have been synchronized.'
        );
      }
      fetchPlansAndUsage(undefined, isSync || isActivated);
    } else {
      fetchPlansAndUsage();
    }
  }, []);

  const showToast = (text: string, type: 'success' | 'error' = 'success') => {
    setToastMessage({ type, text });
    setTimeout(() => setToastMessage(null), 4000);
  };

  const handleSelectPlan = async (planId: string) => {
    setActionLoading(planId);
    try {
      const res = await fetch('/api/plans/select', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          shop_domain: activeShop,
          plan_id: planId,
        }),
      });
      const data = await res.json();
      if (data.success) {
        if (data.confirmationUrl && planId !== 'basic') {
          showToast(`Redirecting to Shopify Billing to approve ${planId.toUpperCase()} plan...`);
          setTimeout(() => {
            try {
              if (typeof (window as any).open === 'function') {
                (window as any).open(data.confirmationUrl, '_top');
              }
            } catch {}
            try {
              if (window.top && window.top !== window) {
                window.top.location.href = data.confirmationUrl;
              } else {
                window.location.href = data.confirmationUrl;
              }
            } catch {
              window.location.href = data.confirmationUrl;
            }
          }, 200);
          return;
        }

        showToast(`Plan successfully updated to ${planId.toUpperCase()}!`);
        await fetchPlansAndUsage(activeShop, true);
      } else {
        showToast(data.error || 'Failed to switch plan', 'error');
      }
    } catch (err) {
      showToast('Network error while switching plan', 'error');
    } finally {
      setActionLoading(null);
    }
  };

  const handleSaveAdminPlan = async () => {
    if (!editingPlan) return;
    setIsSavingAdmin(true);
    try {
      const res = await fetch('/api/plans/admin', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          plan_id: editingPlan.id,
          updates: editingPlan,
        }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(`Admin: ${editingPlan.name} customizations saved!`);
        setIsAdminOpen(false);
        await fetchPlansAndUsage(activeShop);
      } else {
        showToast(data.error || 'Failed to save customizations', 'error');
      }
    } catch {
      showToast('Failed to save plan edits', 'error');
    } finally {
      setIsSavingAdmin(false);
    }
  };

  const handleSaveStorePlan = async () => {
    if (!selectedStoreDomain) return;
    setIsSavingStore(true);
    try {
      const res = await fetch('/api/plans/admin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'update_store',
          shop_domain: selectedStoreDomain,
          plan: selectedStorePlan,
          custom_sku_limit: selectedStoreCustomSku ? parseInt(selectedStoreCustomSku, 10) : null,
          trial_days: selectedStoreTrialDays,
          subscription_status: selectedStoreStatus,
        }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(`Store settings updated for ${selectedStoreDomain}!`);
        setIsAdminOpen(false);
        await fetchPlansAndUsage(selectedStoreDomain);
      } else {
        showToast(data.error || 'Failed to update store plan', 'error');
      }
    } catch {
      showToast('Failed to save store plan', 'error');
    } finally {
      setIsSavingStore(false);
    }
  };

  const handleResetDefaults = async () => {
    if (!confirm('Are you sure you want to reset all plans to standard factory defaults?')) return;
    setIsSavingAdmin(true);
    try {
      const res = await fetch('/api/plans/admin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'reset_defaults' }),
      });
      const data = await res.json();
      if (data.success) {
        showToast('All plans reset to factory defaults!');
        setIsAdminOpen(false);
        await fetchPlansAndUsage(activeShop);
      }
    } catch {
      showToast('Failed to reset plans', 'error');
    } finally {
      setIsSavingAdmin(false);
    }
  };

  const calculateUsagePercent = () => {
    if (!currentUsage.skuLimit) return 5; // Unlimited
    return Math.min(100, Math.round((currentUsage.skuCount / currentUsage.skuLimit) * 100));
  };

  const visiblePlans = plans.filter((p) => {
    if (p.is_active === false) return false;
    if (p.is_visible === false) return false;
    if (p.id === 'accelerate' && plans.some((x) => x.id === 'scale' && x.is_active !== false)) return false;
    return true;
  });
  const basicPlan = visiblePlans.find((p) => p.id === 'basic') || plans.find((p) => p.id === 'basic');
  const growthPlan = visiblePlans.find((p) => p.id === 'growth') || plans.find((p) => p.id === 'growth');
  const scalePlan = visiblePlans.find((p) => p.id === 'scale') || visiblePlans.find((p) => p.id === 'accelerate') || plans.find((p) => p.id === 'scale') || plans.find((p) => p.id === 'accelerate');

  return (
    <AppLayout currentRoute="/pricing">
      <ui-title-bar title="Plans & Billing" />
      <div className="space-y-6">
      {/* Toast Notification */}
      {toastMessage && (
        <div
          className={`fixed bottom-6 right-6 z-50 px-4 py-3 rounded-xl shadow-xl flex items-center gap-3 border text-sm font-medium ${
            toastMessage.type === 'success'
              ? 'bg-emerald-900 text-emerald-100 border-emerald-700'
              : 'bg-rose-900 text-rose-100 border-rose-700'
          }`}
        >
          {toastMessage.type === 'success' ? (
            <i className="fa-solid fa-circle-check text-emerald-400 text-lg" />
          ) : (
            <i className="fa-solid fa-circle-exclamation text-rose-400 text-lg" />
          )}
          <span>{toastMessage.text}</span>
        </div>
      )}

      {/* Activation Success Banner */}
      {activationBanner && (
        <div className="bg-emerald-50 border border-emerald-200 text-emerald-900 rounded-xl p-4 flex items-center justify-between shadow-xs">
          <div className="flex items-center gap-3">
            <span className="text-2xl">🎉</span>
            <div>
              <h4 className="text-sm font-bold text-emerald-950">{activationBanner}</h4>
              <p className="text-xs text-emerald-700 mt-0.5">
                All feature entitlements and catalog quotas have been verified with Shopify Billing and unlocked.
              </p>
            </div>
          </div>
          <button
            onClick={() => setActivationBanner(null)}
            className="text-emerald-700 hover:text-emerald-950 text-sm font-bold p-1 cursor-pointer"
          >
            ✕
          </button>
        </div>
      )}

      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 text-xs font-semibold text-blue-600 uppercase tracking-wider">
            <i className="fa-solid fa-bolt text-xs" />
            <span>Subscriptions &amp; Pricing</span>
          </div>
          <h1 className="text-2xl font-bold text-slate-900 mt-1">Pricing</h1>
          <p className="text-sm text-slate-500">Choose the plan that best fits your business.</p>
        </div>
        <Link
          href={getHref('/help?guide=pricing-plans')}
          className="inline-flex items-center gap-2 px-3.5 py-2 rounded-xl bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200 text-xs font-bold transition-all shadow-2xs shrink-0"
        >
          <i className="fa-solid fa-book-open text-xs text-indigo-600" />
          <span>Pricing Plans Documentation</span>
          <i className="fa-solid fa-arrow-right text-[10px]" />
        </Link>
      </div>

      {/* Current Quota & Plan Status Card */}
      <div className="bg-white rounded-xl border border-slate-200 p-4 sm:p-6 shadow-sm">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-4 border-b border-slate-100">
          <div>
            <span className="text-xs font-bold uppercase tracking-wider text-slate-400">Current Store Plan</span>
            <div className="flex flex-wrap items-center gap-2 sm:gap-3 mt-1">
              <h2 className="text-xl font-bold text-slate-900 capitalize">{currentUsage.planName}</h2>
              {currentUsage.subscriptionStatus === 'trial' ? (
                <span className="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-indigo-50 text-indigo-700 border border-indigo-200 flex items-center gap-1.5 shadow-sm">
                  <i className="fa-solid fa-wand-magic-sparkles text-indigo-500 text-xs" />
                  <span>
                    14-Day Free Trial
                    {currentUsage.trialDaysRemaining !== null && currentUsage.trialDaysRemaining !== undefined
                      ? ` (${currentUsage.trialDaysRemaining} days left)`
                      : ''}
                  </span>
                </span>
              ) : currentUsage.activePlanId === 'basic' ? (
                <span className="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-slate-100 text-slate-700 border border-slate-200">
                  Free Plan
                </span>
              ) : (
                <span className="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-800 border border-emerald-200">
                  Active Subscription
                </span>
              )}
            </div>
            <p className="text-xs text-slate-500 mt-0.5 break-all">
              Store: <span className="font-medium text-slate-700">{activeShop}</span>
            </p>
          </div>

          <div className="text-left md:text-right">
            <div className="text-xs text-slate-400">Catalog SKU Usage</div>
            <div className="text-lg font-bold text-slate-900 mt-0.5">
              {currentUsage.skuCount.toLocaleString()} /{' '}
              {currentUsage.skuLimit ? currentUsage.skuLimit.toLocaleString() : 'Unlimited'}{' '}
              <span className="text-xs font-normal text-slate-500">SKUs</span>
            </div>
          </div>
        </div>

        <div className="mt-4">
          <div className="flex justify-between text-xs text-slate-500 mb-1.5 font-medium">
            <span>Quota Utilization</span>
            <span>{currentUsage.skuLimit ? `${calculateUsagePercent()}%` : 'Unlimited SKU Syncing'}</span>
          </div>
          <div className="w-full h-2.5 bg-slate-100 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full transition-all duration-500 ${
                calculateUsagePercent() > 90
                  ? 'bg-rose-500'
                  : calculateUsagePercent() > 70
                  ? 'bg-amber-500'
                  : 'bg-theme'
              }`}
              style={{ width: `${calculateUsagePercent()}%` }}
            />
          </div>
        </div>
      </div>

      {/* Pricing Cards Grid */}
      {isLoading ? (
        <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" />
          <span>Loading plans...</span>
        </div>
      ) : visiblePlans.length === 0 ? (
        <div className="bg-white rounded-2xl border border-slate-200 p-12 text-center space-y-3">
          <div className="w-12 h-12 rounded-2xl bg-amber-50 text-amber-600 mx-auto flex items-center justify-center">
            <i className="fa-solid fa-store-slash text-xl" />
          </div>
          <h3 className="text-sm font-bold text-slate-900">No Subscription Plans Currently Active</h3>
          <p className="text-xs text-slate-500 max-w-sm mx-auto">
            Subscription tiers are currently being configured by the platform administrator. Please check back shortly or contact support.
          </p>
        </div>
      ) : (
        <div className={`grid grid-cols-1 ${visiblePlans.length === 1 ? 'max-w-md mx-auto' : visiblePlans.length === 2 ? 'md:grid-cols-2 max-w-4xl mx-auto' : 'md:grid-cols-3'} gap-6`}>
          {visiblePlans.map((plan) => {
            const isCurrent = currentUsage.activePlanId === plan.id;
            const isPopular = plan.badge || plan.id === 'growth';
            const hasTrial = plan.trial_days && plan.trial_days > 0;

            return (
              <div
                key={plan.id}
                className={`relative bg-white rounded-2xl transition-all duration-200 flex flex-col justify-between ${
                  isPopular
                    ? 'border-2 border-theme shadow-xl shadow-theme/10 ring-4 ring-theme/10'
                    : 'border border-slate-200 shadow-sm hover:shadow-md'
                }`}
              >
                {/* Popular / Plan Badge */}
                {plan.badge ? (
                  <div className="absolute -top-3.5 left-1/2 -translate-x-1/2">
                    <span className="px-3 py-1 rounded-full text-[11px] font-bold uppercase tracking-wider shadow-sm bg-theme text-white">
                      {plan.badge}
                    </span>
                  </div>
                ) : null}

                <div className="p-6">
                  {/* Plan Name & Icon */}
                  <div className="flex items-center justify-between mt-1 mb-4">
                    <div className="flex items-center gap-2.5">
                      <div
                        className={`w-10 h-10 rounded-xl flex items-center justify-center ${
                          plan.id === 'basic'
                            ? 'bg-slate-100 text-slate-700'
                            : plan.id === 'growth'
                            ? 'bg-blue-100 text-blue-700'
                            : 'bg-purple-100 text-purple-700'
                        }`}
                      >
                        {plan.id === 'basic' ? (
                          <i className="fa-solid fa-layer-group text-base" />
                        ) : plan.id === 'growth' ? (
                          <i className="fa-solid fa-wand-magic-sparkles text-base" />
                        ) : (
                          <i className="fa-solid fa-bolt text-base" />
                        )}
                      </div>
                      <div>
                        <h3 className="font-bold text-slate-900 text-lg">{plan.name}</h3>
                        <p className="text-xs text-slate-400">
                          {plan.id === 'basic'
                            ? 'Ideal for getting started'
                            : plan.id === 'growth'
                            ? 'Best for growing stores'
                            : 'For high-volume merchants'}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Price Section */}
                  <div className="my-6 pb-6 border-b border-slate-100">
                    <div className="flex items-baseline gap-1">
                      {plan.price === 0 ? (
                        <span className="text-4xl font-extrabold text-slate-900">Free</span>
                      ) : (
                        <>
                          <span className="text-4xl font-extrabold text-slate-900">${plan.price}</span>
                          <span className="text-sm font-medium text-slate-500">/ month</span>
                        </>
                      )}
                    </div>
                    <div className="flex items-center gap-2 mt-2">
                      <p className="text-xs text-slate-400">
                        {plan.price === 0 ? 'No credit card required' : 'Billed monthly via Shopify'}
                      </p>
                      {hasTrial ? (
                        <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-0.5 rounded-full shadow-xs">
                          ✨ {plan.trial_days}-Day Free Trial
                        </span>
                      ) : null}
                    </div>
                  </div>

                  {/* Features List */}
                  <div>
                    <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400 mb-3">
                      Features Included:
                    </h4>
                    <ul className="space-y-2.5 text-xs text-slate-600">
                      {plan.features.map((feat, idx) => (
                        <li key={idx} className="flex items-start gap-2.5">
                          <div className="w-4 h-4 rounded-full bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0 mt-0.5">
                            <i className="fa-solid fa-check text-[10px]" />
                          </div>
                          <span className="leading-snug">{feat}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>

                {/* Plan CTA Button */}
                <div className="p-6 pt-0 mt-4">
                  <button
                    disabled={isCurrent}
                    onClick={() => handleSelectPlan(plan.id)}
                    className={`w-full py-2.5 px-4 rounded-xl text-xs font-bold transition-all flex items-center justify-center gap-2 cursor-pointer ${
                      isCurrent
                        ? 'bg-emerald-50 text-emerald-700 cursor-default border border-emerald-200'
                        : 'bg-theme hover:bg-theme-hover text-white shadow-md shadow-theme/20'
                    }`}
                  >
                    {actionLoading === plan.id ? (
                      <i className="fa-solid fa-arrows-rotate text-xs fa-spin" />
                    ) : isCurrent ? (
                      <>
                        <i className="fa-solid fa-circle-check text-emerald-600 text-xs" />
                        <span>Current Active Plan</span>
                      </>
                    ) : plan.price === 0 ? (
                      <span>Select Free Plan</span>
                    ) : (
                      <span>Select {plan.name}</span>
                    )}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Shopify Plan & Quotas Pricing Matrix */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden mt-8">
        <div className="p-6 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div>
            <h3 className="font-bold text-slate-900 text-base">Shopify Plan &amp; Product Quota Schedule</h3>
            <p className="text-xs text-slate-500 mt-0.5">
              Transparent monthly pricing mapped to your Shopify plan and catalog size. Save 20% on annual billing.
            </p>
          </div>
          <Link
            href={getHref('/help?guide=pricing-plans')}
            className="text-xs font-bold text-indigo-600 hover:text-indigo-700 flex items-center gap-1.5 shrink-0"
          >
            <span>Read full plan policy</span>
            <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
          </Link>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse min-w-[600px]">
            <thead>
              <tr className="bg-slate-50/70 border-b border-slate-200 text-slate-700 font-extrabold">
                <th className="p-3.5 pl-6">Shopify Plan</th>
                <th className="p-3.5">Products Quota</th>
                <th className="p-3.5 text-center">Free Plan</th>
                <th className="p-3.5 text-center bg-indigo-50/40 text-indigo-900">Growth Plan</th>
                <th className="p-3.5 text-center">Scale Plan</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 text-slate-600">
              <tr>
                <td className="p-3.5 pl-6 font-bold text-slate-900">Basic / Grow</td>
                <td className="p-3.5">100 SKUs</td>
                <td className="p-3.5 text-center font-bold text-slate-900">$0.00 / mo</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$20.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr>
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5">1,000 SKUs</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$25.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr>
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5">5,000 SKUs</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$29.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr>
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5 font-bold text-purple-700">Unlimited</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center text-slate-400 bg-indigo-50/30">—</td>
                <td className="p-3.5 text-center font-bold text-purple-700">$49.99 / mo</td>
              </tr>
              <tr className="bg-slate-50/40">
                <td className="p-3.5 pl-6 font-bold text-slate-900">Advanced</td>
                <td className="p-3.5">100 SKUs</td>
                <td className="p-3.5 text-center font-bold text-slate-900">$0.00 / mo</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$35.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr className="bg-slate-50/40">
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5">1,000 SKUs</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$45.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr className="bg-slate-50/40">
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5">5,000 SKUs</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$55.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr className="bg-slate-50/40">
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5 font-bold text-purple-700">Unlimited</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center text-slate-400 bg-indigo-50/30">—</td>
                <td className="p-3.5 text-center font-bold text-purple-700">$79.99 / mo</td>
              </tr>
              <tr>
                <td className="p-3.5 pl-6 font-bold text-slate-900">Shopify Plus</td>
                <td className="p-3.5">100 SKUs</td>
                <td className="p-3.5 text-center font-bold text-slate-900">$0.00 / mo</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$45.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr>
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5">1,000 SKUs</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$55.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr>
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5">5,000 SKUs</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center font-bold text-indigo-600 bg-indigo-50/30">$65.99 / mo</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
              </tr>
              <tr>
                <td className="p-3.5 pl-6 font-medium text-slate-700"></td>
                <td className="p-3.5 font-bold text-purple-700">Unlimited</td>
                <td className="p-3.5 text-center text-slate-400">—</td>
                <td className="p-3.5 text-center text-slate-400 bg-indigo-50/30">—</td>
                <td className="p-3.5 text-center font-bold text-purple-700">$99.99 / mo</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* Feature Comparison Matrix ("What Included?") */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden mt-8">
        <div className="p-6 border-b border-slate-100 flex items-center justify-between">
          <div>
            <h3 className="font-bold text-slate-900 text-base">What&apos;s Included in Each Tier?</h3>
            <p className="text-xs text-slate-500 mt-0.5">Feature-by-feature capability breakdown</p>
          </div>
          <span className="text-[10px] font-extrabold uppercase px-2.5 py-1 rounded-full bg-slate-100 text-slate-600">
            Feature Comparison
          </span>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse min-w-[600px]">
            <thead>
              <tr className="bg-slate-50/70 border-b border-slate-200 text-slate-700 font-extrabold">
                <th className="p-4 pl-6 w-1/3">Pricing &amp; Features</th>
                <th className="p-4 text-center">Free Plan</th>
                <th className="p-4 text-center bg-indigo-50/40 text-indigo-900">Growth Plan</th>
                <th className="p-4 text-center">Scale Plan</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 text-slate-600">
              {featureDefinitions.length > 0 ? (
                featureDefinitions
                  .filter((f) => f.is_visible !== false)
                  .sort((a, b) => (a.display_order ?? 0) - (b.display_order ?? 0))
                  .map((feat) => {
                    const renderVal = (val: string, enabled: boolean, isGrowth = false, isScale = false) => {
                      const clean = (val || '').trim().toLowerCase();
                      if (clean === 'yes' || (enabled && clean === '')) {
                        return <i className="fa-solid fa-check text-emerald-600" />;
                      }
                      if (clean === 'no' || clean === '—' || (!enabled && clean === '')) {
                        return <span className="text-slate-400">—</span>;
                      }
                      return (
                        <span
                          className={`${
                            isScale
                              ? 'font-bold text-purple-700'
                              : isGrowth
                              ? 'font-bold text-indigo-600'
                              : clean.includes('5 orders')
                              ? 'font-medium text-amber-700'
                              : 'font-semibold text-slate-800'
                          }`}
                        >
                          {val}
                        </span>
                      );
                    };

                    return (
                      <tr key={feat.id} className="hover:bg-slate-50/50 transition-colors">
                        <td className="p-4 pl-6 font-semibold text-slate-900">
                          <div>{feat.name}</div>
                          {feat.description && (
                            <div className="text-[11px] text-slate-400 font-normal mt-0.5">{feat.description}</div>
                          )}
                        </td>
                        <td className="p-4 text-center">{renderVal(feat.basic_value, feat.basic_enabled)}</td>
                        <td className="p-4 text-center bg-indigo-50/20">{renderVal(feat.growth_value, feat.growth_enabled, true, false)}</td>
                        <td className="p-4 text-center">{renderVal(feat.scale_value, feat.scale_enabled, false, true)}</td>
                      </tr>
                    );
                  })
              ) : (
                <>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Meta Pixel Count</td>
                    <td className="p-4 text-center">1 Pixel</td>
                    <td className="p-4 text-center font-bold text-indigo-600 bg-indigo-50/20">Unlimited</td>
                    <td className="p-4 text-center font-bold text-purple-700">Unlimited</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Conversions API (CAPI)</td>
                    <td className="p-4 text-center">1 Dataset</td>
                    <td className="p-4 text-center bg-indigo-50/20">1 Dataset (+$5.99/mo per extra)</td>
                    <td className="p-4 text-center font-bold text-purple-700">Unlimited</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Order Tracking Quota</td>
                    <td className="p-4 text-center font-medium text-amber-700">5 orders / month</td>
                    <td className="p-4 text-center font-bold text-indigo-600 bg-indigo-50/20">Unlimited</td>
                    <td className="p-4 text-center font-bold text-purple-700">Unlimited</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Advanced Tracking Rules (COD / Subs / Bundles)</td>
                    <td className="p-4 text-center"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center bg-indigo-50/20"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Specific-Market Pixel Routing</td>
                    <td className="p-4 text-center text-slate-400">—</td>
                    <td className="p-4 text-center text-slate-400 bg-indigo-50/20">—</td>
                    <td className="p-4 text-center font-bold text-emerald-600"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Catalog Feeds (XML / CSV)</td>
                    <td className="p-4 text-center">1 Feed</td>
                    <td className="p-4 text-center font-semibold bg-indigo-50/20">3 Feeds</td>
                    <td className="p-4 text-center font-bold text-purple-700">Unlimited</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Products for Catalog Feed</td>
                    <td className="p-4 text-center">Up to 100 SKUs</td>
                    <td className="p-4 text-center bg-indigo-50/20">100 – 5,000 SKUs</td>
                    <td className="p-4 text-center font-bold text-purple-700">Unlimited</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Catalog Feed Sync Frequency</td>
                    <td className="p-4 text-center text-slate-500">Basic (Weekly)</td>
                    <td className="p-4 text-center font-semibold text-slate-800 bg-indigo-50/20">Standard (Daily)</td>
                    <td className="p-4 text-center font-bold text-purple-700">Advanced (Daily + Real-time)</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Order Reconciliation &amp; Report</td>
                    <td className="p-4 text-center"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center bg-indigo-50/20"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Pixel Analytics &amp; Health Monitoring</td>
                    <td className="p-4 text-center text-slate-500">Basic</td>
                    <td className="p-4 text-center font-semibold text-slate-800 bg-indigo-50/20">Advanced</td>
                    <td className="p-4 text-center font-bold text-purple-700">Advanced</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Live Event Stream &amp; Activities</td>
                    <td className="p-4 text-center text-slate-400">—</td>
                    <td className="p-4 text-center bg-indigo-50/20"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Real-Time Ads Report &amp; UTM Attribution</td>
                    <td className="p-4 text-center text-slate-400">—</td>
                    <td className="p-4 text-center font-semibold text-emerald-600 bg-indigo-50/20"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center font-bold text-emerald-600"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Bot &amp; Fraud Protection</td>
                    <td className="p-4 text-center text-slate-600">Layer 1 (Verified Bots)</td>
                    <td className="p-4 text-center bg-indigo-50/20 font-semibold text-indigo-700">Layer 1 + Layer 2 Blocking</td>
                    <td className="p-4 text-center font-bold text-purple-700">Full Protection + Manual Resend</td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Restricted Mode (Consent Policy / GDPR)</td>
                    <td className="p-4 text-center text-slate-400">—</td>
                    <td className="p-4 text-center text-slate-400 bg-indigo-50/20">—</td>
                    <td className="p-4 text-center font-bold text-emerald-600"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Audience Report (Who Buys, Who Returns)</td>
                    <td className="p-4 text-center font-bold text-emerald-600"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center bg-indigo-50/20 font-bold text-emerald-600"><i className="fa-solid fa-check text-emerald-600" /></td>
                    <td className="p-4 text-center font-bold text-emerald-600"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Meta Audiences Sync (Lookalikes &amp; Retargeting)</td>
                    <td className="p-4 text-center text-slate-400">—</td>
                    <td className="p-4 text-center text-slate-400 bg-indigo-50/20">—</td>
                    <td className="p-4 text-center font-bold text-emerald-600"><i className="fa-solid fa-check text-emerald-600" /></td>
                  </tr>
                  <tr>
                    <td className="p-4 pl-6 font-semibold text-slate-900">Customer Support Service Level</td>
                    <td className="p-4 text-center text-slate-700 font-medium">24/7 Support</td>
                    <td className="p-4 text-center font-semibold bg-indigo-50/20">24/7 Priority Chat &amp; Email</td>
                    <td className="p-4 text-center font-bold text-purple-700">Highest Priority 24/7 + VIP Community</td>
                  </tr>
                </>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Related Help Center Guides Hub */}
      <div className="bg-slate-50/80 rounded-2xl border border-slate-200 p-6 sm:p-8 mt-8 space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-slate-200/60 pb-4">
          <div>
            <h3 className="font-extrabold text-slate-900 text-sm sm:text-base flex items-center gap-2">
              <i className="fa-solid fa-book-open text-indigo-600" />
              <span>Related Feature Documentation &amp; Step-by-Step Guides</span>
            </h3>
            <p className="text-xs text-slate-500 mt-0.5">
              Learn how to configure every feature included with your subscription.
            </p>
          </div>
          <Link
            href={getHref('/help')}
            className="text-xs font-bold text-indigo-600 hover:text-indigo-800 flex items-center gap-1.5 shrink-0"
          >
            <span>View All Guides</span>
            <i className="fa-solid fa-arrow-right text-[10px]" />
          </Link>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 pt-1">
          <Link
            href={getHref('/help?guide=setup-pixel-and-capi')}
            className="p-3.5 rounded-xl bg-white border border-slate-200 hover:border-indigo-300 hover:shadow-sm transition-all group"
          >
            <div className="flex items-center gap-2 font-bold text-xs text-slate-800 group-hover:text-indigo-600 transition-colors">
              <i className="fa-brands fa-facebook text-indigo-600" />
              <span>Setup Pixel &amp; CAPI</span>
            </div>
            <p className="text-[11px] text-slate-500 mt-1 line-clamp-2">
              3-step setup guide for Meta Pixel ID, access token, and Shopify App Embed.
            </p>
          </Link>

          <Link
            href={getHref('/help?guide=app-checklist')}
            className="p-3.5 rounded-xl bg-white border border-slate-200 hover:border-indigo-300 hover:shadow-sm transition-all group"
          >
            <div className="flex items-center gap-2 font-bold text-xs text-slate-800 group-hover:text-indigo-600 transition-colors">
              <i className="fa-solid fa-list-check text-amber-600" />
              <span>App Setup Checklist</span>
            </div>
            <p className="text-[11px] text-slate-500 mt-1 line-clamp-2">
              Verify theme embed, match timezones, and clean up duplicate pixel scripts.
            </p>
          </Link>

          <Link
            href={getHref('/help?guide=advanced-settings')}
            className="p-3.5 rounded-xl bg-white border border-slate-200 hover:border-indigo-300 hover:shadow-sm transition-all group"
          >
            <div className="flex items-center gap-2 font-bold text-xs text-slate-800 group-hover:text-indigo-600 transition-colors">
              <i className="fa-solid fa-sliders text-emerald-600" />
              <span>Advanced Settings</span>
            </div>
            <p className="text-[11px] text-slate-500 mt-1 line-clamp-2">
              Fine-tune COD order delays, exclude subscription renewals, and bundle rules.
            </p>
          </Link>

          <Link
            href={getHref('/help?guide=ads-report')}
            className="p-3.5 rounded-xl bg-white border border-slate-200 hover:border-indigo-300 hover:shadow-sm transition-all group"
          >
            <div className="flex items-center gap-2 font-bold text-xs text-slate-800 group-hover:text-indigo-600 transition-colors">
              <i className="fa-solid fa-chart-line text-blue-600" />
              <span>Real-Time Ads Report</span>
            </div>
            <p className="text-[11px] text-slate-500 mt-1 line-clamp-2">
              Trace orders back to ads with UTM tracking and side-by-side reconciliation.
            </p>
          </Link>
        </div>
      </div>

      {/* Admin Plan Customizer Modal */}
      {isAdminOpen && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-3 sm:p-4">
          <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 w-full max-w-2xl max-h-[90vh] overflow-y-auto flex flex-col">
            {/* Modal Header */}
            <div className="p-4 sm:p-6 border-b border-slate-100 flex items-center justify-between sticky top-0 bg-white z-10">
              <div>
                <div className="flex items-center gap-2">
                  <i className="fa-solid fa-sliders text-indigo-600 text-base" />
                  <h3 className="font-bold text-slate-900 text-base sm:text-lg">Admin Plan Customizer</h3>
                </div>
                <p className="text-xs text-slate-500 mt-0.5">
                  Modify global pricing tiers or customize quotas and subscription plans for specific Shopify stores.
                </p>
              </div>
              <button
                onClick={() => setIsAdminOpen(false)}
                className="p-1.5 text-slate-400 hover:text-slate-700 rounded-lg hover:bg-slate-100 cursor-pointer"
              >
                <i className="fa-solid fa-xmark text-sm" />
              </button>
            </div>

            {/* Admin Tabs */}
            <div className="px-4 sm:px-6 pt-3 border-b border-slate-100 flex items-center gap-2 bg-slate-50/60">
              <button
                onClick={() => setAdminTab('plans')}
                className={`px-3.5 py-2 text-xs font-bold rounded-t-xl border-b-2 transition-all cursor-pointer flex items-center gap-1.5 ${
                  adminTab === 'plans'
                    ? 'border-indigo-600 text-indigo-600 bg-white shadow-2xs'
                    : 'border-transparent text-slate-500 hover:text-slate-800'
                }`}
              >
                <i className="fa-solid fa-layer-group text-xs" />
                <span>Global Plan Tiers</span>
              </button>

              <button
                onClick={() => setAdminTab('stores')}
                className={`px-3.5 py-2 text-xs font-bold rounded-t-xl border-b-2 transition-all cursor-pointer flex items-center gap-1.5 ${
                  adminTab === 'stores'
                    ? 'border-indigo-600 text-indigo-600 bg-white shadow-2xs'
                    : 'border-transparent text-slate-500 hover:text-slate-800'
                }`}
              >
                <i className="fa-solid fa-store text-xs" />
                <span>Shopify Stores &amp; Quotas ({shops.length})</span>
              </button>
            </div>

            {/* Modal Body */}
            {adminTab === 'plans' && editingPlan ? (
              <div className="p-4 sm:p-6 space-y-5">
                {/* Select which plan to customize */}
                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-slate-500 mb-2">
                    Select Plan to Edit:
                  </label>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                    {plans.map((p) => (
                      <button
                        key={p.id}
                        onClick={() => setEditingPlan({ ...p })}
                        className={`p-2.5 rounded-xl border text-xs font-semibold transition-all text-center cursor-pointer ${
                          editingPlan.id === p.id
                            ? 'border-indigo-600 bg-indigo-50/60 text-indigo-700'
                            : 'border-slate-200 text-slate-600 hover:bg-slate-50'
                        }`}
                      >
                        {p.name}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Basic Fields */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">Plan Display Name</label>
                    <input
                      type="text"
                      value={editingPlan.name}
                      onChange={(e) => setEditingPlan({ ...editingPlan, name: e.target.value })}
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">Price ($ USD / Month)</label>
                    <input
                      type="number"
                      value={editingPlan.price}
                      onChange={(e) => setEditingPlan({ ...editingPlan, price: parseFloat(e.target.value) || 0 })}
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">
                      SKU Limit (leave blank or 0 for Unlimited)
                    </label>
                    <input
                      type="number"
                      value={editingPlan.sku_limit ?? ''}
                      placeholder="Unlimited"
                      onChange={(e) =>
                        setEditingPlan({
                          ...editingPlan,
                          sku_limit: e.target.value ? parseInt(e.target.value) : null,
                        })
                      }
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">
                      Ad Campaigns Limit (blank for Unlimited)
                    </label>
                    <input
                      type="number"
                      value={editingPlan.campaigns_limit ?? ''}
                      placeholder="Unlimited"
                      onChange={(e) =>
                        setEditingPlan({
                          ...editingPlan,
                          campaigns_limit: e.target.value ? parseInt(e.target.value) : null,
                        })
                      }
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">Support Level Text</label>
                    <input
                      type="text"
                      value={editingPlan.support}
                      onChange={(e) => setEditingPlan({ ...editingPlan, support: e.target.value })}
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">
                      Free Trial (Shopify 7–14 Days, 0 for None)
                    </label>
                    <input
                      type="number"
                      value={editingPlan.trial_days ?? 0}
                      onChange={(e) =>
                        setEditingPlan({
                          ...editingPlan,
                          trial_days: parseInt(e.target.value) || 0,
                        })
                      }
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                  </div>
                </div>

                {/* Feature bullet list editor */}
                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-slate-500 mb-2">
                    Plan Features & Bullet Points:
                  </label>
                  <div className="space-y-2 mb-3">
                    {editingPlan.features.map((feat, index) => (
                      <div key={index} className="flex items-center gap-2">
                        <input
                          type="text"
                          value={feat}
                          onChange={(e) => {
                            const updated = [...editingPlan.features];
                            updated[index] = e.target.value;
                            setEditingPlan({ ...editingPlan, features: updated });
                          }}
                          className="flex-1 text-xs px-3 py-1.5 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                        />
                        <button
                          onClick={() => {
                            const updated = editingPlan.features.filter((_, i) => i !== index);
                            setEditingPlan({ ...editingPlan, features: updated });
                          }}
                          className="p-1.5 text-rose-500 hover:text-rose-700 hover:bg-rose-50 rounded-lg cursor-pointer"
                        >
                          <i className="fa-regular fa-trash-can text-xs" />
                        </button>
                      </div>
                    ))}
                  </div>

                  <div className="flex items-center gap-2">
                    <input
                      type="text"
                      value={newFeatureText}
                      placeholder="Add a new feature bullet point..."
                      onChange={(e) => setNewFeatureText(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' && newFeatureText.trim()) {
                          e.preventDefault();
                          setEditingPlan({
                            ...editingPlan,
                            features: [...editingPlan.features, newFeatureText.trim()],
                          });
                          setNewFeatureText('');
                        }
                      }}
                      className="flex-1 text-xs px-3 py-1.5 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                    <button
                      onClick={() => {
                        if (newFeatureText.trim()) {
                          setEditingPlan({
                            ...editingPlan,
                            features: [...editingPlan.features, newFeatureText.trim()],
                          });
                          setNewFeatureText('');
                        }
                      }}
                      className="px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold flex items-center gap-1 cursor-pointer shrink-0"
                    >
                      <i className="fa-solid fa-plus text-xs" />
                      <span>Add</span>
                    </button>
                  </div>
                </div>
              </div>
            ) : (
              /* TAB 2: STORE-SPECIFIC PLAN & QUOTA CUSTOMIZER */
              <div className="p-4 sm:p-6 space-y-5">
                {/* Select Shopify Store */}
                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-slate-700 mb-1.5">
                    Select Target Shopify Store Domain:
                  </label>
                  <div className="flex items-center gap-2">
                    <select
                      value={selectedStoreDomain}
                      onChange={(e) => {
                        const domain = e.target.value;
                        setSelectedStoreDomain(domain);
                        const storeFound = shops.find((s) => s.domain === domain);
                        if (storeFound) {
                          setSelectedStorePlan(storeFound.plan || 'growth');
                          setSelectedStoreCustomSku(storeFound.custom_sku_limit ? String(storeFound.custom_sku_limit) : '');
                          setSelectedStoreTrialDays(storeFound.trial_days ?? 14);
                        }
                      }}
                      className="flex-1 text-xs px-3 py-2 border border-slate-200 rounded-xl bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium"
                    >
                      {shops.map((s) => (
                        <option key={s.id || s.domain} value={s.domain}>
                          {s.domain} (Current: {s.plan.toUpperCase()})
                        </option>
                      ))}
                    </select>
                  </div>
                  <p className="text-[11px] text-slate-400 mt-1">
                    Choose any connected Shopify store to assign custom plan tiers, extend trials, or override SKU limits.
                  </p>
                </div>

                {/* Custom Store Domain Manual Input (for new stores) */}
                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">
                    Or Enter Store Domain Manually
                  </label>
                  <input
                    type="text"
                    value={selectedStoreDomain}
                    onChange={(e) => setSelectedStoreDomain(e.target.value.trim())}
                    placeholder="my-store.myshopify.com"
                    className="w-full text-xs px-3 py-2 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500 font-mono"
                  />
                </div>

                {/* Assign Plan Tier */}
                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-slate-700 mb-2">
                    Assigned Subscription Plan Tier:
                  </label>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                    {plans.map((p) => (
                      <button
                        key={p.id}
                        type="button"
                        onClick={() => setSelectedStorePlan(p.id)}
                        className={`p-3 rounded-xl border text-left cursor-pointer transition-all ${
                          selectedStorePlan === p.id
                            ? 'border-indigo-600 bg-indigo-50 text-indigo-900 font-bold shadow-xs'
                            : 'border-slate-200 hover:bg-slate-50 text-slate-700'
                        }`}
                      >
                        <div className="text-xs font-bold">{p.name}</div>
                        <div className="text-[11px] text-slate-500 mt-0.5">${p.price}/mo</div>
                      </button>
                    ))}
                  </div>
                </div>

                {/* Custom Quota & Trial Days */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">
                      Custom SKU Quota Override (leave blank for standard plan quota)
                    </label>
                    <input
                      type="number"
                      value={selectedStoreCustomSku}
                      placeholder="e.g. 50000 or leave empty"
                      onChange={(e) => setSelectedStoreCustomSku(e.target.value)}
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                    <span className="text-[10px] text-slate-400">Allows granting enterprise SKU limits to this specific store</span>
                  </div>

                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">
                      Free Trial Duration (Days)
                    </label>
                    <input
                      type="number"
                      value={selectedStoreTrialDays}
                      onChange={(e) => setSelectedStoreTrialDays(parseInt(e.target.value, 10) || 0)}
                      className="w-full text-xs px-3 py-2 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    />
                    <span className="text-[10px] text-slate-400">14-day free trial on Shopify App Store</span>
                  </div>
                </div>

                {/* Subscription Status */}
                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">Subscription Status</label>
                  <select
                    value={selectedStoreStatus}
                    onChange={(e) => setSelectedStoreStatus(e.target.value)}
                    className="w-full text-xs px-3 py-2 border border-slate-200 rounded-xl bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500 font-medium"
                  >
                    <option value="active">Active Subscription</option>
                    <option value="trial">14-Day Free Trial</option>
                    <option value="free">Free Tier</option>
                    <option value="suspended">Suspended / Paused</option>
                  </select>
                </div>
              </div>
            )}

            {/* Modal Footer */}
            <div className="p-4 sm:p-6 border-t border-slate-100 flex flex-col-reverse sm:flex-row items-stretch sm:items-center justify-between gap-3 sticky bottom-0 bg-white">
              {adminTab === 'plans' ? (
                <button
                  onClick={handleResetDefaults}
                  className="text-xs font-semibold text-rose-600 hover:text-rose-700 underline cursor-pointer text-center sm:text-left"
                >
                  Reset to Factory Defaults
                </button>
              ) : (
                <span className="text-xs text-slate-400">
                  Target Store: <span className="font-semibold text-slate-700 font-mono">{selectedStoreDomain}</span>
                </span>
              )}

              <div className="flex items-center justify-end gap-3">
                <button
                  onClick={() => setIsAdminOpen(false)}
                  className="w-1/2 sm:w-auto px-4 py-2 rounded-xl text-xs font-semibold border border-slate-200 text-slate-700 hover:bg-slate-50 cursor-pointer"
                >
                  Cancel
                </button>
                {adminTab === 'plans' ? (
                  <button
                    disabled={isSavingAdmin}
                    onClick={handleSaveAdminPlan}
                    className="w-1/2 sm:w-auto px-5 py-2 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-700 text-white shadow-md shadow-indigo-500/20 flex items-center justify-center gap-2 cursor-pointer"
                  >
                    {isSavingAdmin ? <i className="fa-solid fa-arrows-rotate text-xs fa-spin" /> : <i className="fa-solid fa-check text-xs" />}
                    <span>Save Plan Changes</span>
                  </button>
                ) : (
                  <button
                    disabled={isSavingStore}
                    onClick={handleSaveStorePlan}
                    className="w-1/2 sm:w-auto px-5 py-2 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-700 text-white shadow-md shadow-indigo-500/20 flex items-center justify-center gap-2 cursor-pointer"
                  >
                    {isSavingStore ? <i className="fa-solid fa-arrows-rotate text-xs fa-spin" /> : <i className="fa-solid fa-check text-xs" />}
                    <span>Save Store Settings</span>
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Plan Disabled / Coming Soon Popup Modal */}
      {disabledPlanModal && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-white rounded-3xl shadow-2xl border border-slate-200/80 w-full max-w-lg overflow-hidden transform transition-all">
            {/* Modal Header */}
            <div className="bg-slate-900 text-white p-6 sm:p-7 relative overflow-hidden">
              <div className="absolute -right-8 -top-8 w-32 h-32 rounded-full bg-white/5 blur-xl pointer-events-none" />
              <div className="flex items-start justify-between relative z-10">
                <div className="w-12 h-12 rounded-2xl bg-white/20 backdrop-blur-md flex items-center justify-center text-white border border-white/20 shadow-inner">
                  <i className="fa-solid fa-lock text-xl" />
                </div>
                <button
                  onClick={() => setDisabledPlanModal(null)}
                  className="w-8 h-8 rounded-full bg-black/10 hover:bg-black/20 text-white flex items-center justify-center transition-colors cursor-pointer"
                  title="Close"
                >
                  <i className="fa-solid fa-xmark text-sm" />
                </button>
              </div>
              <div className="mt-4 relative z-10">
                <div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-amber-400/30 text-amber-100 border border-amber-300/30 uppercase tracking-wider mb-2">
                  <i className="fa-solid fa-rocket text-[10px]" />
                  <span>Launch Phase Notice</span>
                </div>
                <h3 className="text-xl font-black text-white">
                  {disabledPlanModal.name} Plan is Temporarily Disabled
                </h3>
                <p className="text-xs text-amber-100 mt-1 leading-relaxed">
                  We are currently launching exclusively with our 100% Free Plan. Paid subscription tiers will be enabled soon!
                </p>
              </div>
            </div>

            {/* Modal Body */}
            <div className="p-6 sm:p-7 space-y-5">
              <div className="bg-amber-50/70 border border-amber-200/80 rounded-2xl p-4 text-xs text-amber-900 leading-relaxed">
                <div className="flex items-start gap-3">
                  <i className="fa-solid fa-circle-info text-amber-600 text-sm mt-0.5 shrink-0" />
                  <div>
                    <p className="font-bold text-amber-950">Why is this plan locked?</p>
                    <p className="mt-1 text-amber-800">
                      During our official public launch, our entire team is focusing on delivering a seamless experience for every merchant on our <strong>Free Plan ($0 / No Credit Card Required)</strong>.
                    </p>
                  </div>
                </div>
              </div>

              <div>
                <h4 className="text-xs font-bold text-slate-800 uppercase tracking-wider mb-3 flex items-center gap-2">
                  <i className="fa-solid fa-gift text-emerald-600" />
                  <span>Everything You Get Free Today</span>
                </h4>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                  <div className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-700">
                    <i className="fa-solid fa-circle-check text-emerald-600 shrink-0" />
                    <span className="font-medium">Upload up to 100 SKUs</span>
                  </div>
                  <div className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-700">
                    <i className="fa-solid fa-circle-check text-emerald-600 shrink-0" />
                    <span className="font-medium">Automatic Product Syncing</span>
                  </div>
                  <div className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-700">
                    <i className="fa-solid fa-circle-check text-emerald-600 shrink-0" />
                    <span className="font-medium">1 Facebook Basic Ad Campaign</span>
                  </div>
                  <div className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-700">
                    <i className="fa-solid fa-circle-check text-emerald-600 shrink-0" />
                    <span className="font-medium">Unlimited Product Templates</span>
                  </div>
                  <div className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-700">
                    <i className="fa-solid fa-circle-check text-emerald-600 shrink-0" />
                    <span className="font-medium">Overall Statistics &amp; Analytics</span>
                  </div>
                  <div className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-700">
                    <i className="fa-solid fa-circle-check text-emerald-600 shrink-0" />
                    <span className="font-medium">Dedicated Email Support</span>
                  </div>
                </div>
              </div>

              <div className="pt-2 border-t border-slate-100 flex flex-col sm:flex-row items-center gap-3">
                <button
                  type="button"
                  onClick={() => setDisabledPlanModal(null)}
                  className="w-full sm:w-1/2 py-2.5 px-4 rounded-xl text-xs font-bold text-white bg-slate-900 hover:bg-slate-800 transition-colors shadow-sm cursor-pointer text-center"
                >
                  Continue with Free Plan
                </button>
                <a
                  href={`mailto:${APP_CONFIG.supportEmail}?subject=Inquiry regarding ${disabledPlanModal.name} Plan upgrade`}
                  className="w-full sm:w-1/2 py-2.5 px-4 rounded-xl text-xs font-semibold text-slate-700 hover:text-slate-900 bg-slate-100 hover:bg-slate-200 transition-colors text-center border border-slate-200 flex items-center justify-center gap-2 cursor-pointer"
                >
                  <i className="fa-solid fa-envelope text-slate-500" />
                  <span>Contact Support</span>
                </a>
              </div>
            </div>
          </div>
        </div>
      )}
      </div>
    </AppLayout>
  );
}
