<script lang="ts">
    import { onMount } from "svelte";
    import Icon from "@iconify/svelte";

    interface ScanItem {
        id: string;
        name: string;
        date: string;
        severity: string;
        image: string | null;
        impact: string;
        alternatives: string[];
        is_greenwashing: boolean;
        is_public: boolean;
    }

    let scanHistory = $state<ScanItem[]>([]);
    let selectedScan = $state<ScanItem | null>(null);
    let userId = $state("");
    let fileInput: HTMLInputElement | undefined;
    let isScanning = $state(false);

    onMount(() => {
        let storedId = localStorage.getItem("ethix_user_id");
        if (!storedId) {
            storedId = crypto.randomUUID();
            localStorage.setItem("ethix_user_id", storedId);
        }
        userId = storedId;

        fetchHistory();

        // Listen for scan-complete event to refresh history
        const handleScanComplete = () => {
            fetchHistory();
        };
        window.addEventListener("scan-complete", handleScanComplete);

        return () => {
            window.removeEventListener("scan-complete", handleScanComplete);
        };
    });

    async function fetchHistory() {
        if (!userId) return;
        try {
            const res = await fetch(
                `/api/incidents/history?user_id=${userId}`,
            );
            const data = await res.json();
            if (Array.isArray(data)) {
                scanHistory = data.map((item: any) => ({
                    id: item._id,
                    name: item.product_name,
                    date: new Date(item.created_at).toLocaleDateString(),
                    severity: item.analysis?.severity || "Low",
                    image: item.image_base64
                        ? `data:image/jpeg;base64,${item.image_base64}`
                        : null,
                    impact: item.analysis?.verdict || "No impact assessment",
                    alternatives: item.analysis?.alternatives || [],
                    is_greenwashing: item.analysis?.is_greenwashing || false,
                    is_public: item.is_public || false,
                }));
            }
        } catch (e) {
            console.error("Failed to fetch history", e);
        }
    }

    function triggerScan() {
        if (isScanning || !fileInput) return;
        fileInput.click();
    }

    async function handleFileSelect(e: Event) {
        const target = e.target as HTMLInputElement;
        if (!target.files || target.files.length === 0) return;

        const file = target.files[0];
        isScanning = true;

        const reader = new FileReader();
        reader.onload = async () => {
            const base64String = reader.result as string;
            await submitScan(base64String);
        };
        reader.readAsDataURL(file);
    }

    async function submitScan(imageBase64: string) {
        try {
            const payload = {
                product_name: "Scanned Item",
                description: "Scanned via mobile app",
                report_type: "product",
                image: imageBase64,
                user_id: userId,
                is_public: false, // Default private
            };

            const res = await fetch(
                "/api/incidents/submit",
                {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(payload),
                },
            );

            const data = await res.json();

            if (data.status === "success") {
                await fetchHistory();
                selectedScan = {
                    id: data.incident_id,
                    name:
                        data.detected_brand !== "Unknown"
                            ? data.detected_brand
                            : "Scanned Product",
                    date: "Just now",
                    severity: data.analysis.severity,
                    image: imageBase64,
                    impact: data.analysis.verdict,
                    alternatives: data.analysis.alternatives || [],
                    is_greenwashing: data.is_greenwashing,
                    is_public: false,
                };
            } else {
                alert("Analysis failed: " + (data.message || "Unknown error"));
            }
        } catch (e) {
            console.error("Scan failed", e);
            alert("Analysis failed. Please try again.");
        } finally {
            isScanning = false;
            if (fileInput) fileInput.value = "";
        }
    }

    async function toggleVisibility() {
        if (!selectedScan) return;
        const newState = !selectedScan.is_public;

        // Optimistic UI update for modal
        selectedScan.is_public = newState;

        // Optimistic UI update for list
        const histIndex = scanHistory.findIndex(
            (s) => s.id === selectedScan!.id,
        );
        if (histIndex !== -1) {
            scanHistory[histIndex].is_public = newState;
        }

        try {
            await fetch(
                `/api/incidents/${selectedScan.id}/visibility`,
                {
                    method: "PUT",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ is_public: newState }),
                },
            );
        } catch (e) {
            // Revert on failure
            selectedScan.is_public = !newState;
            if (histIndex !== -1) {
                scanHistory[histIndex].is_public = !newState;
            }
            alert("Failed to update visibility");
        }
    }

    function openScan(scan: ScanItem) {
        selectedScan = scan;
    }

    function closeScan() {
        selectedScan = null;
    }

    function getSeverityClass(severity: string): string {
        return severity?.toLowerCase() || "low";
    }
