// Service Worker Registration
if ("serviceWorker" in navigator) {
	window.addEventListener("load", () => {
		navigator.serviceWorker
			.register("/sw.js")
			.then((registration) => {
				console.log("ServiceWorker registration successful");
			})
			.catch((err) => {
				console.log("ServiceWorker registration failed: ", err);
			});
	});
}

import { Nfc, SimpleNfc } from "./universal-nfc/dist/index.js";

// Initialize NFC objects
const nfc = new SimpleNfc();
const NFC = new Nfc();

// DOM Elements
const startReadingBtn = document.getElementById("startReadingBtn");
const stopReadingBtn = document.getElementById("stopReadingBtn");
const writeTextBtn = document.getElementById("writeTextBtn");
const writeUrlBtn = document.getElementById("writeUrlBtn");
const outputDiv = document.getElementById("output");

// Event Listeners
startReadingBtn.addEventListener("click", async () => {
	try {
		const available = await nfc.isAvailable();
		if (!available) {
			outputDiv.textContent = "NFC is not available on this device/browser";
			return;
		}

		const { enabled } = await NFC.isEnabled();
		if (!enabled) {
			outputDiv.textContent = "NFC is not enabled on this device";
			return;
		}

		await nfc.startReading((content, type) => {
			outputDiv.textContent = `Read ${type}: ${content}`;
		});
	} catch (error) {
		console.error("Error starting NFC scan:", error);
		outputDiv.textContent = `Error: ${error.message}`;
	}
});

stopReadingBtn.addEventListener("click", () => {
	nfc.stopReading();
	outputDiv.textContent = "NFC scanning stopped";
});

writeTextBtn.addEventListener("click", async () => {
	try {
		const { enabled } = await NFC.isEnabled();
		if (!enabled) {
			outputDiv.textContent = "NFC is not enabled on this device";
			return;
		}

		await nfc.writeText("Hello NFC");
		outputDiv.textContent = "Text written to NFC tag";
	} catch (error) {
		console.error("Error writing to tag:", error);
		outputDiv.textContent = `Error: ${error.message}`;
	}
});

writeUrlBtn.addEventListener("click", async () => {
	try {
		const { enabled } = await NFC.isEnabled();
		if (!enabled) {
			outputDiv.textContent = "NFC is not enabled on this device";
			return;
		}

		await nfc.writeUrl("https://example.com");
		outputDiv.textContent = "URL written to NFC tag";
	} catch (error) {
		console.error("Error writing URL to tag:", error);
		outputDiv.textContent = `Error: ${error.message}`;
	}
});

// Initialize camera when page loads
initCamera();
