<template>
    <div v-loading="loading" class="default-main domain-status-page">
        <section class="setting-grid">
            <div class="panel setting-panel">
                <div class="panel-title">{{ t('embed.domainStatus.settingTitle') }}</div>
                <div class="panel-body setting-form">
                    <div class="form-row">
                        <label>{{ t('embed.domainStatus.headerImage') }}:</label>
                        <el-input v-model="settings.headerImage" placeholder="e.g. https://image.png" />
                    </div>

                    <div class="form-row textarea-row">
                        <label>{{ t('embed.domainStatus.customConfig') }}:</label>
                        <el-input v-model="settings.customConfig" type="textarea" :rows="7" :placeholder="configTemplate" resize="vertical" />
                    </div>
                    <div class="form-row template-row">
                        <label></label>
                        <el-button size="small" @click="settings.customConfig = configTemplate">
                            {{ t('embed.domainStatus.loadTemplate') }}
                        </el-button>
                    </div>

                    <div class="color-grid">
                        <div v-for="item in colorFields" :key="item.key" class="color-item">
                            <label>{{ t(item.label) }}:</label>
                            <el-color-picker v-model="settings[item.key]" />
                            <span>{{ settings[item.key] }}</span>
                        </div>
                    </div>

                    <el-button type="success" class="save-button" :loading="saving" @click="saveSettings">
                        {{ t('embed.domainStatus.save') }}
                    </el-button>
                </div>
            </div>

            <div class="panel embed-panel">
                <div class="panel-title">{{ t('embed.domainStatus.embedCode') }}</div>
                <div class="panel-body">
                    <el-input v-model="embedCode" type="textarea" :rows="17" readonly resize="none" />
                    <el-button class="copy-button" @click="copyEmbedCode">{{ t('embed.domainStatus.copyCode') }}</el-button>
                </div>
            </div>
        </section>

        <section class="panel domain-panel">
            <div class="panel-title">{{ t('embed.domainStatus.domainList') }}</div>
            <div class="domain-list">
                <div v-for="domain in domains" :key="domain.id" class="domain-row">
                    <span class="domain-icon" aria-hidden="true"></span>
                    <span>{{ domain.name }}</span>
                </div>
                <el-empty v-if="domains.length === 0" :description="t('embed.domainStatus.empty')" :image-size="60" />
            </div>
        </section>

        <el-button link type="primary" class="edit-link" @click="editDomainList">
            {{ t('embed.domainStatus.editDomainList') }}
        </el-button>
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { domainStatus, saveDomain } from '/@/api/backend/embed'

defineOptions({
    name: 'embed/domainStatus',
})

interface DomainRow {
    id: number
    name: string
}

interface DomainSetting {
    header_image_url?: string | null
    custom_config?: string | Record<string, unknown> | null
    base_color?: string | null
    border_color?: string | null
    online_color?: string | null
    offline_color?: string | null
    title_color?: string | null
    text_color?: string | null
    tag_color?: string | null
}

type ColorSettingKey = 'baseColor' | 'borderColor' | 'onlineColor' | 'offlineColor' | 'titleColor' | 'textColor' | 'labelColor'

const { t } = useI18n()
const router = useRouter()

const configTemplate = `{
    "hideDomain": [
        "domain1.com",
        "domain2.com"
    ]
}`

const settings = reactive<Record<ColorSettingKey, string> & {
    headerImage: string
    customConfig: string
}>({
    headerImage: '',
    customConfig: '',
    baseColor: '#1c2130',
    borderColor: '#2a3147',
    onlineColor: '#48bb78',
    offlineColor: '#f56565',
    titleColor: '#006dff',
    textColor: '#ffffff',
    labelColor: '#718096',
})

