<template>
    <div class="safeguard-controls">
        <button v-for="control in recognisedControls"
                :key="control"
                type="button"
                :class="[
                    `safeguard-${control}`,
                    'interact-ui',
                    { 'classification-valid': control === 'accept' && canAccept }
                ]"
                :disabled="isDisabled(control)"
                :aria-label="ariaLabels[control]"
                @click="handleClick(control)">
            {{ labels[control] }}
        </button>
    </div>
</template>

<script setup>
    import { ref, computed, watch } from 'vue'

    const componentName = 'ot-continuity-safeguard-controls'
    const componentVersion = 'v1.0.0'
    const interfaceVersion = componentVersion

    const RECOGNISED_TYPES = ['accept', 'cancel', 'reset', 'skip', 'defer', 'delegate']

    const props = defineProps({
        controls: {
            type: Array,
            required: false,
            default: () => ['accept', 'cancel']
        },
        prop_state: {
            type: Object,
            required: false,
            default: null
        },
        onAccept: {
            type: Function,
            required: false,
            default: () => {}
        },
        onCancel: {
            type: Function,
            required: false,
            default: () => {}
        },
        onReset: {
            type: Function,
            required: false,
            default: null
        },
        onSkip: {
            type: Function,
            required: false,
            default: null
        },
        onDefer: {
            type: Function,
            required: false,
            default: null
        },
        onDelegate: {
            type: Function,
            required: false,
            default: null
        },
        validate: {
            type: Function,
            required: false,
            default: null
        },
        sourceData: {
            type: Object,
            required: false,
            default: null
        }
    })

    // Resolve props with fallback to prop_state.props for overlay forwarding.
    // The overlay spreads prop_state.props as individual props, but runtime
    // SFC compilation can lose the binding in some cases. This ensures
    // controls always resolve from whichever source has them.
    const resolvedControls = computed(() => {
        // 1. Try prop_state.props.controls first (most reliable path from overlay)
        const fromState = props.prop_state?.props?.controls
        if (Array.isArray(fromState) && fromState.length > 0) {
            return fromState
        }
        // 2. Fall back to direct prop (works when overlay spread succeeds)
        return props.controls
    })
    const resolvedOnAccept = computed(() => props.prop_state?.props?.onAccept || props.onAccept)
    const resolvedOnCancel = computed(() => props.prop_state?.props?.onCancel || props.onCancel)
    const resolvedOnReset = computed(() => props.prop_state?.props?.onReset || props.onReset || null)
    const resolvedOnSkip = computed(() => props.prop_state?.props?.onSkip || props.onSkip || null)
    const resolvedOnDefer = computed(() => props.prop_state?.props?.onDefer || props.onDefer || null)
    const resolvedValidate = computed(() => props.prop_state?.props?.validate || props.validate || null)
    const resolvedSourceData = computed(() => props.prop_state?.props?.sourceData || props.sourceData || null)

    const labels = {
        accept: 'Accept',
        cancel: 'Cancel',
        reset: 'Reset',
        skip: 'Skip',
        defer: 'Decide Later',
        delegate: 'Delegate'
    }

    const ariaLabels = {
        accept: 'Accept and submit',
        cancel: 'Cancel and dismiss',
        reset: 'Reset form to initial values',
        skip: 'Skip this form and continue',
        defer: 'Decide later and return to this form',
        delegate: 'Delegate this form to another actor'
    }

    // Filter unrecognised control types (REQ-1.1)
    const recognisedControls = computed(() =>
        resolvedControls.value.filter(c => RECOGNISED_TYPES.includes(c))
    )

    const canAccept = ref(false)

    function runValidation() {
        const validateFn = resolvedValidate.value
        if (typeof validateFn === 'function') {
            canAccept.value = validateFn()
        } else {
            canAccept.value = true
        }
    }

    // Run validation on mount
    runValidation()

    // Re-run validation when sourceData changes
    watch(
        () => resolvedSourceData.value,
        () => { runValidation() },
        { deep: true }
    )

    // Register sync callback on sourceData so ATLAS onReset can trigger
    // validation re-evaluation after restoring properties.
    const srcData = resolvedSourceData.value
    if (srcData) {
        srcData.__onResetControlsSync = () => { runValidation() }
    }

    function isDisabled(control) {
        if (control === 'accept') return !canAccept.value
        if (control === 'delegate') return true // non-functional placeholder (REQ-9.6)
        return false // reset, skip, defer, cancel are always enabled
    }

    function handleClick(control) {
        if (control === 'accept') {
            if (!canAccept.value) return
            console.log('[TRACE-REQUEST][controls] Accept clicked')
            resolvedOnAccept.value()
        } else if (control === 'cancel') {
            const srcData = resolvedSourceData.value
            if (typeof srcData?.__cancelOverride === 'function') {
                srcData.__cancelOverride()
            } else {
                resolvedOnCancel.value()
            }
        } else if (control === 'reset' && typeof resolvedOnReset.value === 'function') {
            resolvedOnReset.value()
            // Force validation re-run after ATLAS restores sourceData
            // Use nextTick to ensure sourceData mutations are complete
            Promise.resolve().then(() => { runValidation() })
        } else if (control === 'skip' && typeof resolvedOnSkip.value === 'function') {
            resolvedOnSkip.value()
        } else if (control === 'defer' && typeof resolvedOnDefer.value === 'function') {
            resolvedOnDefer.value()
        }
        // delegate: no action (REQ-9.7)
    }

    defineExpose({
        componentName,
        componentVersion,
        interfaceVersion,
        canAccept
    })
