{% extends 'base.html' %}

{% block content %}
<!-- Page Title -->
<div class="text-center mb-4">
  <h1 class="fw-bold">NFC Write Process</h1>
  <p class="text-muted">Follow the steps below to write data to your NFC tag.</p>
</div>

<!-- Instruction Section -->
<div class="card shadow-sm mb-4">
  <div class="card-body">
    <h5 class="card-title mb-3">
      <i class="bi bi-info-circle text-info me-2"></i> Instructions
    </h5>
    <ul class="list-unstyled">
      <li><i class="bi bi-check-circle-fill text-success me-2"></i> Attach NFC tag to spool so you can reach it with the
        top of your phone.
      </li>
      <li><i class="bi bi-wifi text-primary me-2"></i> Allow NFC usage if prompted.</li>
      <li><i class="bi bi-phone text-secondary me-2"></i> Bring the tag close to your phone when prompted.</li>
    </ul>
  </div>
</div>

<!-- Action Button -->
<div class="text-center mb-3">
  <button id="write" class="btn btn-lg btn-primary shadow" onclick="writeNFC()">
    <i class="bi bi-nfc me-2"></i> Start Writing NFC Tag
  </button>
</div>

<!-- Message Display -->
<div id="message" class="alert alert-secondary text-center" role="alert">
  Press "Start Writing NFC Tag" to begin.
</div>

<script type="text/javascript">
  function writeNFC() {
    // Update user message
    const messageBox = document.getElementById("message");
    messageBox.className = "alert alert-info text-center";
    messageBox.textContent = "Bring NFC Tag closer to the phone...";
    if ('NDEFReader' in window) {
      const ndef = new NDEFReader();
      // Attempt to write the NFC tag
      ndef.write({
        records: [{recordType: "url", data: "{{ BASE_URL }}/spool_info?tag_id={{ myuuid }}"}],
      }).then(() => {
        messageBox.className = "alert alert-success text-center";
        messageBox.textContent = "✅ Message successfully written to the NFC tag!";
      }).catch(error => {
        messageBox.className = "alert alert-danger text-center";
        messageBox.textContent = "❌ Write failed. Please try again: " + error;
      });
    } else {
      messageBox.className = "alert alert-danger text-center";
      messageBox.textContent = "Your browser or device does not support NFC writing. Try Android Phone with Chrome browser.";
    }
  }
</script>
{% endblock %}
