<script lang="ts">
import { onMount } from 'svelte';
import { RefreshCw } from '@lucide/svelte';
import { core_func } from '$lib/ae_core/ae_core_functions';

let status: string[] = $state([]);
let done = $state(false);
let has_error = $state(false);
const RELOAD_DELAY_S = 11;
let countdown = $state(RELOAD_DELAY_S);
const origin = typeof window !== 'undefined' ? window.location.origin : '';

function log(msg: string) {
    status = [...status, `${new Date().toLocaleTimeString()} - ${msg}`];
    console.log(`[FIX-SW] ${msg}`);
}

async function nuke_everything() {
    await core_func.clear_all_storage((msg, level) => {
        if (level === 'error') has_error = true;
        const prefix = level === 'ok' ? '✓ ' : level === 'warn' ? '⚠ ' : '';
        log(prefix + msg);
    });

    log(`─── Reset complete. Reloading in ${RELOAD_DELAY_S} seconds... ───`);
    done = true;

    const tick = setInterval(() => {
        countdown -= 1;
        if (countdown <= 0) clearInterval(tick);
    }, 1000);

    await new Promise((r) => setTimeout(r, RELOAD_DELAY_S * 1000));
    window.location.href = '/';
}

onMount(() => {
    nuke_everything();
});
</script>

<div class="mx-auto max-w-2xl p-8 font-mono">
    <h1 class="mb-2 text-2xl font-bold text-red-600">Full Storage Reset</h1>
    <p class="mb-1 text-sm text-gray-700">
        Clears cached data <strong>for this site only</strong>
        (<span class="font-semibold text-gray-900">{origin}</span>):
        service workers, SW cache, IndexedDB, localStorage, and sessionStorage — then reloads.
    </p>
    <p class="mb-4 text-sm text-gray-500">
        This does <strong>not</strong> affect any other sites or your browser history, passwords,
        or settings. Use this if you are stuck on an old version of the app and nothing else has
        worked.
    </p>

    <div
        class="min-h-60 rounded border border-gray-300 bg-gray-950 p-4 text-green-400 text-sm">
        {#each status as line, i (i)}
            <div
                class="py-0.5 {line.includes('ERROR')
                    ? 'text-red-400'
                    : line.includes('⚠')
                      ? 'text-yellow-400'
                      : ''}">
                {line}
            </div>
        {/each}
        {#if !done}
            <div class="mt-2 animate-pulse text-gray-500">Working...</div>
        {/if}
    </div>

    {#if done}
        <div class="mt-4 flex items-center gap-4">
            <p class="text-sm {has_error ? 'text-yellow-600' : 'text-green-700'} font-semibold">
                {has_error
                    ? 'Reset finished with some errors. Reloading...'
                    : 'Reset complete! Reloading to home page...'}
            </p>
            <button
                class="ml-auto flex items-center gap-2 rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
                onclick={() => (window.location.href = '/')}>
                <RefreshCw size={14} />
                Reload Now ({countdown}s)
            </button>
        </div>
    {/if}
</div>