</script>

<div class="min-h-screen bg-[#051f18] text-white px-5 pt-4 pb-32">

    <section class="flex gap-3 mb-7">
        <button
            class="flex-1 flex flex-col items-center gap-2 py-4 px-2 bg-[#0d2e25] border border-emerald-500/30 rounded-2xl active:scale-95 transition-all shadow-[0_0_15px_rgba(16,185,129,0.1)] relative overflow-hidden group min-h-[100px] justify-center"
            onclick={triggerScan}
            disabled={isScanning}
        >
            <div
                class="absolute inset-0 bg-emerald-500/5 group-hover:bg-emerald-500/10 transition-colors"
            ></div>
            <div
                class="w-10 h-10 bg-emerald-500/20 rounded-xl flex items-center justify-center text-emerald-400 relative z-10"
            >
                {#if isScanning}
                    <Icon
                        icon="ri:loader-4-line"
                        width="24"
                        class="animate-spin"
                    />
                {:else}
                    <Icon icon="ri:camera-lens-fill" width="24" />
                {/if}
            </div>
            <div class="flex flex-col items-center relative z-10">
                <span class="text-sm font-extrabold text-white"
                    >{isScanning ? "Analyzing..." : "Scan Item"}</span
                >
                <span
                    class="text-[10px] text-emerald-400/80 uppercase tracking-wide font-semibold"
                    >AI Detection</span
                >
            </div>
        </button>

        <div
            class="flex-1 flex flex-col items-center gap-2 py-4 px-2 bg-[#0d2e25] border border-[#1f473b] rounded-2xl min-h-[100px] justify-center"
        >
            <div
                class="w-9 h-9 bg-emerald-500/10 rounded-xl flex items-center justify-center"
            >
                <Icon icon="ri:leaf-fill" width="20" class="text-emerald-400" />
            </div>
            <span class="text-lg font-extrabold text-white"
                >{scanHistory.length}</span
            >
            <span
                class="text-[10px] text-gray-400 uppercase tracking-wide font-semibold"
                >Total Scans</span
            >
        </div>
    </section>

    <section class="recent-section">
        <div class="mb-4">
            <h2 class="text-base font-extrabold text-white m-0">Your Scans</h2>
        </div>

        <div class="flex flex-col gap-2.5">
            {#if scanHistory.length === 0}
                <div class="text-center py-10 text-gray-500 text-sm">
                    No scans yet. Start by scanning a product!
                </div>
            {/if}
            {#each scanHistory as item (item.id)}
                <button
                    class="flex items-center gap-3.5 p-5 bg-[#0d2e25] border border-[#1f473b] rounded-2xl cursor-pointer w-full text-left transition-transform active:scale-98 active:bg-[#1f473b]"
                    onclick={() => openScan(item)}
                    aria-label="View {item.name}"
                >
                    <div
                        class="w-12 h-12 rounded-xl overflow-hidden shrink-0 bg-black"
                    >
                        {#if item.image}
                            <img
                                src={item.image}
                                alt={item.name}
                                class="w-full h-full object-cover"
                            />
                        {:else}
                            <div
                                class="w-full h-full flex items-center justify-center font-bold text-[#051f18]"
                                style="background-color: {getSeverityClass(
                                    item.severity,
                                ) === 'high'
                                    ? '#fca5a5'
                                    : '#86efac'}"
                            >
                                <span class="text-lg"
                                    >{item.name ? item.name[0] : "?"}</span
                                >
                            </div>
                        {/if}
                    </div>
                    <div class="flex-1 flex flex-col gap-0.5 min-w-0">
                        <span class="text-sm font-semibold text-white truncate"
                            >{item.name}</span
                        >
                        <div class="flex items-center gap-2">
                            <span class="text-xs text-gray-400"
                                >{item.date}</span
                            >
                            {#if item.is_public}
                                <span
                                    class="text-[9px] px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-400 font-bold border border-emerald-500/30"
                                    >PUBLIC</span
                                >
                            {/if}
                        </div>
                    </div>
                    <span
                        class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wide {item.severity.toLowerCase() ===
                        'high'
                            ? 'bg-red-400/10 text-red-400 border border-red-400/20'
                            : item.severity.toLowerCase() === 'medium'
                              ? 'bg-orange-400/10 text-orange-400 border border-orange-400/20'
                              : 'bg-emerald-400/10 text-emerald-400 border border-emerald-400/20'}"
                    >
                        {item.severity}
                    </span>
                </button>
            {/each}
        </div>
    </section>

    {#if selectedScan}
        <div
            class="fixed inset-0 bg-black/70 backdrop-blur-sm z-[200] flex items-start justify-center p-4 pt-8 pb-4 overflow-y-auto"
            role="button"
            tabindex="0"
            onclick={closeScan}
            onkeydown={(e) => e.key === "Escape" && closeScan()}
        >
            <div
                class="bg-[#0d2e25] border border-[#1f473b] rounded-3xl w-full max-w-[340px] p-5 relative shadow-[0_20px_50px_rgba(0,0,0,0.5)] mb-4"
                onclick={(e) => e.stopPropagation()}
                role="document"
                tabindex="-1"
            >
                <button
                    class="absolute top-4 right-4 bg-transparent border-none text-gray-400 cursor-pointer"
                    onclick={closeScan}
                >
                    <Icon icon="ri:close-fill" width="24" />
                </button>
                <div class="text-center mb-4">
                    <span
                        class="text-xs text-gray-400 uppercase tracking-widest"
                        >{selectedScan.date}</span
                    >
                    <h2 class="text-xl text-white m-0 mt-1">Scan Report</h2>
                </div>
                <div
                    class="w-full h-[160px] bg-black rounded-2xl mb-4 overflow-hidden"
                >
                    {#if selectedScan.image}
                        <img
                            src={selectedScan.image}
                            alt={selectedScan.name}
                            class="w-full h-full object-cover"
                        />
                    {:else}
                        <div
                            class="w-full h-full flex items-center justify-center"
                            style="background-color: {getSeverityClass(
                                selectedScan.severity,
                            ) === 'high'
                                ? '#fca5a5'
                                : '#86efac'}"
                        >
                            <span class="text-6xl text-[#051f18] font-black"
                                >{selectedScan.name
                                    ? selectedScan.name[0]
                                    : "?"}</span
                            >
                        </div>
                    {/if}
                </div>
                <div class="text-center">
                    <h3 class="text-lg text-white m-0 mb-1">
                        {selectedScan.name}
                    </h3>

                    <div class="flex justify-center gap-2 my-4">
                        <div
                            class="inline-block px-3 py-1.5 rounded-full text-xs font-bold uppercase {selectedScan.severity.toLowerCase() ===
                            'high'
                                ? 'bg-red-400/20 text-red-400'
                                : selectedScan.severity.toLowerCase() ===
                                    'medium'
                                  ? 'bg-orange-400/20 text-orange-400'
                                  : 'bg-emerald-400/20 text-emerald-400'}"
                        >
                            Severity: {selectedScan.severity}
                        </div>
                    </div>

                    <!-- Visibility Toggle -->
                    <button
                        class="mb-4 flex items-center justify-center gap-2 px-4 py-2 rounded-xl text-xs font-bold w-full border {selectedScan.is_public
                            ? 'bg-emerald-500/20 text-emerald-400 border-emerald-500/50'
                            : 'bg-[#051f18] text-gray-400 border-[#1f473b]'}"
                        onclick={toggleVisibility}
                    >
                        <div
                            class="w-3 h-3 rounded-full {selectedScan.is_public
                                ? 'bg-emerald-400'
                                : 'bg-gray-500'}"
                        ></div>
                        {selectedScan.is_public
                            ? "PUBLIC REPORT (Visible to everyone)"
                            : "PRIVATE REPORT (Only you)"}
                    </button>

                    <p class="text-gray-300 text-sm mb-4 leading-relaxed">
                        {selectedScan.impact}
                    </p>

                    {#if selectedScan.alternatives && selectedScan.alternatives.length > 0}
                        <div
                            class="mt-6 text-left bg-emerald-900/20 p-4 rounded-xl border border-emerald-500/20 mb-2"
                        >
                            <h4
                                class="text-emerald-400 text-xs font-bold uppercase tracking-widest mb-3 flex items-center gap-2"
                            >
                                <Icon icon="ri:leaf-line" />
                                Sustainable Alternatives
                            </h4>
                            <ul class="text-sm text-gray-300 space-y-2 pl-1">
                                {#each selectedScan.alternatives as alt}
                                    <li class="flex items-start gap-2">
                                        <span class="text-emerald-500 mt-1"
                                            >•</span
                                        >
                                        <span>{alt}</span>
                                    </li>
                                {/each}
                            </ul>
                        </div>
                    {/if}
                </div>
            </div>
        </div>
    {/if}
</div>
