{#
  Optional Libraries with CDN Fallback
  =====================================
  Include these blocks in pages that need Chart.js or Flatpickr.

  Usage in a page template:
    {% extends "admin/base.html" %}

    {# For Flatpickr CSS (in head) #}
    {% block flatpickr_css %}
      {% include 'shared/includes/optional-libs.html' with context %}
      {{ flatpickr_css_loader() }}
    {% endblock %}

    {# For Chart.js #}
    {% block chartjs_script %}
      {% include 'shared/includes/optional-libs.html' with context %}
      {{ chartjs_loader() }}
    {% endblock %}

    {# For Flatpickr JS #}
    {% block flatpickr_script %}
      {% include 'shared/includes/optional-libs.html' with context %}
      {{ flatpickr_loader() }}
    {% endblock %}
#}


{#
  Chart.js Loader with CDN Fallback
  =================================
  Loads Chart.js from CDN, falls back to local copy if CDN fails.
#}
{% macro chartjs_loader() %}
<script>
(function() {
    var script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js';

    script.onerror = function() {
        console.warn('Chart.js CDN failed, loading local copy...');
        var fallbackScript = document.createElement('script');
        fallbackScript.src = '{{ url_for("static", path="shared/js/lib/chart.umd.min.js") }}';
        document.head.appendChild(fallbackScript);
    };

    document.head.appendChild(script);
})();
</script>
{% endmacro %}


{#
  Flatpickr CSS Loader with CDN Fallback
  ======================================
  Loads Flatpickr CSS from CDN, falls back to local copy if CDN fails.
#}
{% macro flatpickr_css_loader() %}
<link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css"
    onerror="this.onerror=null; this.href='{{ url_for('static', path='shared/css/store/flatpickr.min.css') }}';"
/>
{% endmacro %}


{#
  Flatpickr JS Loader with CDN Fallback
  =====================================
  Loads Flatpickr JS from CDN, falls back to local copy if CDN fails.
#}
{% macro flatpickr_loader() %}
<script>
(function() {
    var script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js';

    script.onerror = function() {
        console.warn('Flatpickr CDN failed, loading local copy...');
        var fallbackScript = document.createElement('script');
        fallbackScript.src = '{{ url_for("static", path="shared/js/lib/flatpickr.min.js") }}';
        document.head.appendChild(fallbackScript);
    };

    document.head.appendChild(script);
})();
</script>
{% endmacro %}


{#
  Combined Loaders
  ================
  Convenience macros to load multiple libraries at once.
#}

{# Load Chart.js + Flatpickr together #}
{% macro all_optional_libs_css() %}
{{ flatpickr_css_loader() }}
{% endmacro %}

{% macro all_optional_libs_js() %}
{{ chartjs_loader() }}
{{ flatpickr_loader() }}
{% endmacro %}
