{% extends "admin_base.html" %}
{% block title %}Settings | Nexora Admin{% endblock %}
{% block content %}
<div class="admin-head">
  <p class="eyebrow">Configuration</p>
  <h1>Website Settings</h1>
  <p>Control branding, navigation theme, event details, payment, about text, contact information and email notifications from one place.</p>
</div>

<!-- ══ WEBSITE BRANDING ══ -->
<form method="post" enctype="multipart/form-data" class="settings-form">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="branding">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-palette"></i></span>
      <div class="set-title">
        <h2>Website Branding</h2>
        <p>Logo shown in the navigation &amp; sidebar, background used on the homepage hero.</p>
      </div>
    </header>

    <div class="set-body">
      <div class="brand-previews">
        {% set logo_img = img(settings.site_logo) if settings.site_logo else '' %}
        {% if logo_img %}
        <figure class="media-preview-card">
          <div class="mpc-media mpc-contain"><img src="{{ url_for('serve_media', filename=logo_img) }}" alt="Current website logo"></div>
          <figcaption><i class="fas fa-stamp"></i> Current Logo</figcaption>
        </figure>
        {% endif %}
        {% set bg_img = img(settings.home_background) if settings.home_background else '' %}
        {% if bg_img %}
        <figure class="media-preview-card">
          <div class="mpc-media mpc-cover"><img src="{{ url_for('serve_media', filename=bg_img) }}" alt="Current homepage background"></div>
          <figcaption><i class="fas fa-image"></i> Current Homepage Background</figcaption>
        </figure>
        {% endif %}
      </div>

      <div class="admin-form">
        <label class="upload-tile">Website Logo<input type="file" name="site_logo" accept="image/*"></label>
        <label class="upload-tile">Homepage Background<input type="file" name="home_background" accept="image/*"></label>
      </div>
    </div>

    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-image"></i> Save Branding</button>
      {% endif %}
    </footer>
  </section>
</form>

<!-- ══ NAVIGATION THEME ══ -->
<form method="post" class="settings-form theme-form">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="theme">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-brush"></i></span>
      <div class="set-title">
        <h2>Navigation Theme</h2>
        <p>Controls the real public website top bar, menu text colour and the active-menu accent. Saved values persist across restarts.</p>
      </div>
    </header>

    <div class="set-body">
      <!-- LIVE PREVIEW -->
      <div class="nav-theme-preview" id="navThemePreview" role="presentation">
        <div class="ntp-bar">
          <span class="ntp-brand"><em>NEXORA</em> ESPORTS</span>
          <nav class="ntp-links">
            <span>Home</span>
            <span>Games</span>
            <span class="ntp-active">About</span>
            <span>Gallery</span>
          </nav>
          <span class="ntp-cta">Register</span>
        </div>
      </div>

      <div class="color-grid">
        <div class="color-field">
          <span class="cf-swatch" data-swatch style="background: {{ settings.nav_bg_color or '#d4a017' }};"></span>
          <input type="color" class="cf-native" name="nav_bg_color" value="{{ settings.nav_bg_color or '#d4a017' }}"
                 data-color-input aria-label="Top Bar Color">
          <div class="cf-meta">
            <span class="cf-name">Top Bar Color</span><code class="cf-live" data-live>{{ (settings.nav_bg_color or '#d4a017')|upper }}</code>
            <input type="text" class="cf-hex" data-hex maxlength="7" spellcheck="false" aria-label="Top bar hex value">
          </div>
        </div>
        <div class="color-field">
          <span class="cf-swatch" data-swatch style="background: {{ settings.nav_text_color or '#111827' }};"></span>
          <input type="color" class="cf-native" name="nav_text_color" value="{{ settings.nav_text_color or '#111827' }}"
                 data-color-input aria-label="Navigation Text Color">
          <div class="cf-meta">
            <span class="cf-name">Navigation Text Color</span><code class="cf-live" data-live>{{ (settings.nav_text_color or '#111827')|upper }}</code>
            <input type="text" class="cf-hex" data-hex maxlength="7" spellcheck="false" aria-label="Navigation text hex value">
          </div>
        </div>
        <div class="color-field">
          <span class="cf-swatch" data-swatch style="background: {{ settings.nav_accent_color or '#e8384f' }};"></span>
          <input type="color" class="cf-native" name="nav_accent_color" value="{{ settings.nav_accent_color or '#e8384f' }}"
                 data-color-input aria-label="Active Menu Accent">
          <div class="cf-meta">
            <span class="cf-name">Active Menu Accent</span><code class="cf-live" data-live>{{ (settings.nav_accent_color or '#e8384f')|upper }}</code>
            <input type="text" class="cf-hex" data-hex maxlength="7" spellcheck="false" aria-label="Accent hex value">
          </div>
        </div>
      </div>
      <small class="field-hint">Preview updates instantly — the public site updates when you save.</small>
    </div>

    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-floppy-disk"></i> Save Navigation Theme</button>
      {% endif %}
    </footer>
  </section>
