{% extends "base.html" %}
{% block content %}

<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.5/dist/cdn.min.js" defer></script>

<div class="m-5 p-5 flex justify-center w-auto">
    <!-- Main Card Container -->
    <div x-data="settingsData" x-init="$watch('tab', value => localStorage.setItem('activeTab', value))"
        class="inline-block rounded-xl md:rounded-2xl shadow-xl bg-white/80 dark:bg-gray-800/80">

        <!-- Main Tabs -->
        <div x-cloak
            class="flex overflow-x-auto border-b border-gray-200 dark:border-gray-700 justify-center items-center whitespace-nowrap">

            {% for itab in tabs %}
            <button @click="tab = '{{ itab }}'"
                :class="tab === '{{ itab }}' ? 'border-b-2 border-blue-600 text-blue-600 dark:text-blue-400' : 'text-gray-600 dark:text-gray-300'"
                class="px-4 py-2 text-sm font-medium">
                {{ itab }}
            </button>
            {% endfor %}
        </div>

        <div x-show="tab === 'Posts'" class="space-y-2 md:p-4">
            <div class="overflow-x-auto rounded shadow">
                <table
                    class="min-w-full bg-white dark:bg-gray-700 text-sm text-left text-gray-700 dark:text-white rounded-lg">
                    <thead class="bg-gray-100 dark:bg-gray-900">
                        <tr>
                            <th scope="col" class="px-4 py-3 text-sm font-semibold">Post</th>
                            <th scope="col" class="px-4 py-3 text-sm font-semibold">Details</th>
                            <th scope="col" class="px-4 py-3 text-sm font-semibold">Date</th>
                            <th scope="col" class="px-4 py-3 text-sm font-semibold">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for p in posts %}
                        <tr class="hover:bg-gray-200 dark:hover:bg-gray-400">
                            <td class="px-4 py-2 font-medium text-gray-800 dark:text-gray-200">

                                <a href="{{ url_for('blog.image_detail', image_id=p['id'], image_name=p['slug']) }}"
                                class="block relative">

                                    <!-- Thumbnail -->
                                    <img
                                        src="{{ url_for('blog.upload', filename=p.image_thumbnail|replace('\\', '/') or p.image_path|replace('\\', '/')) }}"
                                        alt="{{ p.title }}"
                                        class="w-full h-48 object-cover">

                                    <!-- Overlay text -->
                                    <h5 class="absolute bottom-0 left-0 w-full text-white text-sm font-semibold px-3 py-2
                                            bg-gradient-to-t from-black/70 to-transparent">
                                        {{ p['title'] }} - {{ p['short_description'] }}
                                    </h5>

                                </a>
                            </td>
                            <td class="px-4 py-2 font-medium text-gray-800 dark:text-gray-200">

                                <div>
                                    Pixel scale: {{ p['pixel_scale'] | round(2)}}″/px
                                </div>

                                <div>
                                    Object type: {{ p['object_type'] }}
                                </div>

                                <div>
                                    Location: {{ p['location'] }}
                                </div>
                            </td>
                            <td class="px-4 py-2 text-gray-600 dark:text-gray-300">
                                {{ p['created_at'].strftime('%Y-%m-%d') }}
                            </td>
                            <td class="px-4 py-2 space-x-2">
                                <a href="{{ url_for('blog.edit_image', image_id=p['id']) }}"
                                    class="inline-block px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded hover:bg-blue-700">
                                    Edit
                                </a>
                                <a href="{{ url_for('blog.delete_image', image_id=p['id']) }}"
                                    class="inline-block px-4 py-2 text-sm font-medium text-white bg-red-600 rounded hover:bg-red-700"
                                    onclick="return confirm('Delete?');">
                                    Delete
                                </a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

