<script lang="ts">
    import { onMount } from "svelte";

    let { simName, resourceName } = $props();

    let logContent = $state("");
    let error = $state("");
    let loading = $state(true);

    onMount(async () => {
        try {
            const res = await fetch(`/results/${simName}/${resourceName}`);
            if (!res.ok) throw new Error("Failed to load log file.");
            logContent = await res.text();
        } catch (e: any) {
            error = e.message;
        } finally {
            loading = false;
        }
    });
</script>

<details class="log-viewer">
    <summary>
        <span>Simulation Logs: {resourceName}</span>
        <a
            href={`/results/${simName}/${resourceName}`}
            download
            class="dl-link"
            onclick={(e) => e.stopPropagation()}>[Download]</a
        >
    </summary>
    <div class="log-content">
        {#if loading}
            <p>Loading logs...</p>
        {:else if error}
            <p class="error">{error}</p>
        {:else}
            <pre>{logContent}</pre>
        {/if}
    </div>
</details>

<style>
    .log-viewer {
        margin-top: 20px;
        margin-bottom: 20px;
        border: 1px solid #000;
        background-color: #f9f9f9;
        max-width: 100%;
    }
    summary {
        font-weight: bold;
        padding: 10px;
        cursor: pointer;
        background-color: #e0e0e0;
        border-bottom: 1px solid #000;
        display: flex;
        justify-content: space-between;
    }
    .dl-link {
        font-weight: normal;
        color: #0000ff;
        text-decoration: underline;
    }
    .dl-link:visited {
        color: #800080;
    }
    details:not([open]) summary {
        border-bottom: none;
    }
    .log-content {
        max-height: 400px;
        overflow-y: auto;
        overflow-x: auto;
        padding: 10px;
        background-color: #fff;
    }
    pre {
        margin: 0;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-family: "JetBrains Mono", Courier, monospace;
        font-size: 14px;
    }
    .error {
        color: red;
        font-weight: bold;
    }
</style>