</form>

<!-- ══ EVENT DETAILS ══ -->
<form method="post" class="settings-form">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="event">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-calendar-days"></i></span>
      <div class="set-title">
        <h2>Event Details</h2>
        <p>Title, hero copy, countdown target and venue information.</p>
      </div>
    </header>

    <div class="set-body">
      <div class="admin-form settings-grid">
        <label class="full">Event Title<input name="event_title" value="{{ settings.event_title }}" required></label>
        <label class="half">Hero Heading <span class="field-hint">(large homepage heading)</span>
          <input name="hero_heading" value="{{ settings.hero_heading }}"></label>
        <label class="half">Tagline <span class="field-hint">(short line under hero)</span>
          <input name="event_tagline" value="{{ settings.event_tagline }}"></label>
        <label class="third">Event Date / Countdown Target<span><input type="datetime-local" name="event_date"
            value="{{ settings.event_date }}" required></span></label>
        <label class="third">Early Bird Deadline<span><input type="datetime-local" name="early_deadline"
            value="{{ settings.early_deadline }}" required></span></label>
        <label class="third">Countdown Shows
          <select name="countdown_mode">
            <option value="event" {% if settings.countdown_mode != 'tickets' %}selected{% endif %}>Event Start Date</option>
            <option value="tickets" {% if settings.countdown_mode == 'tickets' %}selected{% endif %}>Tickets / Registration Last Date</option>
          </select>
        </label>
        <label class="half">Venue<input name="event_venue" value="{{ settings.event_venue }}"></label>
        <label class="quarter">City<input name="event_city" value="{{ settings.event_city }}"></label>
        <label class="full">Discount Text<input name="early_discount" value="{{ settings.early_discount }}"></label>
      </div>
    </div>

    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-floppy-disk"></i> Save Event Details</button>
      {% endif %}
    </footer>
  </section>
</form>

