<template>
    <div class="referralShare">
        <div class="referralShareLink">
            <h4>Share your referral link</h4>
            <div class="referralLinkCopy">
                <input type="text" :value="referralLink" readonly ref="linkInput" class="text" />
                <button class="button buttonSmall" @click="copyLink">
                    {{ copyText }}
                </button>
            </div>
        </div>

        <div class="referralShareSocial">
            <h4>Share via social media</h4>
            <div class="referralSocialButtons">
                <a :href="whatsappUrl" target="_blank" rel="noopener noreferrer" class="socialButton socialWhatsapp" title="Share on WhatsApp">
                    <i class="fab fa-whatsapp"></i> WhatsApp
                </a>
                <a :href="facebookUrl" target="_blank" rel="noopener noreferrer" class="socialButton socialFacebook" title="Share on Facebook">
                    <i class="fab fa-facebook-f"></i> Facebook
                </a>
                <a :href="twitterUrl" target="_blank" rel="noopener noreferrer" class="socialButton socialTwitter" title="Share on X">
                    <i class="fab fa-x-twitter"></i> X
                </a>
            </div>
        </div>

        <div class="referralShareEmail">
            <h4>Invite by email</h4>
            <form @submit.prevent="sendInvite" class="referralEmailForm">
                <div class="referralEmailInput">
                    <input
                        type="email"
                        v-model="inviteEmail"
                        placeholder="Enter your friend's email"
                        class="text"
                        required
                    />
                    <button type="submit" class="button buttonSmall" :disabled="sending">
                        {{ sending ? 'Sending...' : 'Send Invite' }}
                    </button>
                </div>
                <p v-if="message" :class="['referralMessage', messageType]">{{ message }}</p>
            </form>
        </div>
    </div>
</template>

<script>
export default {
    name: 'referral-share',
    props: {
        referralLink: {
            type: String,
            required: true,
        },
        referralCode: {
            type: String,
            default: '',
        },
        rewardAmount: {
            type: String,
            default: '£5.00',
        },
    },
    data() {
        return {
            inviteEmail: '',
            sending: false,
            message: '',
            messageType: 'success',
            copyText: 'Copy Link',
        };
    },
    computed: {
        shareMessage() {
            return `Check out ${window.globalConfig?.siteName || 'this pharmacy'}! Sign up with my link and we'll both get ${this.rewardAmount} off: ${this.referralLink}`;
        },
        whatsappUrl() {
            return `https://wa.me/?text=${encodeURIComponent(this.shareMessage)}`;
        },
        facebookUrl() {
            return `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(this.referralLink)}`;
        },
        twitterUrl() {
            return `https://twitter.com/intent/tweet?text=${encodeURIComponent(this.shareMessage)}`;
        },
    },
    methods: {
        async copyLink() {
            try {
                await navigator.clipboard.writeText(this.referralLink);
                this.copyText = 'Copied!';
                setTimeout(() => {
                    this.copyText = 'Copy Link';
                }, 2000);
            } catch {
                this.$refs.linkInput.select();
                document.execCommand('copy');
                this.copyText = 'Copied!';
                setTimeout(() => {
                    this.copyText = 'Copy Link';
                }, 2000);
            }
        },
        async sendInvite() {
            if (!this.inviteEmail) {
                return;
            }

            this.sending = true;
            this.message = '';

            try {
                const response = await fetch('/members/referrals/invite', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    body: JSON.stringify({
                        email: this.inviteEmail,
                        channel: 'email',
                    }),
                });

                const data = await response.json();

                if (data.success) {
                    this.message = data.message || 'Invitation sent!';
                    this.messageType = 'success';
                    this.inviteEmail = '';
                } else {
                    this.message = data.message || 'Something went wrong.';
                    this.messageType = 'error';
                }
            } catch {
                this.message = 'Something went wrong. Please try again.';
                this.messageType = 'error';
            } finally {
                this.sending = false;
            }
        },
    },
};
</script>
