<script setup>
import { onMounted, ref } from 'vue';
import { usePosStore } from '../../stores/pos';
import PosHistoryCard from './PosHistoryCard.vue';

const props = defineProps({
    storeHash: {
        type: String,
        required: true
    }
});

const posStore = usePosStore();
const isLoadingMore = ref(false);

onMounted(async () => {
    // Only fetch if empty or if needed (could always fetch for simplicity on mount)
    await posStore.fetchPosSessions(props.storeHash, 1);
});

const loadMore = async () => {
    if (posStore.posSessions.length < posStore.posSessionsCount && !posStore.loading) {
        isLoadingMore.value = true;
        await posStore.fetchPosSessions(props.storeHash, posStore.posSessionsPage + 1);
        isLoadingMore.value = false;
    }
};
</script>

<template>
    <div class="pos-history-list position-relative mt-2">
        <div v-if="posStore.loading && posStore.posSessions.length === 0" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2 text-muted small">Loading POS history...</p>
        </div>

        <div v-else-if="posStore.posSessions.length === 0" class="text-center py-5 bg-light rounded-4 border border-dashed">
            <div class="empty-state-icon mb-3 opacity-2">
                <i class="fad fa-receipt fa-4x text-muted"></i>
            </div>
            <p class="text-muted small">No POS history found for this store.</p>
        </div>

        <div v-else>
            <div class="history-items">
                <div v-for="session in posStore.posSessions" :key="session.hashkey">
                    <PosHistoryCard :session="session" />
                </div>
            </div>

            <div v-if="posStore.posSessions.length < posStore.posSessionsCount" class="text-center mt-4">
                <button 
                    @click="loadMore" 
                    class="btn btn-outline-primary btn-sm rounded-pill px-4 py-2 d-inline-flex align-items-center fw-bold"
                    :disabled="isLoadingMore || posStore.loading"
                >
                    <span v-if="isLoadingMore || posStore.loading" class="spinner-border spinner-border-sm me-2" role="status"></span>
                    <i v-else class="fas fa-plus me-2"></i>
                    {{ isLoadingMore || posStore.loading ? 'LOADING...' : 'LOAD MORE' }}
                </button>
            </div>
        </div>
    </div>
</template>

<style scoped>
.empty-state-icon {
    transition: opacity 0.3s ease;
}

.opacity-2 {
    opacity: 0.2;
}

.pos-history-list {
    min-height: 100px;
}

.bg-light {
    background-color: var(--bg-secondary) !important;
}

.border-dashed {
    border-style: dashed !important;
    border-width: 2px !important;
}

:global(.dark-mode) .bg-light {
    background-color: rgba(0,0,0,0.2) !important;
}
</style>