<!-- ══ PAYMENT ══ -->
<form method="post" enctype="multipart/form-data" class="settings-form">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="payment">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-wallet"></i></span>
      <div class="set-title">
        <h2>Payment</h2>
        <p>Bank details, QR code and registration availability.</p>
      </div>
    </header>

    <div class="set-body">
      {% set qr_img = img(settings.payment_qr_image) if settings.payment_qr_image else '' %}
      {% if qr_img %}
      <figure class="media-preview-card qr-preview">
        <div class="mpc-media qr-white"><img src="{{ url_for('serve_media', filename=qr_img) }}" alt="Current payment QR code"></div>
        <figcaption><i class="fas fa-qrcode"></i> Current Payment QR — upload a new image to replace it</figcaption>
      </figure>
      {% endif %}

      <div class="admin-form settings-grid">
        <label class="third">Bank Name<input name="payment_bank_name" value="{{ settings.payment_bank_name }}" placeholder="e.g. Meezan Bank"></label>
        <label class="third">Account Title<input name="payment_account_title" value="{{ settings.payment_account_title }}" placeholder="Account holder name"></label>
        <label class="third">Bank Branch<input name="payment_bank_branch" value="{{ settings.payment_bank_branch }}" placeholder="Branch name / code"></label>
        <label class="half">IBAN Number<input name="payment_iban" value="{{ settings.payment_iban }}" placeholder="PK00 XXXX 0000 0000 0000 0000"></label>
        <label class="half">Account Number<input name="payment_account_number" value="{{ settings.payment_account_number }}" placeholder="Account number"></label>
        <label class="third">Payment QR Code<input type="file" name="payment_qr_image" accept="image/*"></label>
        <label class="two-thirds">Payment Method Label<input name="payment_method_label" value="{{ settings.payment_method_label }}"></label>
        <label class="full">Legacy / Extra Payment Account Details<textarea name="bank_account" rows="2"
            required>{{ settings.bank_account }}</textarea></label>
        <label class="full">Payment Note<textarea name="payment_note" rows="2"
            required>{{ settings.payment_note }}</textarea></label>

        <label class="switch-row full">
          <span class="switch-copy">
            <strong>Registration Open</strong>
            <small>Uncheck to close the public registration form.</small>
          </span>
          <span class="switch">
            <input type="checkbox" name="registration_open" {% if settings.registration_open %}checked{% endif %}>
            <i></i>
          </span>
        </label>
      </div>
    </div>

    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-floppy-disk"></i> Save Payment</button>
      {% endif %}
    </footer>
  </section>
</form>

<!-- ══ ABOUT PAGE TEXT ══ -->
<form method="post" class="settings-form">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="about">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-circle-info"></i></span>
      <div class="set-title">
        <h2>About Page Text</h2>
        <p>Intro and story paragraphs shown on the public About Us page.</p>
      </div>
    </header>
    <div class="set-body">
      <div class="admin-form stacked">
        <label>Intro Paragraph<textarea name="about_intro" rows="3">{{ settings.about_intro }}</textarea></label>
        <label>Story / Main Paragraph<textarea name="about_body" rows="6">{{ settings.about_body }}</textarea></label>
      </div>
    </div>
    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-floppy-disk"></i> Save About Text</button>
      {% endif %}
    </footer>
  </section>
</form>

<!-- ══ CONTACT & SOCIAL ══ -->
<form method="post" class="settings-form">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="contact">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-address-book"></i></span>
      <div class="set-title">
        <h2>Contact &amp; Social</h2>
        <p>Contact channels and social links displayed across the site.</p>
      </div>
    </header>
    <div class="set-body">
      <div class="admin-form settings-grid">
        <label class="icon-field half"><i class="fas fa-envelope"></i>Contact Email<input type="email" name="contact_email" value="{{ settings.contact_email }}"></label>
        <label class="icon-field quarter"><i class="fas fa-phone"></i>Contact Phone<input name="contact_phone" value="{{ settings.contact_phone }}"></label>
        <label class="icon-field quarter"><i class="fas fa-location-dot"></i>Address<input name="contact_address" value="{{ settings.contact_address }}"></label>
        <label class="icon-field half"><i class="fab fa-facebook-f"></i>Facebook URL<input name="facebook_link" value="{{ settings.facebook_link }}" placeholder="https://facebook.com/..."></label>
        <label class="icon-field half"><i class="fab fa-instagram"></i>Instagram URL<input name="instagram_link" value="{{ settings.instagram_link }}" placeholder="https://instagram.com/..."></label>
        <label class="icon-field half"><i class="fab fa-youtube"></i>YouTube URL<input name="youtube_link" value="{{ settings.youtube_link }}" placeholder="https://youtube.com/..."></label>
        <label class="icon-field half"><i class="fab fa-discord"></i>Discord Invite<input name="discord_link" value="{{ settings.discord_link }}" placeholder="https://discord.gg/..."></label>
        <label class="full icon-field"><i class="fab fa-whatsapp"></i>WhatsApp Link<input name="whatsapp_link" value="{{ settings.whatsapp_link }}" placeholder="https://wa.me/92300..."></label>
      </div>
    </div>
    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-floppy-disk"></i> Save Contact &amp; Social</button>
      {% endif %}
    </footer>
  </section>