<div x-data='{
    inventory: {{ inventory | tojson }},
    dataType: {{ data_type | tojson }},
    inventoryConstraints: {{ inventory_constraints | tojson }},
    selectedType: "",
    selectedName: "",
    currentNames: [],
    currentValues: {},

    updateNames() {
        const namesObj = this.inventory[this.selectedType] || {};
        this.currentNames = Object.keys(namesObj);
        this.selectedName = this.currentNames[0] || "";
        this.updateValues();
    },

    updateValues() {
        this.currentValues = this.inventory[this.selectedType]?.[this.selectedName] || {};
    },

    inputTypeFor(key) {
        const dtype = this.dataType[this.selectedType]?.[key];
        if (key === "id") return "hidden";
        if (!dtype) return "text";
        if (["integer", "numeric", "float", "double"].includes(dtype)) return "number";
        if (["boolean", "bool"].includes(dtype)) return "checkbox";
        if (["text", "varchar", "string"].includes(dtype)) return "text";
        if (["date", "datetime", "timestamp"].includes(dtype)) return "date";
        return "text";
    },

    constraintHintFor(key) {
        const allowed = this.inventoryConstraints[this.selectedType]?.[key];
        if (!allowed || allowed.length === 0) return "";
        return `Allowed values: ${allowed.join(", ")}`;
    },

    constraintOptionsFor(key) {
        return this.inventoryConstraints[this.selectedType]?.[key] || [];
    },

    hasConstraintOptions(key) {
        return this.constraintOptionsFor(key).length > 0;
    },

    async saveInventory() {
        const payload = {
            type: this.selectedType,
            name: this.selectedName,
            values: { ...this.currentValues }
        };

        try {
            const response = await fetch("/private/update_inventory", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRFToken": csrfToken
                },
                body: JSON.stringify(payload)
            });
            const data = await response.json().catch(() => ({}));

            if (response.ok) {
                alert(data.message || "Inventory saved successfully!");
                location.reload(); 
            } else {
                alert(data.message || "Failed to save inventory.");
            }
        } catch (error) {
            console.error(error);
            alert("An error occurred while saving.");
        }
    }
}' x-init="
    selectedType = Object.keys(inventory)[0];
    updateNames();
