<script setup>
/*
 * MelissaSettingsPanel — popover "Personalizar" do MelissaLayout
 * --------------------------------------------------------------
 * Painel glass que abre via cog no canto superior direito do
 * Melissa. Concentra:
 *   - Plano de fundo (imagem custom, opacidades, voltar ao default)
 *   - Relogio & Som (formato 24h, toque de termino + botao testar)
 *   - Tema (modo escuro, preset Lara/Nora, cor primaria, surface)
 *
 * Estado e setters chegam via inject('melissaSettings') — mesma
 * fonte usada por MelissaConfiguracoes (sem duplicar refs). Isso
 * mantem persistencia (localStorage + DB) centralizada no pai.
 *
 * Estado local:
 *   - fileInput (template ref) + pickFile() — pura cola de DOM
 *
 * Emit:
 *   - close — botao X clicado
 */
import { inject, ref, computed } from 'vue';
import { TOQUES } from './melissaToques';
import { MELISSA_THEMES } from './melissaThemes';

const emit = defineEmits(['close']);

const settings = inject('melissaSettings', null);
if (!settings) {
    // Fallback defensivo: nunca deveria acontecer (so se montarem
    // este componente fora do MelissaLayout). Loga e segue com noop.
    // eslint-disable-next-line no-console
    console.warn('[MelissaSettingsPanel] inject melissaSettings ausente — montagem fora do MelissaLayout?');
}

const {
    layoutConfig,
    isDarkTheme,
    activeSurface,
    PRIMARY_COLORS,
    SURFACES,
    PRESETS,
    setPrimary,
    setSurface,
    setPreset,
    setDark,
    bgUrl,
    overlayOpacity,
    bgImageOpacity,
    onFileChange,
    clearBg,
    use24h,
    toqueTermino,
    testarToque,
    themeName,
    setThemeName,
    textBgEnabled,
    setTextBgEnabled
} = settings || {};

// Cola de DOM: input <type=file> escondido + trigger via botao "Trocar
// imagem". onFileChange (no pai) faz validacao de tipo/tamanho e ja
// dispara watchers de persistencia em bgUrl.
const fileInput = ref(null);
function pickFile() {
    fileInput.value?.click();
}

// Tema ativo: prioriza themeName persistido (se nao bate com nenhum,
// cai em heuristica primary+preset+surface). Persistimos so o nome
// no DB (melissa_prefs.themeName); na rehidratacao o MelissaLayout
// resolve o nome -> imagem e seta bgUrl.
const activeTheme = computed(() => {
    if (themeName?.value) {
        const persisted = MELISSA_THEMES.find((t) => t.name === themeName.value);
        if (persisted) return persisted.name;
    }
    return MELISSA_THEMES.find((t) =>
        layoutConfig?.primary === t.primary &&
        layoutConfig?.preset === t.preset &&
        layoutConfig?.surface === t.surface
    )?.name || null;
});

async function applyTheme(t) {
    // 1. Persiste o NOME do tema (DB + localStorage). MelissaLayout usa
    //    isso pra restaurar o wallpaper em outro device sem precisar
    //    guardar a data URL gigante no DB.
    setThemeName?.(t.name);

    // 2. Wallpaper na sessao corrente: converte pra data URL pra sobreviver
    //    a reload local (localStorage so aceita data: URLs por seguranca).
    try {
        const res = await fetch(t.image);
        const blob = await res.blob();
        const dataUrl = await new Promise((resolve, reject) => {
            const r = new FileReader();
            r.onload = () => resolve(r.result);
            r.onerror = reject;
            r.readAsDataURL(blob);
        });
        bgUrl.value = dataUrl;
    } catch (e) {
        // eslint-disable-next-line no-console
        console.warn('[Temas] falha ao converter wallpaper em data URL:', e?.message);
        bgUrl.value = t.image; // fallback: URL direta (funciona na sessao)
    }

    // 3. Cor primaria, preset e surface ja persistem direto em colunas
    //    proprias de user_settings via queuePatch.
    setPrimary?.(t.primary);
    setPreset?.(t.preset);
    setSurface?.(t.surface);
}

