<template>
    <div class="referralRewards" v-if="rewards.length">
        <h3>Your Reward Codes</h3>
        <div class="referralRewardsList">
            <div class="rewardItem" v-for="reward in rewards" :key="reward.code">
                <div class="rewardInfo">
                    <span class="rewardAmount">{{ currencySymbol }}{{ reward.amount }} off</span>
                    <span class="rewardExpiry">Min. spend {{ currencySymbol }}{{ minSpend }}</span>
                </div>
                <div class="rewardCode">
                    <button
                        v-if="!reward.revealed"
                        class="button buttonSmall"
                        @click="reveal(reward)"
                    >
                        Reveal Code
                    </button>
                    <span v-else class="codeDisplay">
                        {{ reward.code }}
                        <button class="buttonLink" @click="copyCode(reward)">
                            {{ reward.copyText }}
                        </button>
                    </span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'referral-rewards',
    props: {
        initialRewards: {
            type: Array,
            default: () => [],
        },
        minSpend: {
            type: [String, Number],
            default: 100,
        },
        currencySymbol: {
            type: String,
            default: '£',
        },
    },
    data() {
        return {
            rewards: this.initialRewards.map(r => ({
                ...r,
                revealed: false,
                copyText: 'Copy',
            })),
        };
    },
    methods: {
        reveal(reward) {
            reward.revealed = true;
        },
        async copyCode(reward) {
            try {
                await navigator.clipboard.writeText(reward.code);
                reward.copyText = 'Copied!';
                setTimeout(() => {
                    reward.copyText = 'Copy';
                }, 2000);
            } catch {
                const el = document.createElement('textarea');
                el.value = reward.code;
                document.body.appendChild(el);
                el.select();
                document.execCommand('copy');
                document.body.removeChild(el);
                reward.copyText = 'Copied!';
                setTimeout(() => {
                    reward.copyText = 'Copy';
                }, 2000);
            }
        },
    },
};
</script>