</form>

<!-- ══ EMAIL NOTIFICATIONS ══ -->
<form method="post" class="settings-form">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="email">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-envelope-circle-check"></i></span>
      <div class="set-title">
        <h2>Email Notifications</h2>
        <p>Registration confirmations, approval emails, PDF tickets and contact alerts are sent through this account.</p>
      </div>
    </header>
    <div class="set-body">
      <div class="admin-form settings-grid">
        <label class="third">SMTP Host
          <input name="smtp_host" value="{{ settings.smtp_host }}" placeholder="mail.nexoraesport.com">
        </label>
        <label class="third">SMTP Port
          <input name="smtp_port" value="{{ settings.smtp_port or '465' }}" placeholder="465">
        </label>
        <label class="third">Sender Email / Login
          <input type="email" name="smtp_user" value="{{ settings.smtp_user }}" placeholder="info@nexoraesport.com">
        </label>
        <label class="half">Mailbox Password
          <input type="password" name="smtp_password" value="" placeholder="{% if settings.smtp_password %}Saved - leave blank to keep{% else %}Enter mailbox password{% endif %}">
          <span class="field-hint">{% if settings.smtp_password %}Password is saved. Type a new one only if you want to replace it.{% else %}Use the cPanel mailbox password for the outgoing email account.{% endif %}</span>
        </label>
        <label class="half optional">From Email <span class="field-hint">(optional)</span>
          <input type="email" name="smtp_from_email" value="{{ settings.smtp_from_email }}" placeholder="info@nexoraesport.com">
        </label>
        <label class="half">Admin Notification Email
          <input type="email" name="smtp_admin_email" value="{{ settings.smtp_admin_email }}" placeholder="nexora.esport.support@gmail.com">
          <span class="field-hint">New registration/contact alerts will be sent here.</span>
        </label>
        <label class="half">Group Ticket Delivery
          <select name="group_ticket_delivery">
            <option value="leader_only" {% if settings.group_ticket_delivery != 'all_members' %}selected{% endif %}>Send tickets to group leader only</option>
            <option value="all_members" {% if settings.group_ticket_delivery == 'all_members' %}selected{% endif %}>Send a member ticket to every team member</option>
          </select>
          <span class="field-hint">Each member ticket has a member-specific serial suffix and the group QR entry code.</span>
        </label>
      </div>
    </div>
    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-floppy-disk"></i> Save Email Settings</button>
      {% endif %}
    </footer>
  </section>
</form>

<!-- ══ CHANGE PASSWORD ══ -->
<form method="post" action="{{ url_for('admin_change_password') }}" class="settings-form" id="passwordForm">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="section" value="password">
  <section class="admin-panel set-panel">
    <header class="set-head">
      <span class="set-icon"><i class="fas fa-lock"></i></span>
      <div class="set-title">
        <h2>Change Password</h2>
        <p>Update your own admin login password (minimum 8 characters).</p>
      </div>
    </header>
    <div class="set-body">
      <div class="admin-form stacked">
        <label class="pw-field full">Current Password
          <span class="pw-wrap">
            <input type="password" name="current_password" required autocomplete="current-password">
            <button type="button" class="pw-eye" data-eye aria-label="Show password"><i class="fas fa-eye"></i></button>
          </span>
        </label>
        <label class="pw-field half">New Password
          <span class="pw-wrap">
            <input type="password" name="new_password" id="newPw" required minlength="8" autocomplete="new-password">
            <button type="button" class="pw-eye" data-eye aria-label="Show password"><i class="fas fa-eye"></i></button>
          </span>
        </label>
        <label class="pw-field half">Confirm New Password
          <span class="pw-wrap">
            <input type="password" name="confirm_password" id="confirmPw" required minlength="8" autocomplete="new-password">
            <button type="button" class="pw-eye" data-eye aria-label="Show password"><i class="fas fa-eye"></i></button>
          </span>
        </label>
        <p class="pw-mismatch full" id="pwMismatch" hidden><i class="fas fa-triangle-exclamation"></i> Passwords do not match.</p>
      </div>
    </div>
    <footer class="set-foot">
      {% if can('settings_update') %}
      <button class="btn primary" type="submit"><i class="fas fa-key"></i> Update Password</button>
      {% endif %}
    </footer>
  </section>