// Wrappers: ao escolher imagem custom OU voltar ao padrao, o tema
// previamente selecionado deixa de fazer sentido — limpa themeName.
function onCustomFileChange(e) {
    setThemeName?.(null);
    onFileChange?.(e);
}
function onClearBg() {
    setThemeName?.(null);
    clearBg?.();
}
</script>

<template>
    <div class="glass-panel mp-panel absolute bottom-12 right-0 w-72">
        <!-- Cabecalho fixo -->
        <header class="mp-head">
            <div class="mp-head__title">
                <i class="pi pi-sliders-h" />
                <span>Personalizar</span>
            </div>
            <button
                class="mp-head__close"
                title="Fechar"
                aria-label="Fechar"
                @click="emit('close')"
            >
                <i class="pi pi-times" />
            </button>
        </header>

        <!-- Corpo scrollavel -->
        <div class="mp-body">
            <!-- ── Temas (bundle wallpaper + cores) ─────── -->
            <div class="mp-divider"><span>Temas</span></div>
            <div class="mp-themes">
                <button
                    v-for="t in MELISSA_THEMES"
                    :key="t.name"
                    type="button"
                    class="mp-theme"
                    :class="{ 'is-active': activeTheme === t.name }"
                    :title="`Aplicar tema ${t.name}`"
                    :aria-pressed="activeTheme === t.name"
                    @click="applyTheme(t)"
                >
                    <div class="mp-theme__thumb" :style="{ backgroundImage: `url(${t.image})` }" />
                    <span class="mp-theme__name">{{ t.name }}</span>
                </button>
            </div>

            <!-- ── Plano de fundo ──────────────────────── -->
            <div class="mp-divider"><span>Plano de Fundo</span></div>

            <button class="mp-btn mp-btn--primary" @click="pickFile">
                <i class="pi pi-image" />
                <span>Trocar imagem de fundo</span>
            </button>
            <p class="mp-hint">
                Recomendado: 1920×1080 (Full HD), JPG ou PNG. Máximo 2&nbsp;MB.
            </p>
            <button
                v-if="bgUrl"
                class="mp-btn mp-btn--ghost"
                @click="onClearBg"
            >
                <i class="pi pi-refresh" />
                <span>Voltar ao padrão</span>
            </button>
            <input ref="fileInput" type="file" accept="image/*" hidden @change="onCustomFileChange" />

            <div v-if="bgUrl" class="mp-field">
                <label class="mp-label">
                    Transparência da imagem
                    <span class="mp-label__value">{{ Math.round(bgImageOpacity * 100) }}%</span>
                </label>
                <input
                    v-model.number="bgImageOpacity"
                    type="range"
                    min="0.01"
                    max="1"
                    step="0.01"
                    class="settings-range w-full"
                />
            </div>

            <div class="mp-field">
                <label class="mp-label">
                    Opacidade do fundo
                    <span class="mp-label__value">{{ Math.round(overlayOpacity * 100) }}%</span>
                </label>
                <input
                    v-model.number="overlayOpacity"
                    type="range"
                    min="0"
                    max="0.8"
                    step="0.05"
                    class="settings-range w-full"
                />
            </div>

            <!-- Toggle: fundo solido nos textos do hero (relogio/saudacao/resumo).
                 Util quando o wallpaper tem pouca transparencia e o text-shadow
                 nao da legibilidade suficiente. -->
            <div class="mp-row">
                <span class="mp-row__label">
                    Fundo nos textos
                    <span class="mp-row__sub">(relógio &amp; saudação)</span>
                </span>
                <button
                    class="settings-toggle w-10 h-6 rounded-full transition-colors relative"
                    :class="textBgEnabled ? 'is-on' : 'bg-white/20'"
                    :title="textBgEnabled ? 'Remover fundo dos textos' : 'Adicionar fundo aos textos'"
                    @click="setTextBgEnabled(!textBgEnabled)"
                >
                    <span
                        class="absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all"
                        :style="{ left: textBgEnabled ? '1.125rem' : '0.125rem' }"
                    />
                </button>
            </div>

            <!-- ── Relogio & Toques ────────────────────── -->
            <div class="mp-divider"><span>Relógio &amp; Som</span></div>

            <div class="mp-row">
                <span class="mp-row__label">
                    Formato 24h
                    <span class="mp-row__sub">(relógio)</span>
                </span>
                <button
                    class="settings-toggle w-10 h-6 rounded-full transition-colors relative"
                    :class="use24h ? 'is-on' : 'bg-white/20'"
                    @click="use24h = !use24h"
                >
                    <span
                        class="absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all"
                        :style="{ left: use24h ? '1.125rem' : '0.125rem' }"
                    />
                </button>
            </div>

            <div class="mp-field">
                <label class="mp-label">Toque de término</label>
                <div class="flex gap-1.5">
                    <select v-model="toqueTermino" class="settings-select flex-1">
                        <option v-for="t in TOQUES" :key="t.id" :value="t.id">
                            {{ t.label }}
                        </option>
                    </select>
                    <button
                        class="settings-test-btn"
                        title="Testar"
                        :disabled="toqueTermino === 'nenhum'"
                        @click="testarToque"
                    >
                        <i class="pi pi-play text-[0.65rem]" />
                    </button>
                </div>
            </div>

            <!-- ── Tema ────────────────────────────────── -->
            <div class="mp-divider"><span>Tema</span></div>

            <div class="mp-row">
                <span class="mp-row__label">Modo escuro</span>
                <button
                    class="settings-toggle w-10 h-6 rounded-full transition-colors relative"
                    :class="isDarkTheme ? 'is-on' : 'bg-white/20'"
                    :title="isDarkTheme ? 'Mudar pra claro' : 'Mudar pra escuro'"
                    @click="setDark(!isDarkTheme)"
                >
                    <span
                        class="absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all"
                        :style="{ left: isDarkTheme ? '1.125rem' : '0.125rem' }"
                    />
                </button>
            </div>

            <div class="mp-field">
                <label class="mp-label">Preset</label>
                <div class="mp-presets">
                    <button
                        v-for="p in PRESETS"
                        :key="p"
                        type="button"
                        class="mp-preset"
                        :class="{ 'is-active': layoutConfig.preset === p }"
                        @click="setPreset(p)"
                    >{{ p }}</button>
                </div>
            </div>

            <div class="mp-field">
                <label class="mp-label">Cor primária</label>
                <div class="grid grid-cols-9 gap-1.5">
                    <button
                        v-for="pc in PRIMARY_COLORS"
                        :key="pc.name"
                        class="settings-swatch"
                        :class="{ 'is-active': layoutConfig.primary === pc.name }"
                        :style="{ backgroundColor: pc.swatch === 'currentColor' ? 'var(--m-text)' : pc.swatch }"
                        :title="pc.name"
                        @click="setPrimary(pc.name)"
                    />
                </div>
            </div>

            <div class="mp-field">
                <label class="mp-label">Surface</label>
                <div class="grid grid-cols-8 gap-1.5">
                    <button
                        v-for="sf in SURFACES"
                        :key="sf.name"
                        class="settings-swatch"
                        :class="{ 'is-active': activeSurface === sf.name }"
                        :style="{ backgroundColor: sf.palette['500'] }"
                        :title="sf.name"
                        @click="setSurface(sf.name)"
                    />
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
/* glass-panel base — redeclarado aqui porque o do pai esta em
   <style scoped> e nao atravessa o limite do componente. Os
   overrides de light mode (html:not(.app-dark) .win11-root ...)
   estao em <style> nao-scoped do pai e continuam aplicando. */