const colorFields: { key: ColorSettingKey; label: string }[] = [
    { key: 'baseColor', label: 'embed.domainStatus.baseColor' },
    { key: 'titleColor', label: 'embed.domainStatus.titleColor' },
    { key: 'borderColor', label: 'embed.domainStatus.borderColor' },
    { key: 'textColor', label: 'embed.domainStatus.textColor' },
    { key: 'onlineColor', label: 'embed.domainStatus.onlineColor' },
    { key: 'labelColor', label: 'embed.domainStatus.labelColor' },
    { key: 'offlineColor', label: 'embed.domainStatus.offlineColor' },
]

const embedCode = ref(`<div style="position: relative;max-width: 1000px;margin: 0 auto;overflow: hidden;border: none;">
    <iframe id="domainstatusIframe" src="https://1xaud.em7bd7.co/embed/domain-status/domain-status.asp" style="width: 100%;overflow: hidden;border: none;"></iframe>
    <script>
        (() => {
            const merchantId = (typeof _ !== "undefined" && typeof _.getVar === "function") ? (_.getVar("merchantId") ?? "") : "";
            if (!merchantId) {
                console.log("merchantId not found");
                return;
            }
            function init(iframe) {
                iframe.addEventListener('load', function() {
                    iframe.contentWindow.postMessage({ type: 'setIframeData', clientMerchant: merchantId }, '*');
                });
                window.addEventListener("message", function(event) {
                    if (event.data && event.data.type === "setDomainStatusIframeHeight") {
                        iframe.style.height = event.data.height + "px";
                    }
                }, false);
            }
            var el = document.getElementById('domainstatusIframe');
            if (el) { init(el); return; }
            var attempts = 0;
            var timer = setInterval(function() {
                attempts++;
                var el = document.getElementById('domainstatusIframe');
                if (el) {
                    clearInterval(timer);
                    init(el);
                } else if (attempts >= 5) {
                    clearInterval(timer);
                    alert("iframe not found");
                }
            }, 1000);
        })();
    <\/script>
</div>`)

const saving = ref(false)

const saveSettings = async () => {
    let customConfig: Record<string, unknown> = {}
    try {
        if (settings.customConfig.trim()) {
            const parsed = JSON.parse(settings.customConfig)
            if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') throw new Error()
            customConfig = parsed
        }
    } catch {
        ElMessage.error(t('embed.domainStatus.invalidConfig'))
        return
    }

    saving.value = true
    try {
        await saveDomain({
            header_image_url: settings.headerImage,
            custom_config: customConfig,
            base_color: settings.baseColor,
            border_color: settings.borderColor,
            online_color: settings.onlineColor,
            offline_color: settings.offlineColor,
            title_color: settings.titleColor,
            text_color: settings.textColor,
            tag_color: settings.labelColor,
        })
        await loadDomainStatus()
    } finally {
        saving.value = false
    }
}

const copyEmbedCode = async () => {
    try {
        await navigator.clipboard.writeText(embedCode.value)
        ElMessage.success(t('embed.domainStatus.copied'))
    } catch {
        ElMessage.error(t('embed.domainStatus.copyFailed'))
    }
}

const domains = ref<DomainRow[]>([])
const loading = ref(false)

const formatCustomConfig = (value: DomainSetting['custom_config']) => {
    if (!value) return ''
    return typeof value === 'string' ? value : JSON.stringify(value, null, 2)
}

const normalizeDomainList = (value: unknown): DomainRow[] => {
    const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\n,;]+/) : []
    return list
        .map((item) => (typeof item === 'object' && item ? String((item as any).domain ?? (item as any).name ?? '') : String(item)))
        .map((name) => name.trim())
        .filter(Boolean)
        .map((name, index) => ({ id: index + 1, name }))
}

const applyDomainSetting = (domain?: DomainSetting) => {
    if (!domain) return
    settings.headerImage = domain.header_image_url ?? ''
    settings.customConfig = formatCustomConfig(domain.custom_config)
    settings.baseColor = domain.base_color ?? ''
    settings.borderColor = domain.border_color ?? ''
    settings.onlineColor = domain.online_color ?? ''
    settings.offlineColor = domain.offline_color ?? ''
    settings.titleColor = domain.title_color ?? ''
    settings.textColor = domain.text_color ?? ''
    settings.labelColor = domain.tag_color ?? ''
}

