<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EDS Trend (Pure Web)</title>

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- Alpine.js (defer = important!) -->
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>

    <!-- Google Font: Poppins (exciting but stable) -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700;800&display=swap" rel="stylesheet">

    <style>
        /* === DARK THEME VARIABLES === */
        :root {
            --color-bg: #121212;
            --color-card: #1E1E1E;
            --color-text-primary: #E0E0E0;
            --color-text-secondary: #A0A0A0;

            --color-accent: #FF9800; /* Orange */
            --color-accent-hover: #FFB74D;
            --color-affirm: #22c55e;   /* nice Tailwind green-500 */
            --color-error: #F44336; /* Red */
            --color-details-title: #9C27B0; /* Purple */
            --color-input-border: #03A9F4; /* Blue */
        }

        body {
            background-color: var(--color-bg);
            color: var(--color-text-primary);
            font-family: 'Poppins', Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
        }

        .card-bg {
            background-color: var(--color-card);
            /* subtle purple edge */
            border: 1px solid rgba(156,39,176,0.12);
            box-shadow: 0 6px 18px rgba(0,0,0,0.35), inset 0 0 0 1px rgba(156,39,176,0.02);
        }

        .input-border-visible {
            border: 1px solid var(--color-input-border);
        }

        input:focus, input:focus-visible {
            outline: 2px solid var(--color-accent);
            border-color: var(--color-accent) !important;
            box-shadow: none;
        }

        .text-accent {
            color: var(--color-accent);
        }

        .btn-primary {
            background-color: var(--color-affirm);
            color: var(--color-text-primary);
            font-weight: 700;
            transition: background-color 0.2s, transform 0.2s;
        }
        .btn-primary:hover:not(:disabled) {
            background-color: var(--color-accent-hover);
        }
        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        summary {
            cursor: pointer;
            padding: 0.5rem 0;
            font-weight: 600;
        }

        summary::-webkit-details-marker {
            display: none;
        }

        /* === Compact / Mobile-friendly overrides === */
        /* Reduce global font sizing and tighten paddings so the page fits a single mobile view */
        body {
            font-size: 14px;
        }

        h1 {
            font-size: 1.25rem !important;
            line-height: 1.1;
            margin-bottom: 0.25rem;
        }

        /* Section titles: make h2 and details summary consistent and a bit smaller */
        .card-bg h2,
        details > summary {
            color: var(--color-details-title) !important;
            font-size: 1rem !important;
            margin-bottom: 0.15rem !important;
            font-weight: 700 !important;
            letter-spacing: -0.01em;
        }

        /* If a summary explicitly has inline color, prefer the variable instead */
        details > summary[style] { color: var(--color-details-title) !important; }

        /* Make cards skinnier and reduce internal padding */
        .card-bg {
            padding: 0.75rem !important;
            border-radius: 0.6rem;
        }

        /* Tighten inputs and controls */
        input[type="text"], input[type="number"], textarea, select {
            padding: 0.45rem !important;
            font-size: 0.95rem !important;
        }

        .input-border-visible {
            border-width: 1px !important;
        }

        /* Smaller buttons */
        .btn-primary {
            padding: 0.45rem 0.75rem !important;
            font-size: 0.95rem !important;
        }

        /* Shrink status bar */
        #STATUS_BAR_WEB {
            padding: 0.35rem !important;
            font-size: 0.85rem !important;
        }

        /* Reduce container width to approximate a single-column mobile layout even on desktop */
        .max-w-4xl {
            max-width: 28rem !important;
        }

        /* Tighten details/summary spacing */
        details summary { padding: 0.25rem 0 !important; }

        /* Helpful small-screen tweaks */
        @media (max-width: 640px) {
            .max-w-4xl {
                max-width: 100% !important;
                padding-left: 0.5rem;
                padding-right: 0.5rem;
            }
        }
    </style>
</head>