.glass-panel {
    background: var(--m-bg-soft);
    backdrop-filter: blur(24px) saturate(140%);
    -webkit-backdrop-filter: blur(24px) saturate(140%);
    border: 1px solid var(--m-border);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

/* ─── Painel "Personalizar" (mp-*) ────────────────────────────
   Cores via vars (--m-text, --m-border, etc) pra adaptar light
   e dark — em light o glass-panel ganha fundo claro e texto
   branco hardcoded ficava invisivel.
   Estrutura: header fixo + body scrollavel, secoes separadas
   por .mp-divider (linha + label inline):
   - Plano de Fundo (imagem, opacidades)
   - Relogio & Som (24h, toque)
   - Tema (modo escuro, preset, primaria, surface)
   ─────────────────────────────────────────────────────────── */
.mp-panel {
    display: flex;
    flex-direction: column;
    padding: 0;
    max-height: calc(100vh - 5rem);
    overflow: hidden;
    color: var(--m-text);
}
.mp-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 14px;
    border-bottom: 1px solid var(--m-border);
    flex-shrink: 0;
}
.mp-head__title {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--m-text);
    font-size: 0.82rem;
    font-weight: 600;
    letter-spacing: 0.02em;
}
.mp-head__title > i {
    color: var(--p-primary-color);
    font-size: 0.9rem;
}
.mp-head__close {
    width: 26px;
    height: 26px;
    display: grid;
    place-items: center;
    background: transparent;
    border: 1px solid var(--m-border);
    color: var(--m-text-muted);
    border-radius: 7px;
    cursor: pointer;
    font-size: 0.7rem;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease;
}
.mp-head__close:hover {
    background: var(--m-bg-soft-hover);
    color: var(--m-text);
    border-color: var(--m-border-strong);
}

