/* Shared helpers + reusable UI components ---------------------------------- */
window.fmt = {
    money: function (n) { if (n == null || n === '') return '—'; return new Intl.NumberFormat('az-AZ').format(n) + ' ₼'; },
    date: function (d) {
        if (!d) return '—';
        var x = new Date(d); if (isNaN(x)) return d;
        return x.toLocaleDateString('az-AZ', { day: '2-digit', month: '2-digit', year: 'numeric' });
    },
    days: function (n) {
        if (n == null) return '';
        if (n < 0) return Math.abs(n) + ' gün gecikmə';
        if (n === 0) return 'Bu gün';
        return n + ' gün qalıb';
    }
};

/* Coloured status chip. */
Vue.component('status-pill', {
    props: { text: String, tone: { type: String, default: '' }, dot: Boolean },
    template:
        '<span class="pill" :class="[tone ? \'pill--\'+tone : \'\', dot ? \'pill--dot\' : \'\']">{{ text }}</span>'
});

/* Empty state. */
Vue.component('ui-empty', {
    props: { icon: { type: String, default: 'fa-light fa-inbox' }, title: String, hint: String },
    template:
        '<div class="empty"><i :class="icon"></i><p>{{ title }}</p><small v-if="hint">{{ hint }}</small></div>'
});

/* Skeleton loading list. */
Vue.component('ui-skeleton-list', {
    props: { rows: { type: Number, default: 6 } },
    template:
        '<div><div v-for="n in rows" :key="n" class="skel skel-item"></div></div>'
});

/* Auto load-more: emits "load" when its sentinel scrolls into view. */
Vue.component('infinite-loader', {
    props: { hasMore: Boolean, loading: Boolean, loaded: Number, total: Number },
    mounted: function () {
        var self = this;
        if (!('IntersectionObserver' in window)) return;
        this._io = new IntersectionObserver(function (entries) {
            if (entries[0].isIntersecting && self.hasMore && !self.loading) self.$emit('load');
        }, { rootMargin: '300px' });
        this._io.observe(this.$refs.sentinel);
    },
    beforeDestroy: function () { if (this._io) this._io.disconnect(); },
    template:
        '<div class="infinite" ref="sentinel">' +
        '<div v-if="loading" class="infinite__spin"><i class="fa-light fa-spinner fa-spin"></i> Yüklənir...</div>' +
        '<button v-else-if="hasMore" class="btn btn--outline btn--sm" @click="$emit(\'load\')">Daha çox ({{ loaded }}/{{ total }})</button>' +
        '<div v-else-if="total" class="infinite__end">Hamısı yükləndi · {{ total }}</div>' +
        '</div>'
});

/* Mixin: paginated list loading with load-more + pull-to-refresh support. */
window.ListMixin = {
    data: function () {
        return { items: [], total: 0, loading: false, loadingMore: false, error: null, skip: 0, take: 25, query: {}, _lastKey: null };
    },
    computed: {
        hasMore: function () { return this.items.length < this.total; }
    },
    mounted: function () {
        var self = this;
        this._onRefresh = function () { self.refresh(); };
        window.addEventListener('app:refresh', this._onRefresh);
    },
    beforeDestroy: function () { if (this._onRefresh) window.removeEventListener('app:refresh', this._onRefresh); },
    methods: {
        refresh: function () { if (this._lastKey) return this.fetchList(this._lastKey, true); },
        async fetchList(key, reset) {
            this._lastKey = key;
            if (reset) { this.skip = 0; this.items = []; this.total = 0; }
            var first = this.skip === 0;
            first ? (this.loading = true) : (this.loadingMore = true);
            this.error = null;
            try {
                var res = await window.API.load(key, { skip: this.skip, take: this.take, query: this.query });
                this.items = first ? res.items : this.items.concat(res.items);
                this.total = res.total;
                this.skip = this.items.length;
            } catch (e) {
                this.error = (e && e.message) || 'Yükləmə xətası';
            } finally { this.loading = false; this.loadingMore = false; }
        }
    }
};