const loadDomainStatus = async () => {
    loading.value = true
    try {
        const response = await domainStatus()
        const data = response.data ?? response
        applyDomainSetting(data?.domain)
        domains.value = normalizeDomainList(data?.domain_list)
    } finally {
        loading.value = false
    }
}

const editDomainList = () => {
    router.push({ name: 'routine/config' })
}

onMounted(loadDomainStatus)
</script>

<style scoped lang="scss">
.domain-status-page {
    padding: var(--ba-main-space);
    color: var(--el-text-color-primary);
}

.setting-grid {
    display: grid;
    grid-template-columns: minmax(560px, 7fr) minmax(380px, 3fr);
    gap: 14px;
    margin-bottom: 14px;
}

.panel {
    overflow: hidden;
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    background: var(--el-bg-color);
}

.panel-title {
    padding: 10px 14px;
    color: #fff;
    font-size: 14px;
    font-weight: 700;
    background: #333;
}

.panel-body {
    padding: 16px;
}

.setting-form {
    min-height: 410px;
}

.form-row {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;

    > label {
        width: 195px;
        flex: 0 0 195px;
        text-align: right;
        font-weight: 600;
    }

    :deep(.el-input) {
        flex: 1;
    }
}

.textarea-row {
    align-items: flex-start;
}

.template-row {
    margin-top: -2px;
    margin-bottom: 10px;
}

.color-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px 22px;
    margin: 18px 0;
}

.color-item {
    display: flex;
    align-items: center;
    gap: 8px;

    label {
        min-width: 145px;
        text-align: right;
        font-weight: 600;
    }

    span {
        color: var(--el-text-color-secondary);
        font-family: monospace;
        font-size: 12px;
    }
}

.save-button {
    width: calc(100% - 207px);
    margin-left: 207px;
    font-weight: 700;
}

.embed-panel {
    :deep(textarea) {
        padding: 14px;
        color: var(--el-text-color-primary);
        background: var(--el-fill-color-light);
        font-family: monospace;
        font-size: 12px;
        line-height: 1.55;
    }
}

.copy-button {
    width: 100%;
    margin-top: 12px;
}

.domain-list {
    min-height: 44px;
}

.domain-row {
    display: flex;
    align-items: center;
    gap: 9px;
    min-height: 44px;
    padding: 0 14px;
    border-bottom: 1px solid var(--el-border-color-lighter);

    &:last-child {
        border-bottom: 0;
    }
}

.domain-icon {
    position: relative;
    width: 16px;
    height: 16px;
    flex: 0 0 16px;
    border: 1.5px solid var(--el-text-color-secondary);
    border-radius: 50%;

    &::before,
    &::after {
        position: absolute;
        content: '';
    }

    &::before {
        top: 2px;
        bottom: 2px;
        left: 4px;
        right: 4px;
        border-right: 1px solid var(--el-text-color-secondary);
        border-left: 1px solid var(--el-text-color-secondary);
        border-radius: 50%;
    }

    &::after {
        top: 7px;
        right: 1px;
        left: 1px;
        border-top: 1px solid var(--el-text-color-secondary);
    }
}

.edit-link {
    margin-top: 10px;
    padding-left: 0;
}

.domain-editor {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.domain-edit-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr) auto auto;
    align-items: center;
    gap: 12px;
}

.add-domain-button {
    width: 100%;
}

@media (max-width: 1100px) {
    .setting-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 720px) {
    .domain-status-page {
        padding: 12px;
    }

    .form-row {
        align-items: stretch;
        flex-direction: column;
        gap: 6px;

        > label {
            width: auto;
            flex-basis: auto;
            text-align: left;
        }
    }

    .color-grid {
        grid-template-columns: 1fr;
    }

    .color-item label {
        min-width: 130px;
        text-align: left;
    }

    .save-button {
        width: 100%;
        margin-left: 0;
    }

    .domain-edit-row {
        grid-template-columns: 1fr;
    }
}
</style>
