{#
   =============================================================================
   Feature Gate Macros

   Provides macros for tier-based feature gating in templates.
   Uses Alpine.js $store.features for dynamic checking.

   Usage:
   from "shared/macros/feature_gate.html" import feature_gate, feature_locked, upgrade_banner

   Show content only if feature is available:
   call feature_gate("analytics_dashboard")
       <div>Analytics content here</div>
   endcall

   Show locked state with upgrade prompt:
   feature_locked("analytics_dashboard", "Analytics Dashboard", "View advanced analytics")

   Show upgrade banner:
   upgrade_banner("analytics_dashboard")
   =============================================================================
#}


{# =============================================================================
   Feature Gate Container
   Shows content only if feature is available

   Parameters:
   - feature_code: The feature code to check
   - fallback: Optional fallback content when feature is not available
   ============================================================================= #}
{% macro feature_gate(feature_code, show_fallback=true) %}
<div x-data x-show="$store.features.has('{{ feature_code }}')" x-cloak>
    {{ caller() }}
</div>
{% if show_fallback %}
<div x-data x-show="$store.features.loaded && !$store.features.has('{{ feature_code }}')" x-cloak>
    {{ feature_locked(feature_code) }}
</div>
{% endif %}
{% endmacro %}


{# =============================================================================
   Feature Locked Card
   Shows a card explaining the feature is locked with upgrade prompt

   Parameters:
   - feature_code: The feature code
   - title: Optional title override
   - description: Optional description override
   - show_upgrade_button: Whether to show upgrade button (default true)
   ============================================================================= #}
{% macro feature_locked(feature_code, title=none, description=none, show_upgrade_button=true) %}
<div class="bg-gray-50 dark:bg-gray-800 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600 p-6 text-center"
     x-data="{ feature: null }"
     x-init="
         await $store.features.loadFullFeatures();
         feature = $store.features.getFeature('{{ feature_code }}');
     ">
    {# Lock icon #}
    <div class="mx-auto w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center mb-4">
        <svg class="w-6 h-6 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
        </svg>
    </div>

    {# Title #}
    <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">
        {% if title %}
            {{ title }}
        {% else %}
            <span x-text="feature?.name || 'Premium Feature'">Premium Feature</span>
        {% endif %}
    </h3>

    {# Description #}
    <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
        {% if description %}
            {{ description }}
        {% else %}
            <span x-text="feature?.description || 'This feature requires a plan upgrade.'">
                This feature requires a plan upgrade.
            </span>
        {% endif %}
    </p>

    {# Tier badge #}
    <p class="text-sm text-gray-600 dark:text-gray-300 mb-4">
        Available on
        <span class="font-semibold text-purple-600 dark:text-purple-400"
              x-text="feature?.minimum_tier_name || 'higher tier'">higher tier</span>
        plan
    </p>

    {% if show_upgrade_button %}
    {# Upgrade button #}
    <a :href="`/store/${$store.features.getStoreCode()}/billing`"
       class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md
              text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2
              focus:ring-offset-2 focus:ring-purple-500 transition-colors">
        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/>
        </svg>
        Upgrade Plan
    </a>
    {% endif %}
</div>
{% endmacro %}


{# =============================================================================
   Upgrade Banner
   Inline banner for upgrade prompts

   Parameters:
   - feature_code: The feature code
   - message: Optional custom message
   ============================================================================= #}
{% macro upgrade_banner(feature_code, message=none) %}
<div x-data="{ feature: null }"
     x-init="
         await $store.features.loadFullFeatures();
         feature = $store.features.getFeature('{{ feature_code }}');
     "
     x-show="$store.features.loaded && !$store.features.has('{{ feature_code }}')"
     x-cloak
     class="bg-gradient-to-r from-purple-500 to-indigo-600 rounded-lg p-4 mb-4">
    <div class="flex items-center justify-between">
        <div class="flex items-center">
            <svg class="w-5 h-5 text-white mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M13 10V3L4 14h7v7l9-11h-7z"/>
            </svg>
            <p class="text-white text-sm">
                {% if message %}
                    {{ message }}
                {% else %}
                    <span x-text="'Upgrade to ' + (feature?.minimum_tier_name || 'a higher plan') + ' to unlock ' + (feature?.name || 'this feature')">
                        Upgrade to unlock this feature
                    </span>
                {% endif %}
            </p>
        </div>
        <a :href="`/store/${$store.features.getStoreCode()}/billing`"
           class="inline-flex items-center px-3 py-1.5 border border-white text-xs font-medium rounded
                  text-white hover:bg-white hover:text-purple-600 transition-colors">
            Upgrade
        </a>
    </div>
</div>
{% endmacro %}


{# =============================================================================
   Feature Badge
   Small badge to show feature tier requirement

   Parameters:
   - feature_code: The feature code
   ============================================================================= #}
{% macro feature_badge(feature_code) %}
<span x-data="{ feature: null }"
      x-init="
          await $store.features.loadFullFeatures();
          feature = $store.features.getFeature('{{ feature_code }}');
      "
      x-show="!$store.features.has('{{ feature_code }}')"
      x-cloak
      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200">
    <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
    </svg>
    <span x-text="feature?.minimum_tier_name || 'Pro'">Pro</span>
</span>
{% endmacro %}


{# =============================================================================
   Sidebar Item with Feature Gate
   Sidebar navigation item that shows lock if feature not available

   Parameters:
   - feature_code: The feature code
   - href: Link URL
   - icon: Icon name
   - label: Display label
   - current_page: Current page for active state
   ============================================================================= #}
{% macro sidebar_item_gated(feature_code, href, icon, label, current_page='') %}
<template x-if="$store.features.has('{{ feature_code }}')">
    <a href="{{ href }}"
       class="flex items-center px-4 py-2 text-sm font-medium rounded-lg transition-colors
              {{ 'bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-white' if current_page == label|lower else 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800 hover:text-gray-900 dark:hover:text-white' }}">
        <span class="w-5 h-5 mr-3" x-html="window.icons?.['{{ icon }}'] || ''"></span>
        {{ label }}
    </a>
</template>
<template x-if="!$store.features.has('{{ feature_code }}')">
    <div class="flex items-center px-4 py-2 text-sm font-medium rounded-lg text-gray-400 dark:text-gray-500 cursor-not-allowed"
         title="Requires plan upgrade">
        <span class="w-5 h-5 mr-3" x-html="window.icons?.['{{ icon }}'] || ''"></span>
        {{ label }}
        <svg class="w-4 h-4 ml-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
        </svg>
    </div>
</template>
{% endmacro %}


{# =============================================================================
   UPGRADE PROMPT MACROS
   ============================================================================= #}


{# =============================================================================
   Usage Limit Warning
   Shows warning banner when approaching or at a limit

   Parameters:
   - metric_name: One of "orders", "products", "team_members"
   ============================================================================= #}
{% macro limit_warning(metric_name) %}
<div x-data
     x-init="$store.upgrade.loadUsage()"
     x-show="$store.upgrade.shouldShowLimitWarning('{{ metric_name }}')"
     x-cloak
     x-html="$store.upgrade.getLimitWarningHTML('{{ metric_name }}')">
</div>
{% endmacro %}


{# =============================================================================
   Usage Progress Bar
   Shows compact progress bar for a limit

   Parameters:
   - metric_name: One of "orders", "products", "team_members"
   - label: Display label
   ============================================================================= #}
{% macro usage_bar(metric_name, label) %}
<div x-data x-init="$store.upgrade.loadUsage()">
    <div class="flex items-center justify-between mb-1">
        <span class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ label }}</span>
        <span class="text-sm text-gray-500 dark:text-gray-400"
              x-text="$store.upgrade.getUsageString('{{ metric_name }}')"></span>
    </div>
    <div x-html="$store.upgrade.getUsageBarHTML('{{ metric_name }}')"></div>
</div>
{% endmacro %}


{# =============================================================================
   Upgrade Card
   Shows upgrade recommendation card (for dashboard)
   Only shows if there are upgrade recommendations

   Parameters:
   - class: Additional CSS classes
   ============================================================================= #}
{% macro upgrade_card(class='') %}
<div x-data
     x-init="$store.upgrade.loadUsage()"
     x-show="$store.upgrade.hasUpgradeRecommendation"
     x-cloak
     class="{{ class }}"
     x-html="$store.upgrade.getUpgradeCardHTML()">
</div>
{% endmacro %}


{# =============================================================================
   Limit Check Button
   Button that checks limit before action

   Parameters:
   - limit_type: One of "orders", "products", "team_members"
   - action: JavaScript to execute if limit allows
   - label: Button label
   - class: Additional CSS classes
   ============================================================================= #}
{% macro limit_check_button(limit_type, action, label, class='') %}
<button
    @click="$store.upgrade.checkLimitAndProceed('{{ limit_type }}', () => { {{ action }} })"
    class="{{ class }}">
    {{ label }}
</button>
{% endmacro %}


{# =============================================================================
   Tier Badge
   Shows current tier as a badge

   Parameters:
   - class: Additional CSS classes
   ============================================================================= #}
{% macro tier_badge(class='') %}
<span x-data
      x-init="$store.upgrade.loadUsage()"
      x-show="$store.upgrade.currentTier"
      x-cloak
      class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ class }}"
      :class="{
          'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300': $store.upgrade.currentTier?.code === 'essential',
          'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300': $store.upgrade.currentTier?.code === 'professional',
          'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300': $store.upgrade.currentTier?.code === 'business',
          'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-300': $store.upgrade.currentTier?.code === 'enterprise'
      }"
      x-text="$store.upgrade.currentTier?.name">
</span>
{% endmacro %}


{# =============================================================================
   Quick Upgrade Link
   Simple upgrade link that appears when limits are reached
   ============================================================================= #}
{% macro quick_upgrade_link() %}
<a x-data
   x-init="$store.upgrade.loadUsage()"
   x-show="$store.upgrade.hasLimitsReached && $store.upgrade.nextTier"
   x-cloak
   :href="$store.upgrade.getBillingUrl()"
   class="inline-flex items-center text-sm text-purple-600 dark:text-purple-400 hover:text-purple-800 dark:hover:text-purple-300">
    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/>
    </svg>
    <span>Upgrade to <span x-text="$store.upgrade.nextTier?.name"></span></span>
</a>
{% endmacro %}


{# =============================================================================
   Onboarding Banner
   Shows a checklist of post-signup onboarding steps from all enabled modules.
   Steps are fetched from the API, dismiss is session-scoped (sessionStorage).

   Usage:
   {{ onboarding_banner() }}
   ============================================================================= #}
{% macro onboarding_banner() %}
<div x-data="onboardingBanner()"
     x-show="visible"
     x-cloak
     class="mb-4 bg-white dark:bg-gray-800 rounded-lg shadow-xs border border-gray-200 dark:border-gray-700 overflow-hidden">
    {# Header with progress #}
    <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
                <span x-html="$icon('rocket', 'w-5 h-5 text-purple-600 dark:text-purple-400')"></span>
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">{{ _("onboarding.banner.title") }}</h3>
                <span class="text-sm text-gray-500 dark:text-gray-400"
                      x-text="`${completedSteps}/${totalSteps}`"></span>
            </div>
            <button @click="dismiss()"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                    title="{{ _("onboarding.banner.dismiss") }}">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
        {# Progress bar #}
        <div class="mt-3 w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
            <div class="bg-purple-600 h-2 rounded-full transition-all duration-500"
                 :style="`width: ${progressPercentage}%`"></div>
        </div>
    </div>

    {# Non-owner message #}
    <template x-if="!isOwner">
        <div class="px-6 py-4 text-center">
            <p class="text-sm text-gray-600 dark:text-gray-400">
                <span x-html="$icon('information-circle', 'inline w-5 h-5 mr-1 text-gray-400')"></span>
                Contact your administrator to complete platform setup.
            </p>
        </div>
    </template>

    {# Step checklist (owners only) #}
    <template x-if="isOwner">
        <div class="divide-y divide-gray-100 dark:divide-gray-700">
            <template x-for="step in steps" :key="step.key">
                <a :href="step.route"
                   class="flex items-center px-6 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors group">
                    {# Completion indicator #}
                    <div class="flex-shrink-0 mr-4">
                        <template x-if="step.completed">
                            <div class="w-6 h-6 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center">
                                <svg class="w-4 h-4 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                </svg>
                            </div>
                        </template>
                        <template x-if="!step.completed">
                            <div class="w-6 h-6 rounded-full border-2 border-gray-300 dark:border-gray-600 group-hover:border-purple-400 transition-colors"></div>
                        </template>
                    </div>
                    {# Step icon + text #}
                    <div class="flex-shrink-0 mr-3">
                        <span x-html="$icon(step.icon, 'w-5 h-5 text-gray-400 dark:text-gray-500')" class="block"></span>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-medium text-gray-900 dark:text-white"
                           :class="{ 'line-through text-gray-400 dark:text-gray-500': step.completed }"
                           x-text="t(step.title_key)"></p>
                        <p class="text-xs text-gray-500 dark:text-gray-400 truncate"
                           x-text="t(step.description_key)"></p>
                    </div>
                    {# Arrow #}
                    <template x-if="!step.completed">
                        <svg class="w-4 h-4 text-gray-400 group-hover:text-purple-500 transition-colors flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                        </svg>
                    </template>
                </a>
            </template>
        </div>
    </template>
</div>
{% endmacro %}


{# =============================================================================
   Email Settings Warning
   Shows warning banner when store email settings are not configured.
   This banner appears at the top of store pages until email is configured.

   Usage:
   {{ email_settings_warning() }}
   ============================================================================= #}
{% macro email_settings_warning() %}
<div x-data="emailSettingsWarning()"
     x-show="showWarning"
     x-cloak
     class="mb-4 p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
    <div class="flex items-center justify-between">
        <div class="flex items-center">
            <svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400 mr-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
            </svg>
            <div>
                <p class="font-medium text-yellow-800 dark:text-yellow-300">Email not configured</p>
                <p class="text-sm text-yellow-700 dark:text-yellow-400">
                    Configure your email settings to send order confirmations and customer notifications.
                </p>
            </div>
        </div>
        <a :href="`/store/${storeCode}/settings?tab=email`"
           class="ml-4 px-4 py-2 text-sm font-medium text-yellow-800 bg-yellow-200 rounded-lg hover:bg-yellow-300 dark:bg-yellow-800 dark:text-yellow-200 dark:hover:bg-yellow-700 whitespace-nowrap">
            Configure Email
        </a>
    </div>
</div>
{% endmacro %}