.mp-body {
    flex: 1;
    overflow-y: auto;
    padding: 12px 14px 16px;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mp-body::-webkit-scrollbar { width: 5px; }
.mp-body::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

/* Divider com label inline — separa secoes do painel */
.mp-divider {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 14px 0 10px;
    color: var(--m-text-muted);
    font-size: 0.62rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.16em;
}
.mp-divider:first-child {
    margin-top: 2px;
}
.mp-divider::before,
.mp-divider::after {
    content: '';
    flex: 1;
    height: 1px;
    background: var(--m-border);
}
.mp-divider > span {
    flex-shrink: 0;
}

/* Botoes do painel */
.mp-btn {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 9px;
    font-size: 0.82rem;
    font-family: inherit;
    cursor: pointer;
    transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease;
    text-align: left;
}
.mp-btn--primary {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    color: var(--m-text);
}
.mp-btn--primary:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mp-btn--ghost {
    background: transparent;
    border: 1px solid transparent;
    color: var(--m-text-muted);
    padding: 6px 12px;
    margin-bottom: 8px;
}
.mp-btn--ghost:hover {
    background: var(--m-bg-soft);
    color: var(--m-text);
}
.mp-btn > i {
    font-size: 0.85rem;
    flex-shrink: 0;
}

/* Hint pequeno abaixo de botao */
.mp-hint {
    font-size: 0.66rem;
    line-height: 1.4;
    color: var(--m-text-faint);
    padding: 0 4px;
    margin: 4px 0 8px;
}

/* Field generico (label + input/range/select abaixo) */
.mp-field {
    margin-bottom: 12px;
}
.mp-label {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: var(--m-text-muted);
    font-size: 0.72rem;
    margin-bottom: 6px;
}
.mp-label__value {
    color: var(--m-text);
    font-variant-numeric: tabular-nums;
    font-size: 0.7rem;
}

/* Row (label esq + controle dir, mesma linha) */
.mp-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    font-size: 0.82rem;
}
.mp-row__label {
    color: var(--m-text);
}
.mp-row__sub {
    color: var(--m-text-faint);
    font-size: 0.7rem;
    margin-left: 4px;
}

