{% load i18n unfold arith %}

{% with gross=revenue_gross_30|default:0 returns=returns_30|default:0 %}
    {% with total=gross|add:returns %}
        {% component "unfold/components/card.html" with class="xl:col-span-2" %}
            {% component "unfold/components/title.html" %}
                {% trans "Income overview" %}
            {% endcomponent %}

            {% with net=revenue_net_30|default:0 %}
                {% with tax_amt=gross|sub:net %}
                    {% with returns_capped=returns %}
                        {% if returns > gross %}
                            {% with returns_capped=gross %}{% endwith %}
                        {% endif %}
                        {% with tax_amt_pos=tax_amt %}
                            {% if tax_amt_pos < 0 %}
                                {% with tax_amt_pos=0 %}{% endwith %}
                            {% endif %}
                            {% with net_for_pie=gross|sub:tax_amt_pos|sub:returns_capped %}
                                {% if net_for_pie < 0 %}
                                    {% with net_for_pie=0 %}{% endwith %}
                                {% endif %}
                                <div class="flex flex-col sm:flex-row items-center gap-6">
                                    <div class="relative w-48 h-48">
                                        <canvas id="incomePieChart" width="192" height="192"></canvas>
                                    </div>
                                    <div>
                                        <div class="flex items-center gap-2 mb-2">
                                            <span class="inline-block w-3 h-3 rounded-sm" style="background:rgb(34,197,94)"></span>
                                            <span class="text-sm text-gray-600 dark:text-gray-300">{% trans "Net" %}:</span>
                                            <span class="font-semibold">{% if currency_symbol %}{{ currency_symbol }}{% endif %}{{ net }}</span>
                                        </div>
                                        {% if tax_amt_pos > 0 %}
                                            <div class="flex items-center gap-2 mb-2">
                                                <span class="inline-block w-3 h-3 rounded-sm" style="background:rgb(249,115,22)"></span>
                                                <span class="text-sm text-gray-600 dark:text-gray-300">{% trans "Taxes" %}:</span>
                                                <span class="font-semibold">{% if currency_symbol %}{{ currency_symbol }}{% endif %}{{ tax_amt_pos|floatformat:2 }}</span>
                                            </div>
                                        {% endif %}
                                        <div class="flex items-center gap-2 mb-2">
                                            <span class="inline-block w-3 h-3 rounded-sm" style="background:rgb(239,68,68)"></span>
                                            <span class="text-sm text-gray-600 dark:text-gray-300">{% trans "Returns" %}:</span>
                                            <span class="font-semibold">{% if currency_symbol %}{{ currency_symbol }}{% endif %}{{ returns }}</span>
                                        </div>
                                        <div class="flex items-center gap-2">
                                            <span class="inline-block w-3 h-3 rounded-sm" style="background:linear-gradient(90deg, rgba(0,0,0,0.15), rgba(0,0,0,0.15))"></span>
                                            <span class="text-sm text-gray-600 dark:text-gray-300">{% trans "Gross (pie total)" %}:</span>
                                            <span class="font-semibold">{% if currency_symbol %}{{ currency_symbol }}{% endif %}{{ gross }}</span>
                                        </div>
                                    </div>
                                </div>
                                <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
                                <script>
                                    (function () {
                                        try {
                                            const ctx = document.getElementById('incomePieChart').getContext('2d');
                                            const gross = Number({{ gross|default:0 }});
                                            const netBackend = Number({{ net|default:0 }});
                                            const returnsRaw = Number({{ returns_capped|default:0 }});
                                            const taxes = Math.max(gross - netBackend, 0);
                                            const returnsVal = Math.min(returnsRaw, gross);
                                            const netVal = Math.max(gross - taxes - returnsVal, 0);

                                            let dataValues = [netVal, taxes, returnsVal];
                                            let labels = ['{{ _("Net") }}', '{{ _("Taxes") }}', '{{ _("Returns") }}'];
                                            let colors = ['rgb(34,197,94)', 'rgb(249,115,22)', 'rgb(239,68,68)'];

                                            const sum = dataValues.reduce((a, b) => a + Number(b || 0), 0);
                                            if (sum <= 0) {
                                                dataValues = [1];
                                                labels = ['{{ _("No data") }}'];
                                                colors = ['rgba(0,0,0,0.1)'];
                                            }

                                            const currency = "{% if currency_symbol %}{{ currency_symbol }}{% endif %}";
                                            new Chart(ctx, {
                                                type: 'doughnut',
                                                data: {
                                                    labels: labels,
                                                    datasets: [{
                                                        data: dataValues,
                                                        backgroundColor: colors,
                                                        borderWidth: 0,
                                                    }]
                                                },
                                                options: {
                                                    responsive: true,
                                                    maintainAspectRatio: false,
                                                    plugins: {
                                                        legend: {position: 'bottom'},
                                                        tooltip: {
                                                            callbacks: {
                                                                label: function (context) {
                                                                    const label = context.label || '';
                                                                    const val = context.parsed || 0;
                                                                    if (labels.length === 1) return label;
                                                                    return `${label}: ${currency}${val}`;
                                                                }
                                                            }
                                                        }
                                                    },
                                                    cutout: '55%'
                                                }
                                            });
                                        } catch (e) {
                                            console && console.warn && console.warn('Pie chart init failed', e);
                                        }
                                    })();
                                </script>
                            {% endwith %}
                        {% endwith %}
                    {% endwith %}
                {% endwith %}
            {% endwith %}
        {% endcomponent %}
    {% endwith %}
{% endwith %}
