'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import AppLayout from '@/components/layout/AppLayout';
import { appRoute } from '@/lib/utils/asset';
import { showToast as appBridgeToast } from '@/lib/shopify/appBridge';


import {
  ProductTemplate,
  DEFAULT_TEMPLATES,
  VARIABLE_TAGS,
  loadAllTemplates,
  saveAllTemplates,
} from '@/lib/templates/template-service';

export default function ProductTemplatesPage() {
  const [templates, setTemplates] = useState<ProductTemplate[]>(DEFAULT_TEMPLATES);
  const [activeTemplate, setActiveTemplate] = useState<ProductTemplate>(DEFAULT_TEMPLATES[0]);
  const [activeTab, setActiveTab] = useState<'editor' | 'library'>('editor');
  const [toastMessage, setToastMessage] = useState<string | null>(null);
  const [activeShop, setActiveShop] = useState<string>('');
  const [storePlan, setStorePlan] = useState<string>('basic');
  const [showUpgradeModal, setShowUpgradeModal] = useState<boolean>(false);
  const isFreePlan = storePlan === 'basic';
  const getHref = (path: string) => appRoute(path, activeShop);

  useEffect(() => {
    fetchShopInfo();
    const loaded = loadAllTemplates();
    setTemplates(loaded);
    if (loaded.length > 0) {
      setActiveTemplate(loaded[0]);
    }
  }, []);

  const fetchShopInfo = async () => {
    try {
      const res = await fetch('/api/shops');
      const data = await res.json();
      if (data.success && data.store) {
        if (data.store.domain) setActiveShop(data.store.domain);
        if (data.store.plan) setStorePlan(data.store.plan);
      }
    } catch {
      // ignore
    }
  };

  const showToast = (msg: string) => {
    appBridgeToast(msg);
    setToastMessage(msg);
    setTimeout(() => setToastMessage(null), 3500);
  };

  const handleSaveTemplate = () => {
    if (isFreePlan && activeTemplate.id !== 'tpl_advantage_plus') {
      setShowUpgradeModal(true);
      return;
    }
    const exists = templates.some(t => t.id === activeTemplate.id);
    let updated: ProductTemplate[];
    if (exists) {
      updated = templates.map(t => (t.id === activeTemplate.id ? activeTemplate : t));
    } else {
      updated = [...templates, activeTemplate];
    }
    setTemplates(updated);
    saveAllTemplates(updated);
    showToast(`Template "${activeTemplate.name}" saved successfully!`);
  };

  const handleCreateNew = () => {
    if (isFreePlan) {
      setShowUpgradeModal(true);
      return;
    }
    const newTpl: ProductTemplate = {
      id: `tpl_custom_${Date.now()}`,
      name: 'New Custom Template',
      description: 'Custom title and attribute template for Meta product catalogs.',
      type: 'complete',
      titlePattern: '{{product.title}} - {{variant.title}} | {{product.vendor}}',
      descriptionPattern: '{{product.description}}',
      priceRule: 'compare_at_and_price',
      customLabels: {
        label0: 'CustomFeed',
      },
    };
    setActiveTemplate(newTpl);
    setActiveTab('editor');
  };

  const handleInsertTag = (tag: string, field: 'title' | 'description') => {
    if (field === 'title') {
      setActiveTemplate(prev => ({
        ...prev,
        titlePattern: `${prev.titlePattern} ${tag}`.trim(),
      }));
    } else {
      setActiveTemplate(prev => ({
        ...prev,
        descriptionPattern: `${prev.descriptionPattern} ${tag}`.trim(),
      }));
    }
  };

  // Live preview parser
  const renderPreviewTitle = () => {
    let t = activeTemplate.titlePattern || '{{product.title}}';
    VARIABLE_TAGS.forEach(v => {
      t = t.replaceAll(v.tag, v.sample);
    });
    return t;
  };

  const renderPreviewDescription = () => {
    let d = activeTemplate.descriptionPattern || 'High-performance all-mountain snowboard with dual carbon stringers and sintered base.';
    VARIABLE_TAGS.forEach(v => {
      d = d.replaceAll(v.tag, v.sample);
    });
    return d;
  };

  return (
    <AppLayout currentRoute="/templates">
      <ui-title-bar title="Product Templates & Rules">
        <button variant="primary" onClick={handleSaveTemplate}>Save Template</button>
      </ui-title-bar>
      <div className="space-y-6 pb-16">
        {/* 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-xs font-semibold bg-slate-900 text-white border-slate-700 animate-in fade-in duration-200">
            <i className="fa-solid fa-circle-check text-emerald-400 text-sm" />
            <span>{toastMessage}</span>
          </div>
        )}

        {/* Page Header */}
        <div className="flex flex-col sm:flex-row sm: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-slate-700 uppercase tracking-wider">
              <i className="fa-solid fa-wand-magic-sparkles text-xs" />
              <span>Catalog Optimization Studio</span>
              {isFreePlan && (
                <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-slate-100 text-slate-800 border border-slate-200 normal-case">
                  Free Plan: 1 Template Included
                </span>
              )}
            </div>
            <h1 className="text-2xl font-bold text-slate-900 tracking-tight mt-1">Product Templates &amp; Dynamic Ad Rules</h1>
            <p className="text-xs text-slate-500">
              Create dynamic title templates, price formatting rules, and custom labels for Advantage+ Dynamic Ads.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <Link
              href={getHref('/catalog')}
              className="px-3.5 py-2 bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold rounded-xl flex items-center justify-center gap-1.5 shadow-2xs transition"
            >
              <i className="fa-solid fa-layer-group text-slate-700 text-xs" />
              <span>Apply to Catalogs</span>
            </Link>
            <button
              onClick={handleCreateNew}
              className="px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl flex items-center justify-center gap-1.5 shadow-sm hover:shadow-md transition active:scale-98 cursor-pointer"
            >
              <i className="fa-solid fa-plus text-xs" />
              <span>Create Template</span>
              {isFreePlan && <i className="fa-solid fa-lock text-[10px] text-slate-400 ml-0.5" />}
            </button>
          </div>
        </div>

        {/* Main Grid: Template Presets / Editor + Live Ad Preview */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
          {/* Left Column: Preset Selector & Template Editor (7 cols) */}
          <div className="lg:col-span-7 space-y-5">
            {/* Presets Quick Selector */}
            <div className="bg-white rounded-2xl border border-slate-200/80 p-4 sm:p-5 shadow-xs space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                  Template Library ({templates.length})
                </span>
                <span className="text-[11px] text-slate-400">
                  {isFreePlan ? 'Free plan: Advantage+ Dynamic Ad Standard' : 'Click to load & customize'}
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                {templates.map(t => {
                  const isSelected = activeTemplate.id === t.id;
                  const isLocked = isFreePlan && t.id !== 'tpl_advantage_plus';

                  return (
                    <button
                      key={t.id}
                      type="button"
                      onClick={() => {
                        if (isLocked) {
                          setShowUpgradeModal(true);
                          return;
                        }
                        setActiveTemplate({ ...t });
                      }}
                      className={`p-3.5 rounded-xl border text-left transition-all flex flex-col justify-between cursor-pointer ${
                        isLocked
                          ? 'border-slate-200 bg-slate-50/70 hover:bg-slate-100/70 opacity-80'
                          : isSelected
                          ? 'border-slate-900 bg-slate-50 shadow-2xs ring-2 ring-slate-900/10'
                          : 'border-slate-200 bg-white hover:bg-slate-50 text-slate-700'
                      }`}
                    >
                      <div className="w-full">
                        <div className="flex items-start justify-between gap-2 mb-2">
                          <h4 className="font-bold text-xs text-slate-900 flex items-center gap-1.5 leading-snug">
                            {isLocked && <i className="fa-solid fa-lock text-[10px] text-slate-400 shrink-0" />}
                            <span>{t.name}</span>
                          </h4>
                          {isLocked ? (
                            <span className="shrink-0 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider bg-slate-200/80 text-slate-700 border border-slate-300 flex items-center gap-1">
                              <i className="fa-solid fa-lock text-[8px]" />
                              <span>Paid Plan</span>
                            </span>
                          ) : t.id === 'tpl_advantage_plus' && isFreePlan ? (
                            <span className="shrink-0 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider bg-emerald-50 text-emerald-700 border border-emerald-200 flex items-center gap-1">
                              <i className="fa-solid fa-circle-check text-[8px]" />
                              <span>Default (Free)</span>
                            </span>
                          ) : t.badgeText ? (
                            <span className="shrink-0 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider bg-slate-100 text-slate-700 border border-slate-200">
                              {t.badgeText}
                            </span>
                          ) : null}
                        </div>
                        <p className="text-[11px] text-slate-500 leading-relaxed">{t.description}</p>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Template Editor Form */}
            <div className="bg-white rounded-2xl border border-slate-200/80 p-4 sm:p-6 shadow-xs space-y-5">
              <div className="flex items-center justify-between pb-3 border-b border-slate-100">
                <div className="flex items-center gap-2">
                  <i className="fa-solid fa-sliders text-theme text-sm" />
                  <h3 className="text-sm font-bold text-slate-900">Template Customizer</h3>
                </div>
                <button
                  onClick={handleSaveTemplate}
                  className="px-4 py-1.5 bg-theme hover:bg-theme-hover text-white text-xs font-bold rounded-xl shadow-sm hover:shadow-md transition flex items-center gap-1.5 cursor-pointer"
                >
                  <i className="fa-solid fa-check text-xs" />
                  <span>Save Template</span>
                </button>
              </div>

              {isFreePlan && (
                <div className="p-3 bg-slate-50 border border-slate-200 rounded-xl flex items-center justify-between gap-3 text-xs">
                  <div className="flex items-center gap-2 text-slate-700">
                    <i className="fa-solid fa-circle-info text-slate-600" />
                    <span>Free Plan: Editing default <strong>Advantage+ Dynamic Ad Standard</strong> template.</span>
                  </div>
                  <Link
                    href={getHref('/pricing')}
                    className="shrink-0 px-2.5 py-1 bg-slate-900 text-white rounded-lg text-[11px] font-bold hover:bg-slate-800 transition"
                  >
                    Upgrade
                  </Link>
                </div>
              )}

              {/* Template Name & Description */}
              <div className="grid grid-cols-1 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">Template Name</label>
                  <input
                    type="text"
                    value={activeTemplate.name}
                    onChange={e => setActiveTemplate({ ...activeTemplate, name: e.target.value })}
                    className="w-full px-3.5 py-2 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme font-medium"
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">Description</label>
                  <input
                    type="text"
                    value={activeTemplate.description}
                    onChange={e => setActiveTemplate({ ...activeTemplate, description: e.target.value })}
                    className="w-full px-3.5 py-2 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme"
                  />
                </div>
              </div>

              {/* Dynamic Title Pattern */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <label className="block text-xs font-bold text-slate-900">Product Title Formula</label>
                  <span className="text-[11px] text-slate-400">Supports merge variables</span>
                </div>
                <textarea
                  rows={2}
                  value={activeTemplate.titlePattern}
                  onChange={e => setActiveTemplate({ ...activeTemplate, titlePattern: e.target.value })}
                  placeholder="e.g. {{product.title}} - {{variant.title}} | {{product.vendor}}"
                  className="w-full px-3.5 py-2.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme font-mono"
                />

                {/* Merge Variable Chips */}
                <div>
                  <div className="text-[11px] font-semibold text-slate-500 mb-1.5 flex items-center gap-1">
                    <span>Click to insert variable into Title:</span>
                  </div>
                  <div className="flex flex-wrap gap-1.5">
                    {VARIABLE_TAGS.map(v => (
                      <button
                        key={v.tag}
                        type="button"
                        onClick={() => handleInsertTag(v.tag, 'title')}
                        className="px-2 py-1 rounded-lg bg-slate-100 hover:bg-theme/10 hover:text-theme border border-slate-200/80 text-[11px] font-mono text-slate-700 transition cursor-pointer"
                        title={`Inserts sample value: ${v.sample}`}
                      >
                        + {v.tag}
                      </button>
                    ))}
                  </div>
                </div>
              </div>

              {/* Dynamic Description Pattern */}
              <div className="space-y-2 pt-2 border-t border-slate-100">
                <label className="block text-xs font-bold text-slate-900">Product Description Formula</label>
                <textarea
                  rows={3}
                  value={activeTemplate.descriptionPattern}
                  onChange={e => setActiveTemplate({ ...activeTemplate, descriptionPattern: e.target.value })}
                  placeholder="e.g. {{product.description}} - Fast shipping from {{product.vendor}}."
                  className="w-full px-3.5 py-2.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme font-mono"
                />
              </div>

              {/* Pricing & Compare-At Rule */}
              <div className="space-y-2 pt-2 border-t border-slate-100">
                <label className="block text-xs font-bold text-slate-900">Price &amp; Sale Discount Rule</label>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                  <label
                    className={`p-3 rounded-xl border text-xs cursor-pointer transition ${
                      activeTemplate.priceRule === 'compare_at_and_price'
                        ? 'bg-theme/5 border-theme text-theme font-semibold ring-1 ring-theme/20'
                        : 'bg-white border-slate-200 text-slate-700'
                    }`}
                  >
                    <input
                      type="radio"
                      name="priceRule"
                      checked={activeTemplate.priceRule === 'compare_at_and_price'}
                      onChange={() => setActiveTemplate({ ...activeTemplate, priceRule: 'compare_at_and_price' })}
                      className="sr-only"
                    />
                    <div className="font-bold">Original &amp; Sale Price</div>
                    <div className="text-[10px] text-slate-500 mt-0.5">Shows discount badges</div>
                  </label>

                  <label
                    className={`p-3 rounded-xl border text-xs cursor-pointer transition ${
                      activeTemplate.priceRule === 'price_only'
                        ? 'bg-theme/5 border-theme text-theme font-semibold ring-1 ring-theme/20'
                        : 'bg-white border-slate-200 text-slate-700'
                    }`}
                  >
                    <input
                      type="radio"
                      name="priceRule"
                      checked={activeTemplate.priceRule === 'price_only'}
                      onChange={() => setActiveTemplate({ ...activeTemplate, priceRule: 'price_only' })}
                      className="sr-only"
                    />
                    <div className="font-bold">Current Price Only</div>
                    <div className="text-[10px] text-slate-500 mt-0.5">Standard single price</div>
                  </label>

                  <label
                    className={`p-3 rounded-xl border text-xs cursor-pointer transition ${
                      activeTemplate.priceRule === 'compare_at_only'
                        ? 'bg-theme/5 border-theme text-theme font-semibold ring-1 ring-theme/20'
                        : 'bg-white border-slate-200 text-slate-700'
                    }`}
                  >
                    <input
                      type="radio"
                      name="priceRule"
                      checked={activeTemplate.priceRule === 'compare_at_only'}
                      onChange={() => setActiveTemplate({ ...activeTemplate, priceRule: 'compare_at_only' })}
                      className="sr-only"
                    />
                    <div className="font-bold">MSRP / Compare Price</div>
                    <div className="text-[10px] text-slate-500 mt-0.5">Anchor catalog price</div>
                  </label>
                </div>
              </div>

              {/* Custom Labels Mapping (0 to 4) */}
              <div className="space-y-3 pt-2 border-t border-slate-100">
                <div className="flex items-center justify-between">
                  <label className="block text-xs font-bold text-slate-900">Custom Labels (Campaign Segmentation)</label>
                  <span className="text-[10px] text-slate-400">Mapped to Meta Custom Labels 0–4</span>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[11px] font-semibold text-slate-600 mb-1">Custom Label 0 (e.g. Margin / Price Tier)</label>
                    <input
                      type="text"
                      value={activeTemplate.customLabels.label0 || ''}
                      onChange={e =>
                        setActiveTemplate({
                          ...activeTemplate,
                          customLabels: { ...activeTemplate.customLabels, label0: e.target.value },
                        })
                      }
                      placeholder="e.g. HighMargin or {{discount_percent}}% OFF"
                      className="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 font-mono focus:ring-2 focus:ring-theme/20 focus:border-theme"
                    />
                  </div>

                  <div>
                    <label className="block text-[11px] font-semibold text-slate-600 mb-1">Custom Label 1 (e.g. Season / Collection)</label>
                    <input
                      type="text"
                      value={activeTemplate.customLabels.label1 || ''}
                      onChange={e =>
                        setActiveTemplate({
                          ...activeTemplate,
                          customLabels: { ...activeTemplate.customLabels, label1: e.target.value },
                        })
                      }
                      placeholder="e.g. Winter2026 or {{product.product_type}}"
                      className="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 font-mono focus:ring-2 focus:ring-theme/20 focus:border-theme"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Right Column: Real-Time Facebook Dynamic Ad Preview Card (5 cols) */}
          <div className="lg:col-span-5 space-y-4 lg:sticky lg:top-20">
            <div className="bg-white rounded-2xl border border-slate-200/80 p-4 sm:p-5 shadow-xs space-y-4">
              <div className="flex items-center justify-between pb-3 border-b border-slate-100">
                <div className="flex items-center gap-2">
                  <i className="fa-regular fa-eye text-theme text-sm" />
                  <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                    Live Meta Ad Preview
                  </h3>
                </div>
                <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
                  Advantage+ Feed
                </span>
              </div>

              {/* Simulated Facebook Carousel Ad Card */}
              <div className="bg-slate-50 border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
                {/* Ad Sponsor Header */}
                <div className="p-3 sm:p-3.5 bg-white flex items-center gap-2.5 border-b border-slate-100">
                  <div className="w-7 h-7 rounded-full bg-blue-600 text-white font-bold text-xs flex items-center justify-center shrink-0">
                    f
                  </div>
                  <div className="min-w-0">
                    <h5 className="font-bold text-xs text-slate-900 leading-none truncate">{activeShop || 'Your Shopify Store'}</h5>
                    <p className="text-[10px] text-slate-400 mt-0.5 truncate">Sponsored • Advantage+ Catalog Ad</p>
                  </div>
                </div>

                {/* Product Image Box */}
                <div className="relative aspect-square bg-slate-100 flex items-center justify-center overflow-hidden">
                  <img
                    src="https://images.unsplash.com/photo-1551698618-1dfe5d97d256?auto=format&fit=crop&w=600&q=80"
                    alt="Sample Product"
                    width={600}
                    height={600}
                    loading="lazy"
                    className="w-full h-full object-cover"
                  />
                  {/* Dynamic Sale Badge Overlay */}
                  {activeTemplate.priceRule === 'compare_at_and_price' && (
                    <div className="absolute top-3 left-3 bg-rose-600 text-white text-[11px] font-extrabold px-2.5 py-1 rounded-lg shadow-md uppercase tracking-wider flex items-center gap-1">
                      <span>SALE -29%</span>
                    </div>
                  )}
                  <div className="absolute bottom-3 right-3 bg-slate-900/80 backdrop-blur-xs text-white text-[10px] font-medium px-2 py-0.5 rounded-md">
                    1 of 6 Variants
                  </div>
                </div>

                {/* Ad Body Content */}
                <div className="p-3.5 sm:p-4 bg-white space-y-2">
                  <div className="flex items-baseline justify-between gap-2">
                    <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider truncate">
                      {activeShop || 'quickstart.myshopify.com'}
                    </span>
                    <div className="flex items-center gap-1.5 shrink-0">
                      {activeTemplate.priceRule === 'compare_at_and_price' ? (
                        <>
                          <span className="text-xs line-through text-slate-400 font-medium">$349.00</span>
                          <span className="text-sm font-extrabold text-slate-900">$249.00 USD</span>
                        </>
                      ) : (
                        <span className="text-sm font-extrabold text-slate-900">$249.00 USD</span>
                      )}
                    </div>
                  </div>

                  {/* Rendered Live Title */}
                  <h4 className="font-bold text-xs text-slate-900 leading-snug line-clamp-2">
                    {renderPreviewTitle()}
                  </h4>

                  {/* Rendered Live Description */}
                  <p className="text-[11px] text-slate-500 line-clamp-2 leading-relaxed">
                    {renderPreviewDescription()}
                  </p>

                  <button className="w-full mt-2 py-2 px-3 bg-slate-100 hover:bg-slate-200 text-slate-900 rounded-xl text-xs font-bold transition flex items-center justify-center gap-1.5 cursor-pointer">
                    <span>Shop Now</span>
                    <i className="fa-solid fa-arrow-right text-xs" />
                  </button>
                </div>
              </div>

              {/* Feed Meta Tags Preview */}
              <div className="p-3 bg-slate-50 rounded-xl border border-slate-200/80 space-y-1.5 text-xs">
                <div className="font-bold text-slate-900 text-[11px]">Exported Catalog Payload:</div>
                <div className="font-mono text-[10px] text-slate-600 space-y-1 overflow-x-auto">
                  <div className="truncate"><strong>title:</strong> {renderPreviewTitle()}</div>
                  <div><strong>price:</strong> {activeTemplate.priceRule === 'compare_at_and_price' ? '349.00 USD' : '249.00 USD'}</div>
                  {activeTemplate.priceRule === 'compare_at_and_price' && (
                    <div><strong>sale_price:</strong> 249.00 USD</div>
                  )}
                  {activeTemplate.customLabels.label0 && (
                    <div className="truncate"><strong>custom_label_0:</strong> {activeTemplate.customLabels.label0}</div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Upgrade Required Modal */}
      {showUpgradeModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-xs animate-in fade-in duration-200">
          <div className="bg-white rounded-2xl max-w-md w-full shadow-2xl border border-slate-200 overflow-hidden text-center p-6 space-y-4 animate-in zoom-in-95 duration-200">
            <div className="w-14 h-14 mx-auto rounded-2xl bg-slate-100 border border-slate-200 flex items-center justify-center text-slate-900 shadow-xs">
              <i className="fa-solid fa-crown text-2xl" />
            </div>
            <div>
              <div className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[11px] font-bold bg-slate-100 text-slate-800 border border-slate-200 mb-2">
                <i className="fa-solid fa-lock text-[10px]" />
                <span>Paid Plan Feature</span>
              </div>
              <h3 className="text-lg font-bold text-slate-900">Unlock Unlimited Product Templates</h3>
              <p className="text-xs text-slate-600 mt-2 leading-relaxed">
                Your Free Plan includes <strong>1 Default Template (Advantage+ Dynamic Ad Standard)</strong>.
                Upgrade to our Growth or Accelerate plan to create unlimited custom templates, dynamic pricing formulas, and advanced catalog rules.
              </p>
            </div>

            <div className="bg-slate-50 border border-slate-200/80 rounded-xl p-3.5 text-left space-y-2 text-xs">
              <div className="font-semibold text-slate-900 flex items-center gap-2">
                <i className="fa-solid fa-sparkles text-slate-700" />
                <span>Paid Plan Benefits:</span>
              </div>
              <ul className="text-slate-600 space-y-1.5 pl-1 text-[11px]">
                <li className="flex items-center gap-2">
                  <i className="fa-solid fa-check text-emerald-600 text-[10px]" />
                  <span>Unlimited custom product title &amp; description formulas</span>
                </li>
                <li className="flex items-center gap-2">
                  <i className="fa-solid fa-check text-emerald-600 text-[10px]" />
                  <span>Compare-at price and dynamic sale percentage badges</span>
                </li>
                <li className="flex items-center gap-2">
                  <i className="fa-solid fa-check text-emerald-600 text-[10px]" />
                  <span>Custom label segmenting (custom_label_0 to custom_label_4)</span>
                </li>
              </ul>
            </div>

            <div className="flex items-center gap-3 pt-2">
              <button
                type="button"
                onClick={() => setShowUpgradeModal(false)}
                className="flex-1 py-2.5 px-4 bg-white hover:bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold text-slate-700 transition cursor-pointer"
              >
                Close
              </button>
              <Link
                href={getHref('/pricing')}
                className="flex-1 py-2.5 px-4 bg-slate-900 hover:bg-slate-800 text-white rounded-xl text-xs font-bold transition shadow-sm hover:shadow-md flex items-center justify-center gap-1.5"
              >
                <span>View Upgrade Plans</span>
                <i className="fa-solid fa-arrow-right text-[11px]" />
              </Link>
            </div>
          </div>
        </div>
      )}
    </AppLayout>
  );
}
