// Simpan user default jika belum ada
if (!localStorage.getItem("adminUser")) {
  const userData = {
    username: "admin",
    password: "admin123"
  };
  localStorage.setItem("adminUser", JSON.stringify(userData));
}

// Fungsi Login
function login(event) {
  event.preventDefault();
  const username = document.getElementById("username").value.trim();
  const password = document.getElementById("password").value.trim();
  const savedUser = JSON.parse(localStorage.getItem("adminUser"));

  if (username === savedUser.username && password === savedUser.password) {
    document.getElementById("login-form").style.display = "none";
    document.getElementById("main-ui").style.display = "block";
    tampilkanProduk();
  } else {
    alert("Username atau password salah!");
  }
}

// Menambahkan produk ke localStorage
function tambahProduk(event) {
  event.preventDefault();
  const nama = document.getElementById("nama-produk").value.trim();
  const harga = parseInt(document.getElementById("harga-produk").value.trim());
  const barcode = document.getElementById("barcode-produk").value.trim();

  let produkList = JSON.parse(localStorage.getItem("produkList")) || [];

  produkList.push({ nama, harga, barcode });
  localStorage.setItem("produkList", JSON.stringify(produkList));

  tampilkanProduk();
}

// Menampilkan daftar produk
function tampilkanProduk() {
  const listEl = document.getElementById("list-produk");
  listEl.innerHTML = "";
  const produkList = JSON.parse(localStorage.getItem("produkList")) || [];

  produkList.forEach((produk, index) => {
    const li = document.createElement("li");
    li.textContent = `${produk.nama} - Rp${produk.harga} - ${produk.barcode}`;
    listEl.appendChild(li);
  });
}

// Scan barcode dan tampilkan produk
function startScan() {
  const html5QrCode = new Html5Qrcode("reader");

  Html5Qrcode.getCameras().then(devices => {
    if (devices && devices.length) {
      html5QrCode.start(
        { facingMode: "environment" },
        { fps: 10, qrbox: 250 },
        scannedBarcode => {
          html5QrCode.stop();
          cekProdukDariBarcode(scannedBarcode);
        }
      ).catch(err => {
        console.error("Gagal memulai scan", err);
      });
    }
  });
}

function cekProdukDariBarcode(barcode) {
  const produkList = JSON.parse(localStorage.getItem("produkList")) || [];
  const produk = produkList.find(p => p.barcode === barcode);

  if (produk) {
    alert(`Produk ditemukan:\n${produk.nama} - Rp${produk.harga}`);
  } else {
    alert("Produk tidak ditemukan.");
  }
}

// Tampilkan/Hide dashboard
function tampilkanDashboard() {
  const dashboard = document.getElementById("admin-dashboard");
  dashboard.style.display = dashboard.style.display === "none" ? "block" : "none";
}

// Keranjang (Dummy)
function tampilkanKeranjang() {
  alert("Fitur keranjang belum tersedia.");
}
