<template>
    <div class="checkoutSectionWrap">
        <h6>Additional Info</h6>
        <div class="row">
            <label for="orderNotes">Notes</label>
            <textarea
                name="order_notes"
                id="orderNotes"
                @input="onInput"
                @keyup="updateCharCount"
                :value="message"
                class="text"
            ></textarea>
            <div class="countdown">
                {{ remainingChars }} characters remaining
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'order-notes',

    props: {
        message: {
            type: String,
            default: ''
        },
        maxLength: {
            type: Number,
            default: 500
        },
        errors: {
            type: Object,
            default: () => ({})
        }
    },

    data() {
        return {
            localMessage: ''
        };
    },

    computed: {
        remainingChars() {
            return this.maxLength - (this.localMessage?.length || 0);
        }
    },

    watch: {
        message: {
            immediate: true,
            handler(newVal) {
                this.localMessage = newVal || '';
            }
        }
    },

    methods: {
        onInput(event) {
            let value = event.target.value;

            // Enforce max length
            if (value.length > this.maxLength) {
                value = value.substring(0, this.maxLength);
                event.target.value = value;
            }

            this.localMessage = value;
            this.$emit('update-message', value);
        },

        updateCharCount() {
            // Character count updates automatically via computed property
        }
    }
};
</script>