<body class="p-4 sm:p-6" x-data="edsTrendApp()">

    <!-- MAIN CONTAINER -->
    <div class="w-full max-w-4xl mx-auto space-y-6">
        <h1 class="text-4xl font-extrabold text-accent mb-2">EDS Trend</h1>
        <p class="text-sm text-gray-400">Fetch and plot trend data from the EDS server.</p>
        <hr class="border-gray-700">

        <!-- MESSAGES -->
        <div x-show="message.text" 
             :class="{
                 'bg-yellow-900 border-yellow-600 text-yellow-100': message.type === 'info',
                 'bg-red-900 border-red-600 text-red-100': message.type === 'error',
                 'bg-green-900 border-green-600 text-green-100': message.type === 'success'
             }"
             class="p-3 text-sm border-l-4 rounded-lg shadow transition-all duration-300"
             x-text="message.text"
             x-cloak>
        </div>

        <!-- 1. SENSOR SELECTION -->
        <div class="card-bg p-6 rounded-xl shadow-lg space-y-4">
            <h2 class="text-2xl font-semibold">1. Sensor Selection (IDCS)</h2>
            <p class="text-sm text-gray-400">Separate IDCS with spaces or commas.</p>
            <p class="text-sm text-gray-400">(e.g., M100FI M310LI FI8001).</p>
            
            <input 
                type="text" 
                x-model="idcsInput"
                x-init="loadHistory()"
                list="idcs-history-list"
                class="w-full p-3 card-bg input-border-visible rounded-lg focus:outline-none transition duration-150"
                placeholder="Enter IDCS list here or select from history."
            >
            <datalist id="idcs-history-list">
                <template x-for="item in idcsHistory" :key="item">
                    <option :value="item"></option>
                </template>
            </datalist>
            
            <div class="flex items-center pt-2">
                <input type="checkbox" id="default_idcs_web" x-model="defaultIdcs"
                       class="form-checkbox h-5 w-5 rounded border-gray-400 focus:ring-accent card-bg"
                       style="color: var(--color-accent);">
                <label for="default_idcs_web" class="ml-3 text-base">Use Configured Default IDCS</label>
            </div>
        </div>

        <!-- 2. TIME RANGE -->
        <div class="card-bg p-6 rounded-xl shadow-lg space-y-4">
            <details closed>
                <summary class="text-2xl font-semibold" style="color: var(--color-details-title)">2. Time Range</summary>
                <p class="text-sm text-gray-400 pt-4">You can define zero, one, or two of these variables.</p>
                <p class="text-sm text-gray-400 pt-4"> Defaults to last 48h.</p>
                <br></br>
                <div class="grid grid-cols-1 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-400 mb-1" >Days to Plot</label>
                        <input type="number" x-model="daysInput"
                               class="w-full p-3 card-bg input-border-visible rounded-lg"
                               placeholder="e.g., 7.5 (optional, integers or decimals)">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-400 mb-1">Start Time</label>
                        <input type="text" x-model="startTimeInput"
                               class="w-full p-3 card-bg input-border-visible rounded-lg"
                               placeholder="e.g., 18 February 2025 (optional, various formats)">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-400 mb-1">End Time</label>
                        <input type="text" x-model="endTimeInput"
                               class="w-full p-3 card-bg input-border-visible rounded-lg"
                               placeholder="e.g., 2024-10-25 12:00 (optional, various formats)">
                    </div>
                </div>
            </details>
        </div>

        <!-- 3. ADVANCED OPTIONS -->
        <div class="card-bg p-6 rounded-xl shadow-lg">
            <details>
                <summary class="text-2xl font-semibold" style="color: var(--color-details-title)">3. Advanced Data Options</summary>
                <p class="text-sm text-gray-400 pt-4">Defaults to ~400 data points. You can specify the time delta between points, or choose the number of points.</p>

                <div class="pt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-400 mb-1">Seconds Between Points</label>
                        <input type="number" x-model="secondsBetweenPointsInput"
                               class="w-full p-3 card-bg input-border-visible rounded-lg"
                               placeholder="e.g., 60">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-400 mb-1">Datapoint Count</label>
                        <input type="number" x-model="datapointCountInput"
                               class="w-full p-3 card-bg input-border-visible rounded-lg"
                               placeholder="e.g., 1000">
                    </div>
                </div>
                <!-- Small separator and mock-data option -->
                <div class="border-t border-gray-700 mt-4 pt-3">
                    <div class="flex items-center">
                        <input type="checkbox" id="use_mock_web" x-model="useMock"
                               class="form-checkbox h-4 w-4 rounded border-gray-400 focus:ring-accent card-bg"
                               style="color: var(--color-accent);">
                        <label for="use_mock_web" class="ml-3 text-sm text-gray-300">Use mock data (no VPN required)</label>
                    </div>
                </div>
            </details>
        </div>

        <!-- 4. PLOTTING METHOD -->
        <div class="card-bg p-6 rounded-xl shadow-lg space-y-6">
            <details closed>
                <summary class="text-2xl font-semibold" style="color: var(--color-details-title)">4. Plotting Method</summary>
                <p class="text-sm text-gray-400 pt-4">Choose how the plot will show. Plotly is best for cross-platform.</p>

                <div class="pt-4 flex flex-wrap gap-6">
                    <label class="flex items-center space-x-2">
                        <input type="radio" x-model="plotMethod" value="webplot"
                               class="form-radio h-5 w-5 border-gray-400 focus:ring-accent card-bg"
                               style="color: var(--color-accent);">
                        <span>Plotly Web Plot (Recommended)</span>
                    </label>
                    <label class="flex items-center space-x-2">
                        <input type="radio" x-model="plotMethod" value="matplotlib"
                               class="form-radio h-5 w-5 border-gray-400 focus:ring-accent card-bg"
                               style="color: var(--color-accent);">
                        <span>Matplotlib (Legacy)</span>
                    </label>
                </div>
            </details>
        </div>

        <!-- ACTION BUTTONS -->
        <div class="card-bg p-4 rounded-xl shadow-lg flex justify-between items-center space-x-4">
            <button 
                @click="fetchAndPlot" 
                :disabled="isLoading"
                class="btn-primary font-bold py-2 px-4 rounded w-full sm:w-auto"
            >
                <span x-show="!isLoading">Fetch & Plot Trend</span>
                <span x-show="isLoading">Processing...</span>
            </button>

            <button 
                @click="closeApp"
                class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded w-full sm:w-auto"
            >
                Close
            </button>
        </div>

        <!-- STATUS BAR -->
        <div id="STATUS_BAR_WEB"
             class="w-full p-2 mt-2 text-sm rounded text-center transition duration-200"
             :class="statusColorClasses"
             x-text="statusMessage">
        </div>
    </div>

    <!-- === ALPINE LOGIC === -->
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('edsTrendApp', () => ({
                // State
                idcsInput: '',
                defaultIdcs: false,
                startTimeInput: '',
                endTimeInput: '',
                daysInput: '',
                secondsBetweenPointsInput: '',
                datapointCountInput: '',
                plotMethod: 'webplot',
                isLoading: false,
                idcsHistory: [],
                message: { text: '', type: '' },
                statusMessage: '',
                statusColorClasses: '',
                useMock: false,

                // --- Methods ---
                setMessage(text, type = 'info', duration = 4000) {
                    this.message = { text, type };
                    if (duration > 0) {
                        setTimeout(() => this.message = { text: '', type: '' }, duration);
                    }
                },

                async loadHistory() {
                    try {
                        const response = await fetch('/api/history');
                        if (response.ok) {
                            const history = await response.json();
                            this.idcsHistory = history;
                            if (history.length > 0) this.idcsInput = history[0];
                        }
                    } catch (e) {
                        console.warn('History load failed:', e);
                    }
                },

                async fetchAndPlot() {
                    if (!this.idcsInput.trim() && !this.defaultIdcs) {
                        this.setMessage("Please enter at least one IDCS or enable default IDCS.", 'error', 6000);
                        return;
                    }

                    this.isLoading = true;
                    this.setMessage("Fetching data... please wait.", 'info', 0);

                    const payload = {
                        idcs: this.idcsInput.trim().split(/[\s,]+/).filter(Boolean),
                        default_idcs: this.defaultIdcs,
                        days: this.daysInput ? parseFloat(this.daysInput) : null,
                        starttime: this.startTimeInput.trim() || null,
                        endtime: this.endTimeInput.trim() || null,
                        seconds_between_points: this.secondsBetweenPointsInput ? parseInt(this.secondsBetweenPointsInput) : null,
                        datapoint_count: this.datapointCountInput ? parseInt(this.datapointCountInput) : null,
                        force_webplot: this.plotMethod === 'webplot',
                        force_matplotlib: this.plotMethod === 'matplotlib',
                        use_mock: this.useMock,
                    };

                    try {
                        const response = await fetch('/api/fetch_eds_trend', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(payload),
                        });

                        // Attempt to parse JSON safely. Some error responses
                        // may include different keys (error, detail, message).
                        let result = null;
                        try {
                            result = await response.json();
                        } catch (jsonErr) {
                            // Non-JSON response fallback
                            result = { error: `Non-JSON response from server: ${jsonErr.message}` };
                        }

                        if (response.ok) {
                            this.setMessage(result.message || "Success! Plot should open.", 'success', 6000);
                            this.loadHistory();
                        } else {
                            // Prefer common keys in server responses. Provide a helpful fallback.
                            const errMsg = result && (result.error || result.detail || result.message) || JSON.stringify(result) || 'Unknown error.';
                            this.setMessage(`Error: ${errMsg}`, 'error', 8000);
                        }
                    } catch (err) {
                        // Network-level errors (DNS, connection refused, CORS, etc.)
                        this.setMessage(`Network error: ${err.message}`, 'error', 8000);
                    } finally {
                        this.isLoading = false;
                    }
                },

                closeApp() {
                    // Works if app runs in PyWebView or Electron; fallback otherwise
                    try {
                        window.close();
                    } catch {
                        alert('Close pressed. (Browser tabs cannot be closed programmatically)');
                    }
                },
            }))
        });
    </script>
</body>
<body>
    <div x-data="{ showConfigIframe: false }">
        <template x-if="showConfigIframe">
            <div id="iframe-overlay">
                <iframe 
                    :src="configIframeUrl" 
                    frameborder="0" 
                    class="w-full h-full">
                </iframe>
            </div>
        </template>
    </div>
    
    </body>
</html>