</form>
{% endblock %}

{% block scripts %}
<script>
  (function () {
    "use strict";

    /* ── Navigation Theme: live preview + hex swatches ── */
    var preview = document.getElementById("navThemePreview");
    var map = {
      nav_bg_color:   "--ntp-bg",
      nav_text_color: "--ntp-text",
      nav_accent_color: "--ntp-accent"
    };

    function syncColorField(input) {
      var field = input.closest(".color-field");
      if (!field) return;
      var hex = input.value;
      var swatch = field.querySelector("[data-swatch]");
      var hexBox = field.querySelector("[data-hex]");
      var live = field.querySelector("[data-live]");
      if (swatch) swatch.style.background = hex;
      if (live) live.textContent = hex.toUpperCase();
      if (hexBox && document.activeElement !== hexBox) hexBox.value = hex.toUpperCase();
      if (preview && map[input.name]) preview.style.setProperty(map[input.name], hex);
    }

    document.querySelectorAll("[data-color-input]").forEach(function (input) {
      syncColorField(input);
      input.addEventListener("input", function () { syncColorField(input); });
      input.addEventListener("change", function () { syncColorField(input); });
    });

    document.querySelectorAll(".color-field").forEach(function (field) {
      var native = field.querySelector("[data-color-input]");
      var hexBox = field.querySelector("[data-hex]");
      if (!native || !hexBox) return;
      hexBox.addEventListener("input", function () {
        var v = hexBox.value.trim();
        if (/^#[0-9a-fA-F]{6}$/.test(v)) {
          native.value = v;
          syncColorField(native);
        }
      });
    });

    /* ── Password visibility toggles ── */
    document.querySelectorAll("[data-eye]").forEach(function (btn) {
      btn.addEventListener("click", function () {
        var wrap = btn.closest(".pw-wrap");
        var input = wrap ? wrap.querySelector("input") : null;
        if (!input) return;
        var show = input.type === "password";
        input.type = show ? "text" : "password";
        btn.innerHTML = show ? '<i class="fas fa-eye-slash"></i>' : '<i class="fas fa-eye"></i>';
        btn.setAttribute("aria-label", show ? "Hide password" : "Show password");
      });
    });

    /* ── Password mismatch guard ── */
    var pwForm = document.getElementById("passwordForm");
    var newPw = document.getElementById("newPw");
    var confirmPw = document.getElementById("confirmPw");
    var mismatch = document.getElementById("pwMismatch");
    function pwCheck() {
      if (!newPw || !confirmPw || !mismatch) return true;
      if (confirmPw.value && newPw.value !== confirmPw.value) {
        mismatch.hidden = false;
        confirmPw.setCustomValidity("Passwords do not match.");
        return false;
      }
      mismatch.hidden = true;
      confirmPw.setCustomValidity("");
      return true;
    }
    if (newPw && confirmPw) {
      newPw.addEventListener("input", pwCheck);
      confirmPw.addEventListener("input", pwCheck);
      pwForm.addEventListener("submit", function (e) { if (!pwCheck()) e.preventDefault(); });
    }

    /* ── Loading state on every settings form submit ── */
    document.querySelectorAll(".settings-form").forEach(function (form) {
      form.addEventListener("submit", function () {
        var btn = form.querySelector('button[type="submit"]');
        if (!btn) return;
        btn.disabled = true;
        btn.dataset.orig = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Saving…';
        setTimeout(function () {
          btn.disabled = false;
          if (btn.dataset.orig) btn.innerHTML = btn.dataset.orig;
        }, 6000);
      });
    });
  })();
</script>
{% endblock %}