</script>

<style scoped>
.safeguard-controls {
    display: flex;
    gap: 0.5rem;
    padding: 0.75rem 0;
    flex-wrap: wrap;
}

.safeguard-controls button {
    padding: 0.5rem 1rem;
    border: 1px solid #d0d0d0;
    border-radius: 0.35rem;
    background: #f5f5f5;
    cursor: pointer;
    font: inherit;
    font-size: 0.85rem;
    font-weight: 500;
    color: #333;
    transition: background 0.15s, border-color 0.15s, box-shadow 0.15s;
}

.safeguard-controls button:hover {
    background: #e8e8e8;
}

.safeguard-controls button:disabled {
    opacity: 0.3;
    cursor: not-allowed;
    background: transparent;
}

.safeguard-controls button.safeguard-accept {
    border-color: #a5d6a7;
    background: #e8f5e9;
    color: #2e7d32;
}

.safeguard-controls button.safeguard-accept:hover {
    background: #c8e6c9;
}

.safeguard-controls button.safeguard-accept.classification-valid {
    border-color: #388e3c;
    background: #388e3c;
    color: #ffffff;
    box-shadow: 0 0 0 2px rgba(56,142,60,0.2);
}

.safeguard-controls button.safeguard-accept.classification-valid:hover {
    background: #2e7d32;
    border-color: #2e7d32;
}

.safeguard-controls button.safeguard-cancel {
    border-color: #ef9a9a;
    background: #ffebee;
    color: #c62828;
}

.safeguard-controls button.safeguard-cancel:hover {
    background: #ffcdd2;
}

.safeguard-controls button.safeguard-reset {
    border-color: #90caf9;
    background: #e3f2fd;
    color: #1565c0;
}

.safeguard-controls button.safeguard-reset:hover {
    background: #bbdefb;
}

.safeguard-controls button.safeguard-skip {
    border-color: #ffe082;
    background: #fff8e1;
    color: #f57f17;
}

.safeguard-controls button.safeguard-skip:hover {
    background: #fff3c4;
}

.safeguard-controls button.safeguard-defer {
    border-color: #b39ddb;
    background: #f3e5f5;
    color: #7b1fa2;
}

.safeguard-controls button.safeguard-defer:hover {
    background: #e1bee7;
}

.safeguard-controls button.safeguard-delegate {
    border-color: #b0bec5;
    background: #eceff1;
    color: #546e7a;
}
</style>