" x-show="tab === 'Inventory'" class="space-y-2 p-4  text-gray-700 dark:text-white">

            <div class="grid grid-cols-2 gap-4 md:grid-cols-4">
                <!-- Inventory Type Dropdown -->
                <label for="inventoryType" class="flex items-center">
                    Select Inventory Type
                </label>

                <select id="inventoryType" x-model="selectedType" @change="updateNames()"
                    class="p-2 block w-full border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700">
                    {% for item in inventory %}
                    <option value="{{ item }}">{{ item | capitalize }}</option>
                    {% endfor %}
                </select>

                <!-- Item Name Dropdown -->
                <label for="itemName" class="flex items-center">
                    Add/Edit Inventory
                </label>

                <select id="itemName" x-model="selectedName" @change="updateValues()"
                    class="p-2 block w-full border-gray-300 rounded-md shadow-sm bg-gray-100 dark:bg-gray-700">
                    <template x-for="name in currentNames" :key="name">
                        <option :value="name" x-text="name"></option>
                    </template>
                </select>
            </div>

            <!-- Inventory Details Display -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-2 p-2 bg-gray-50 dark:bg-gray-800 mt-4 rounded-lg">
                <div class="md:col-span-2 rounded-md bg-blue-50 px-3 py-2 text-sm text-blue-900 dark:bg-blue-900/30 dark:text-blue-100">
                    Fields with fixed allowed values show a hint below the label. Use the dropdown when available.
                </div>
                <template x-for="[key, value] in Object.entries(currentValues)" :key="key">
                    <template x-if="inputTypeFor(key) !== 'hidden'">
                        <div class="flex items-start justify-between not-[]:gap-2">
                            <div class="pr-3">
                                <label x-text="key"></label>
                                <template x-if="constraintHintFor(key)">
                                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400" x-text="constraintHintFor(key)"></p>
                                </template>
                            </div>
                            <template x-if="inputTypeFor(key) === 'checkbox'">
                                <input type="checkbox" class="w-5 h-5" x-model="currentValues[key]"
                                    :checked="currentValues[key]" />
                            </template>
                            <template x-if="inputTypeFor(key) !== 'checkbox' && hasConstraintOptions(key)">
                                <select
                                    class="p-2 text-left rounded-md bg-gray-100 dark:bg-gray-700 min-w-48"
                                    x-model="currentValues[key]">
                                    <option value="">Select value</option>
                                    <template x-for="option in constraintOptionsFor(key)" :key="option">
                                        <option :value="option" x-text="option"></option>
                                    </template>
                                </select>
                            </template>
                            <template x-if="inputTypeFor(key) !== 'checkbox' && !hasConstraintOptions(key)">
                                <input :type="inputTypeFor(key)"
                                    class="p-2 text-left rounded-md bg-gray-100 dark:bg-gray-700"
                                    x-model="currentValues[key]" />
                            </template>
                        </div>
                    </template>
                </template>
            </div>

            <!-- Add/Edit Button -->
            <div class="mt-4 flex justify-end">
                <button @click="saveInventory"
                    class="px-4 py-2 bg-blue-600 text-white rounded-md shadow hover:bg-blue-700">
                    Add/Edit Inventory
                </button>
            </div>
        </div>

        <div x-show="tab === 'Settings'"
            class="space-y-2 md:p-4 grid grid-cols-2 gap-4  text-gray-700 dark:text-white ">

            <div class="rounded-lg border px-4 py-3 {% if can_manage_site %}border-green-300 bg-green-50 text-green-900 dark:border-green-700 dark:bg-green-950/30 dark:text-green-100{% else %}border-gray-300 bg-gray-50 text-gray-800 dark:border-gray-700 dark:bg-gray-900/40 dark:text-gray-200{% endif %}"
                style="grid-column: 1 / -1;">
                {% if can_manage_site %}
                This profile has admin access. Site-management and one-time maintenance actions are enabled.
                {% else %}
                This profile does not have admin access. Site-management and maintenance actions are hidden.
                {% endif %}
            </div>

            <label class="flex items-center">
                Display Name
            </label>
            <input type="text" x-model="settings.display_name"
                class="p-2 text-left rounded-md bg-gray-100 dark:bg-gray-700">

            <label class="flex items-center">
                Display Image
            </label>

            <div>
                <input type="file" @change="uploadImage($event)" accept="image/jpeg,image/jpg"
                    class="p-2 text-left rounded-md bg-gray-100 dark:bg-gray-700">
                <template x-if="settings.display_image">
                    <img :src="uploadBaseUrl + settings.display_image.replace(/\\/g, '/')"
                        class="p-2 w-32 h-32 object-cover rounded-2xl">
                </template>
            </div>

            <label class="flex items-center">
                Bio Description (HTML)
            </label>
            <textarea x-model="settings.bio"
                class="p-2 text-left rounded-md h-80 bg-gray-100 dark:bg-gray-700"></textarea>

            <label class="flex items-center">
                Website Name
            </label>
            <input type="text" x-model="settings.site_name"
                class="p-2 text-left rounded-md bg-gray-100 dark:bg-gray-700">

            <label class="flex items-center">
                Astrometry.net API Key (optional)
            </label>

            <div x-data="{ show: false }" class="relative">
                <input :type="show ? 'text' : 'password'" x-model="settings.astrometry_api"
                    class="p-2 pr-10 text-left rounded-md bg-gray-100 dark:bg-gray-700 w-full">

                <button type="button" @click="show = !show"
                    class="absolute right-2 top-2 text-gray-600 dark:text-gray-300">
                    <svg x-show="!show" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                        viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7
                                -1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>

                    <svg x-show="show" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                        viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.477 0-8.268-2.943-9.542-7
                                a10.097 10.097 0 012.042-3.362M6.18 6.18A9.956 9.956 0 0112 5c4.477 0 8.268 2.943
                                9.542 7a10.094 10.094 0 01-4.043 5.263M3 3l18 18" />
                    </svg>
                </button>
            </div>

            <label class="flex items-center">
                Open Weather Maps API Key (optional)
            </label>

            <div x-data="{ show: false }" class="relative">
                <input :type="show ? 'text' : 'password'" x-model="settings.owm_api"
                    class="p-2 pr-10 text-left rounded-md bg-gray-100 dark:bg-gray-700 w-full">

                <button type="button" @click="show = !show"
                    class="absolute right-2 top-2 text-gray-600 dark:text-gray-300">
                    <svg x-show="!show" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                        viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7
                                -1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>

                    <svg x-show="show" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                        viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.477 0-8.268-2.943-9.542-7
                                a10.097 10.097 0 012.042-3.362M6.18 6.18A9.956 9.956 0 0112 5c4.477 0 8.268 2.943
                                9.542 7a10.094 10.094 0 01-4.043 5.263M3 3l18 18" />
                    </svg>
                </button>
            </div>

            <label class="flex items-center">
                Telescopius API Key (optional)
            </label>

            <div x-data="{ show: false }" class="relative">
                <input :type="show ? 'text' : 'password'" x-model="settings.telescopius_api"
                    class="p-2 pr-10 text-left rounded-md bg-gray-100 dark:bg-gray-700 w-full">

                <button type="button" @click="show = !show"
                    class="absolute right-2 top-2 text-gray-600 dark:text-gray-300">
                    <svg x-show="!show" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                        viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7
                                            -1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>

                    <svg x-show="show" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                        viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.477 0-8.268-2.943-9.542-7
                                            a10.097 10.097 0 012.042-3.362M6.18 6.18A9.956 9.956 0 0112 5c4.477 0 8.268 2.943
                                            9.542 7a10.094 10.094 0 01-4.043 5.263M3 3l18 18" />
                    </svg>
                </button>
            </div>

            <label class="flex items-center">
                Welcome Page Note (HTML)
            </label>
            <textarea x-model="settings.welcome_note"
                class="p-2 text-left rounded-md h-80 bg-gray-100 dark:bg-gray-700"></textarea>

            <div style="grid-column: 1 / -1;">
                <button @click="saveSettings" class="w-full px-4 py-3 bg-blue-600 text-white rounded hover:bg-blue-700">
                    Save Settings
                </button>
            </div>

            {% if can_manage_site %}
            <div class="mt-2 rounded-lg border border-amber-300 bg-amber-50 p-4 dark:border-amber-700 dark:bg-amber-950/30"
                style="grid-column: 1 / -1;">
                <div class="flex flex-col gap-4">
                    <div>
                        <h3 class="font-semibold text-amber-900 dark:text-amber-200">Admin Maintenance</h3>
                        <p class="mt-1 text-sm text-amber-800 dark:text-amber-300">
                            These actions run once when you click them. They are intended for manual cleanup and backfills.
                        </p>
                    </div>

                    <div class="rounded-md border border-amber-200 bg-white/50 p-4 dark:border-amber-800 dark:bg-black/10">
                        <div>
                            <p class="font-medium">Redo plate solving for all images</p>
                            <p class="text-sm text-gray-600 dark:text-gray-300">
                                Rebuild thumbnails, overlays, and pixel scale from each image's stored plate-solving header.
                            </p>
                        </div>
                        <button @click="runRedoPlateSolvingOnce" type="button"
                            class="mt-3 w-full px-4 py-2 text-white rounded"
                            style="background-color: rgb(37 99 235);">
                            Run Once
                        </button>
                    </div>

                    <div class="rounded-md border border-amber-200 bg-white/50 p-4 dark:border-amber-800 dark:bg-black/10">
                        <div>
                            <p class="font-medium">Redo guiding graphs for all images</p>
                            <p class="text-sm text-gray-600 dark:text-gray-300">
                                Rebuild stored guiding and calibration plots from each image's saved guide logs.
                            </p>
                        </div>
                        <button @click="runRedoGraphsOnce" type="button"
                            class="mt-3 w-full px-4 py-2 text-white rounded"
                            style="background-color: rgb(37 99 235);">
                            Run Once
                        </button>
                    </div>

                    <div class="rounded-md border border-red-200 bg-white/50 p-4 dark:border-red-800 dark:bg-black/10">
                        <div>
                            <p class="font-medium">Purge unbound images and thumbnails</p>
                            <p class="text-sm text-gray-600 dark:text-gray-300">
                                Delete uploaded image files and thumbnails that are no longer referenced in the database.
                            </p>
                        </div>
                        <button @click="runPurgeImagesOnce" type="button"
                            class="mt-3 w-full px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700">
                            Run Once
                        </button>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<script>
    document.addEventListener("alpine:init", () => {
        Alpine.data("settingsData", () => ({
            tab: {{ active_tab | tojson }} || localStorage.getItem("activeTab") || "Posts",
            uploadBaseUrl: "{{ url_for('blog.upload', filename='') }}",
            settings: {
                display_name: {{ user_settings.display_name | default('') | tojson }},
        display_image: {{ user_settings.display_image | default('') | tojson }},
        bio: {{ user_settings.bio | default('') | tojson }},
        site_name: {{ web_info.site_name | default('') | tojson }},
        astrometry_api: {{ user_settings.astrometry_api_key | default('')  | tojson }},
        owm_api: {{ user_settings.open_weather_api_key | default('')  | tojson }},
        telescopius_api: {{ user_settings.telescopius_api_key | default('')  | tojson }},
        welcome_note: {{ web_info.welcome_message | default('') | tojson }},
            },

        uploadImage(event) {
        this.settings.display_image = event.target.files[0];
    },

        async runRedoPlateSolvingOnce() {
        if (!confirm("Redo plate solving for all images now?")) {
        return;
    }

    const response = await fetch("/private/admin/redo_plate_solving", {
        method: "POST",
        headers: {
            "X-CSRFToken": csrfToken
        }
    });

    const data = await response.json().catch(() => ({}));
    alert(data.message || "Action finished.");
    },

        async runRedoGraphsOnce() {
        if (!confirm("Redo guiding graphs for all images now?")) {
        return;
    }

    const response = await fetch("/private/admin/redo_guiding_graphs", {
        method: "POST",
        headers: {
            "X-CSRFToken": csrfToken
        }
    });

    const data = await response.json().catch(() => ({}));
    alert(data.message || "Action finished.");
    },

        async runPurgeImagesOnce() {
        if (!confirm("Delete unbound uploaded images and thumbnails now? This cannot be undone.")) {
        return;
    }

    const response = await fetch("/private/admin/purge_orphan_image_uploads", {
        method: "POST",
        headers: {
            "X-CSRFToken": csrfToken
        }
    });

    const data = await response.json().catch(() => ({}));
    alert(data.message || "Action finished.");
    },

        async saveSettings() {
        const form = new FormData();
        form.append("display_name", this.settings.display_name);
        form.append("site_name", this.settings.site_name);
        form.append("astrometry_api", this.settings.astrometry_api);
        form.append("owm_api", this.settings.owm_api);
        form.append("telescopius_api", this.settings.telescopius_api);
        form.append("welcome_note", this.settings.welcome_note);
        form.append("bio", this.settings.bio);

        if(this.settings.display_image) {
        form.append("display_image", this.settings.display_image);
    }

    const response = await fetch("/private/update_settings", {
        method: "POST",
        headers: {
            "X-CSRFToken": csrfToken
        },
        body: form
    });

    if (response.ok) {
        alert("Settings saved!");
        location.reload();
    } else {
        alert("Failed to save.");
    }
            }
        }));
    });
</script>
{%endblock%}
