<h2 class="text-2xl font-bold mb-6 text-gray-700">Kontrol Alat</h2>

<div class="grid grid-cols-1 md:grid-cols-2 gap-6">

    <!-- HEATER -->
    <div class="bg-white p-6 rounded-2xl shadow">
        <div class="flex justify-between items-center">
            <p class="font-semibold text-gray-700 flex items-center gap-2">
                🔥 Heater
            </p>
            <input type="checkbox" id="heaterToggle"
                onchange="setHeater(this)"
                class="w-6 h-6 cursor-pointer">
        </div>
    </div>

    <!-- FAN -->
    <div class="bg-white p-6 rounded-2xl shadow">
        <div class="flex justify-between items-center">
            <p class="font-semibold text-gray-700 flex items-center gap-2">
                💨 Fan
            </p>
            <input type="checkbox" id="fanToggle"
                onchange="setFan(this)"
                class="w-6 h-6 cursor-pointer">
        </div>
    </div>

</div>

<!-- JADWAL -->
<div class="bg-white p-6 rounded-2xl shadow mt-6">
    <p class="font-semibold mb-3 text-gray-700">
        ⏰ Jadwal Otomatis
    </p>

    <div class="grid grid-cols-2 gap-4">
        <div>
            <label class="text-sm text-gray-500">Start Time</label>
            <input id="startTime" type="time" class="border p-2 rounded-xl w-full">
        </div>
        <div>
            <label class="text-sm text-gray-500">End Time</label>
            <input id="endTime" type="time" class="border p-2 rounded-xl w-full">
        </div>
    </div>

    <button onclick="setSchedule()"
        class="mt-4 bg-purple-500 text-white px-6 py-2 rounded-xl">
        Simpan Jadwal
    </button>
</div>

<!-- MODE -->
<div class="bg-white p-4 rounded-2xl shadow mt-4">
    <p class="text-sm text-gray-500">Status Mode</p>

    <div class="flex gap-3 mt-2">
        <span id="modeAuto"
            onclick="setModeAuto()"
            class="px-4 py-1 rounded-xl bg-gray-300 text-white cursor-pointer">
            CONTROL
        </span>
        <span id="modeManual"
            onclick="setModeManual()"
            class="px-4 py-1 rounded-xl bg-gray-300 text-white cursor-pointer">
            MANUAL
        </span>
    </div>
</div>

<script type="module">

import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import { getDatabase, ref, set, update, onValue } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-database.js";

const firebaseConfig = {
    apiKey: "AIzaSyC-Wdu6vNC0dRyF33S3_C2wpVt9I6wnp0w",
    authDomain: "smartoven-f9fdd.firebaseapp.com",
    databaseURL: "https://smartoven-f9fdd-default-rtdb.firebaseio.com/",
    projectId: "smartoven-f9fdd",
    appId: "1:1005261996032:web:1bcb483b922275f08f98e5"
};

const app = initializeApp(firebaseConfig);
const db  = getDatabase(app);

const heaterToggleEl = document.getElementById("heaterToggle");
const fanToggleEl    = document.getElementById("fanToggle");
const startTimeEl    = document.getElementById("startTime");
const endTimeEl      = document.getElementById("endTime");
const modeAutoEl     = document.getElementById("modeAuto");
const modeManualEl   = document.getElementById("modeManual");

let currentMode = 0; // 0 = CONTROL/AUTO, 1 = MANUAL

// ===== UI MODE =====
const setModeUi = (mode) => {
    currentMode = mode;

    if (mode === 0) {
        // CONTROL aktif
        modeAutoEl.classList.replace("bg-gray-300", "bg-green-500");
        modeManualEl.classList.replace("bg-green-500", "bg-gray-300");

        heaterToggleEl.disabled = true;
        fanToggleEl.disabled    = true;
        startTimeEl.disabled    = false;
        endTimeEl.disabled      = false;
    } else {
        // MANUAL aktif
        modeManualEl.classList.replace("bg-gray-300", "bg-green-500");
        modeAutoEl.classList.replace("bg-green-500", "bg-gray-300");

        heaterToggleEl.disabled = false;
        fanToggleEl.disabled    = false;
        startTimeEl.disabled    = true;
        endTimeEl.disabled      = true;
    }
};

// ===== SET MODE =====
window.setModeAuto = function () {
    set(ref(db, 'control/mode'), 0);
};

window.setModeManual = function () {
    set(ref(db, 'control/mode'), 1);
};

// ===== MANUAL CONTROL =====
window.setHeater = function (el) {
    if (currentMode !== 1) {
        alert("Pakai mode MANUAL dulu!");
        el.checked = !el.checked;
        return;
    }
    set(ref(db, 'manual/heater'), el.checked ? 1 : 0);
};

window.setFan = function (el) {
    if (currentMode !== 1) {
        alert("Pakai mode MANUAL dulu!");
        el.checked = !el.checked;
        return;
    }
    set(ref(db, 'manual/fan'), el.checked ? 1 : 0);
};

// ===== JADWAL =====
window.setSchedule = function () {
    const start = startTimeEl.value;
    const end   = endTimeEl.value;

    if (!start || !end) {
        alert("Isi waktu dulu!");
        return;
    }

    const [sh, sm] = start.split(":").map(Number);
    const [eh, em] = end.split(":").map(Number);

    update(ref(db, 'control'), {
        start_hour:   sh,
        start_minute: sm,
        end_hour:     eh,
        end_minute:   em
    })
    .then(() => alert(`Jadwal disimpan!\nStart: ${start}\nEnd: ${end}`))
    .catch((err) => alert("Gagal simpan: " + err));
};

// ===== LISTENERS =====

// Mode
onValue(ref(db, 'control/mode'), (snap) => {
    const mode = snap.val();
    if (mode == null) return;
    setModeUi(mode);
});

// Toggle manual (heater & fan)
onValue(ref(db, 'manual'), (snap) => {
    const d = snap.val();
    if (!d) return;
    heaterToggleEl.checked = d.heater === 1;
    fanToggleEl.checked    = d.fan    === 1;
});

// Jadwal — digabung dalam 1 listener
onValue(ref(db, 'control'), (snap) => {
    const d = snap.val();
    if (!d) return;

    if (d.start_hour != null && d.start_minute != null) {
        startTimeEl.value =
            String(d.start_hour).padStart(2, '0') + ":" +
            String(d.start_minute).padStart(2, '0');
    }

    if (d.end_hour != null && d.end_minute != null) {
        endTimeEl.value =
            String(d.end_hour).padStart(2, '0') + ":" +
            String(d.end_minute).padStart(2, '0');
    }
});

</script>