/* Preset chips (Aura / Lara / Nora) */
.mp-presets {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}
.mp-preset {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    color: var(--m-text);
    padding: 5px 12px;
    border-radius: 8px;
    font-size: 0.74rem;
    font-family: inherit;
    text-transform: capitalize;
    cursor: pointer;
    transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease;
}
.mp-preset:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mp-preset.is-active {
    background: var(--p-primary-color);
    border-color: var(--p-primary-color);
    color: var(--p-primary-contrast-color, white);
}

/* ─── Settings popover: select + botao testar do toque ────── */
.settings-select {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border-strong);
    color: var(--m-text);
    padding: 7px 10px;
    border-radius: 8px;
    font-size: 0.8rem;
    outline: none;
    appearance: none;
    -webkit-appearance: none;
    cursor: pointer;
    min-width: 0;
}
.settings-select:hover {
    background: var(--m-bg-soft-hover);
}
.settings-select option {
    /* renderizado pelo OS — usa tokens semanticos pra acompanhar dark/light */
    background: var(--p-content-background);
    color: var(--m-text);
}

.settings-test-btn {
    width: 32px;
    height: 32px;
    display: grid;
    place-items: center;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border-strong);
    color: var(--m-text);
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 140ms ease;
}
.settings-test-btn:hover {
    background: var(--m-accent);
    border-color: var(--m-accent);
}
.settings-test-btn:disabled {
    background: var(--m-bg-soft);
    border-color: var(--m-border);
    color: var(--m-text-faint);
    cursor: not-allowed;
}

/* Sliders do painel — accent-color pinta thumb + parte preenchida na
   primary. Sem sobrescrever ::-webkit-slider-track (Chrome desce a thumb
   se a track for estilizada). */
.settings-range {
    accent-color: var(--p-primary-color);
    width: 100%;
}

/* Toggle "ligado" usa a primary do preset escolhido */
.settings-toggle.is-on {
    background-color: var(--p-primary-color);
}

/* Swatches de cor primaria — circulos compactos com ring na ativa */
.settings-swatch {
    width: 22px;
    height: 22px;
    border-radius: 9999px;
    border: 1px solid rgba(255, 255, 255, 0.18);
    cursor: pointer;
    transition: transform 120ms ease, box-shadow 120ms ease;
    padding: 0;
}
.settings-swatch:hover {
    transform: scale(1.12);
}
.settings-swatch.is-active {
    box-shadow:
        0 0 0 2px var(--m-bg-medium),
        0 0 0 4px var(--p-primary-color);
}

/* ─── Temas (cards de wallpaper) ─────────────────────────────
   Grid 3-col com thumb quadrado + label. Click aplica wallpaper
   + cor primaria + preset + surface de uma vez. */
.mp-themes {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    margin-bottom: 12px;
}
.mp-theme {
    display: flex;
    flex-direction: column;
    align-items: stretch;
    gap: 6px;
    padding: 4px;
    background: transparent;
    border: 1px solid transparent;
    border-radius: 9px;
    cursor: pointer;
    transition: border-color 120ms ease, background-color 120ms ease, transform 120ms ease;
    font: inherit;
    color: var(--m-text);
}
.mp-theme:hover {
    background: var(--m-bg-soft-hover, rgba(255, 255, 255, 0.06));
    border-color: var(--m-border);
}
.mp-theme:active { transform: scale(0.97); }
.mp-theme.is-active {
    background: color-mix(in srgb, var(--p-primary-color) 14%, transparent);
    border-color: var(--p-primary-color);
}
.mp-theme__thumb {
    aspect-ratio: 1;
    border-radius: 7px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    border: 1px solid var(--m-border);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.18);
}
.mp-theme.is-active .mp-theme__thumb {
    border-color: var(--p-primary-color);
}
.mp-theme__name {
    font-size: 0.7rem;
    font-weight: 600;
    text-align: center;
    letter-spacing: 0.02em;
    color: var(--m-text);
    line-height: 1;
}
</style>
