{% extends "base.html" %}
{% set active = "ganti_password" %}

{% block title %}Ganti Password{% endblock %}
{% block page_title %}Ganti Password{% endblock %}

{% block extra_head %}
<style>
  .pw-wrap {
    max-width: 480px;
  }

  /* Strength bar */
  .strength-bar {
    height: 4px;
    background: var(--border);
    border-radius: 2px;
    margin-top: 8px;
    overflow: hidden;
  }
  .strength-fill {
    height: 100%;
    border-radius: 2px;
    transition: width .3s, background .3s;
  }
  .strength-label {
    font-size: .72rem;
    margin-top: 4px;
    transition: color .3s;
  }

  /* Input with icon */
  .input-wrap { position: relative; }
  .input-icon {
    position: absolute;
    left: 12px; top: 50%; transform: translateY(-50%);
    color: var(--muted); pointer-events: none;
  }
  .form-input-icon {
    padding-left: 40px !important;
  }
  .show-pass {
    position: absolute;
    right: 12px; top: 50%; transform: translateY(-50%);
    background: none; border: none;
    color: var(--muted); cursor: pointer;
    padding: 2px; transition: color .2s;
    display: flex; align-items: center;
  }
  .show-pass:hover { color: var(--text); }

  /* Requirement checklist */
  .req-list {
    list-style: none;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    gap: 5px;
  }
  .req-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: .78rem;
    color: var(--muted);
    transition: color .2s;
  }
  .req-item.met { color: var(--success); }
  .req-icon {
    width: 14px; height: 14px;
    border-radius: 50%;
    border: 1.5px solid var(--border);
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
    transition: all .2s;
    font-size: 8px;
  }
  .req-item.met .req-icon {
    background: var(--success);
    border-color: var(--success);
    color: #fff;
  }

  /* OAuth notice */
  .oauth-notice {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    background: rgba(227,179,65,.08);
    border: 1px solid rgba(227,179,65,.25);
    border-radius: var(--radius-sm);
    padding: 14px 16px;
    font-size: .85rem;
    color: var(--warning);
  }
  .oauth-notice svg { flex-shrink: 0; margin-top: 1px; }

  /* Submit button */
  .btn-submit {
    width: 100%;
    padding: 11px;
    background: var(--accent);
    color: #fff; border: none;
    border-radius: var(--radius-sm);
    font-family: 'DM Sans', sans-serif;
    font-size: .9rem; font-weight: 600;
    cursor: pointer;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: all .2s;
    margin-top: 4px;
  }
  .btn-submit:hover:not(:disabled) { background: #79b8ff; transform: translateY(-1px); }
  .btn-submit:disabled { opacity: .45; cursor: not-allowed; transform: none; }

  /* Toast */
  .toast {
    position: fixed;
    bottom: 28px; right: 28px;
    padding: 13px 20px;
    border-radius: var(--radius-sm);
    font-size: .875rem; font-weight: 500;
    display: flex; align-items: center; gap: 10px;
    z-index: 9999;
    animation: toast-in .25s ease;
    max-width: 340px;
    box-shadow: 0 8px 24px rgba(0,0,0,.3);
  }
  @keyframes toast-in {
    from { opacity: 0; transform: translateY(12px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  .toast-success { background: #1a3a23; border: 1px solid rgba(63,185,80,.35); color: var(--success); }
  .toast-error   { background: #3a1a1a; border: 1px solid rgba(248,81,73,.35); color: var(--danger); }
</style>
{% endblock %}

{% block content %}
<div class="pw-wrap">

  {% if user.oauth_provider %}
  <!-- ── Akun OAuth — tidak bisa ganti password lokal ── -->
  <div class="card">
    <div class="oauth-notice">
      <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12.01" y2="16"/>
      </svg>
      <div>
        <div style="font-weight:600;margin-bottom:4px">Akun terhubung via OAuth</div>
        Akun Anda masuk menggunakan
        <strong>{{ user.oauth_provider | capitalize }}</strong>.
        Ubah password melalui pengaturan akun {{ user.oauth_provider | capitalize }} Anda.
      </div>
    </div>
  </div>

  {% else %}
  <!-- ── Form ganti password ── -->
  <div class="card">
    <div class="card-header" style="margin-bottom:20px">
      <span class="card-title">🔐 Ubah Password</span>
    </div>

    <!-- Info user -->
    <div style="display:flex;align-items:center;gap:12px;padding:12px 14px;
                background:var(--surface2);border-radius:var(--radius-sm);margin-bottom:24px">
      <div style="width:36px;height:36px;border-radius:50%;
                  background:linear-gradient(135deg,var(--accent-dim),var(--accent));
                  display:flex;align-items:center;justify-content:center;
                  font-size:.9rem;font-weight:700;color:#fff;flex-shrink:0">
        {{ user.username[0].upper() }}
      </div>
      <div>
        <div style="font-size:.875rem;font-weight:600">{{ user.full_name or user.username }}</div>
        <div style="font-size:.75rem;color:var(--muted)">{{ user.username }}
          {% if user.role == 'admin' %}<span class="badge badge-admin" style="margin-left:6px">admin</span>{% endif %}
        </div>
      </div>
    </div>

    <!-- Password lama -->
    <div class="form-group">
      <label class="form-label" for="old-password">Password Saat Ini</label>
      <div class="input-wrap">
        <svg class="input-icon" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <rect x="3" y="11" width="18" height="11" rx="2"/>
          <path d="M7 11V7a5 5 0 0110 0v4"/>
        </svg>
        <input class="form-input form-input-icon" type="password" id="old-password"
               placeholder="Masukkan password saat ini" autocomplete="current-password" />
        <button type="button" class="show-pass" onclick="togglePass('old-password', 'eye-old')" title="Tampilkan">
          <svg id="eye-old" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- Password baru -->
    <div class="form-group">
      <label class="form-label" for="new-password">Password Baru</label>
      <div class="input-wrap">
        <svg class="input-icon" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <rect x="3" y="11" width="18" height="11" rx="2"/>
          <path d="M7 11V7a5 5 0 0110 0v4"/>
        </svg>
        <input class="form-input form-input-icon" type="password" id="new-password"
               placeholder="Buat password baru" autocomplete="new-password"
               oninput="checkStrength()" />
        <button type="button" class="show-pass" onclick="togglePass('new-password', 'eye-new')" title="Tampilkan">
          <svg id="eye-new" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
          </svg>
        </button>
      </div>

      <!-- Strength meter -->
      <div class="strength-bar"><div class="strength-fill" id="strength-fill" style="width:0"></div></div>
      <div class="strength-label" id="strength-label" style="color:var(--muted)">Masukkan password baru</div>

      <!-- Requirements -->
      <ul class="req-list" style="margin-top:12px">
        <li class="req-item" id="req-len">
          <span class="req-icon"></span> Minimal 6 karakter
        </li>
        <li class="req-item" id="req-upper">
          <span class="req-icon"></span> Mengandung huruf kapital
        </li>
        <li class="req-item" id="req-num">
          <span class="req-icon"></span> Mengandung angka
        </li>
        <li class="req-item" id="req-diff">
          <span class="req-icon"></span> Berbeda dari password lama
        </li>
      </ul>
    </div>

    <!-- Konfirmasi password baru -->
    <div class="form-group">
      <label class="form-label" for="confirm-password">Konfirmasi Password Baru</label>
      <div class="input-wrap">
        <svg class="input-icon" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <rect x="3" y="11" width="18" height="11" rx="2"/>
          <path d="M7 11V7a5 5 0 0110 0v4"/>
        </svg>
        <input class="form-input form-input-icon" type="password" id="confirm-password"
               placeholder="Ulangi password baru" autocomplete="new-password"
               oninput="checkMatch()" />
        <button type="button" class="show-pass" onclick="togglePass('confirm-password', 'eye-confirm')" title="Tampilkan">
          <svg id="eye-confirm" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
          </svg>
        </button>
      </div>
      <div class="form-hint" id="match-hint"></div>
    </div>

    <!-- Submit -->
    <button class="btn-submit" id="btn-submit" onclick="submitChange()" disabled>
      <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
        <path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v14a2 2 0 01-2 2z"/>
        <polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>
      </svg>
      Simpan Password Baru
    </button>
  </div>

  <!-- Tips keamanan -->
  <div class="card" style="margin-top:16px">
    <div class="card-header" style="margin-bottom:12px">
      <span class="card-title">💡 Tips Keamanan</span>
    </div>
    <ul style="font-size:.82rem;color:var(--muted);padding-left:16px;line-height:2">
      <li>Jangan gunakan password yang sama di banyak layanan</li>
      <li>Gunakan kombinasi huruf, angka, dan simbol</li>
      <li>Password akan tetap aktif pada sesi yang sudah login</li>
      <li>Hubungi admin jika lupa password lama</li>
    </ul>
  </div>
  {% endif %}

</div>
{% endblock %}

{% block scripts %}
<script>
  const EYE_OPEN   = `<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>`;
  const EYE_CLOSED = `<path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94"/>
    <path d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19"/>
    <line x1="1" y1="1" x2="23" y2="23"/>`;

  function togglePass(inputId, iconId) {
    const input = document.getElementById(inputId);
    const icon  = document.getElementById(iconId);
    if (input.type === 'password') {
      input.type = 'text';
      icon.innerHTML = EYE_CLOSED;
    } else {
      input.type = 'password';
      icon.innerHTML = EYE_OPEN;
    }
  }

  // ── Password strength ────────────────────────────────────────────
  function checkStrength() {
    const pw    = document.getElementById('new-password').value;
    const old   = document.getElementById('old-password').value;
    const fill  = document.getElementById('strength-fill');
    const label = document.getElementById('strength-label');

    // Requirement items
    setReq('req-len',   pw.length >= 6);
    setReq('req-upper', /[A-Z]/.test(pw));
    setReq('req-num',   /[0-9]/.test(pw));
    setReq('req-diff',  pw.length > 0 && pw !== old);

    // Score
    let score = 0;
    if (pw.length >= 6)        score++;
    if (pw.length >= 10)       score++;
    if (/[A-Z]/.test(pw))     score++;
    if (/[0-9]/.test(pw))     score++;
    if (/[^a-zA-Z0-9]/.test(pw)) score++;

    const levels = [
      { pct: '0%',   color: 'var(--border)',   text: 'Masukkan password baru',  labelColor: 'var(--muted)' },
      { pct: '20%',  color: 'var(--danger)',   text: 'Sangat lemah',            labelColor: 'var(--danger)' },
      { pct: '40%',  color: '#e3853d',          text: 'Lemah',                   labelColor: '#e3853d' },
      { pct: '60%',  color: 'var(--warning)',  text: 'Cukup',                   labelColor: 'var(--warning)' },
      { pct: '80%',  color: '#6bd49a',          text: 'Kuat',                    labelColor: '#6bd49a' },
      { pct: '100%', color: 'var(--success)',  text: 'Sangat kuat',             labelColor: 'var(--success)' },
    ];

    const lv = pw.length === 0 ? levels[0] : levels[Math.min(score, 5)];
    fill.style.width      = lv.pct;
    fill.style.background = lv.color;
    label.textContent     = lv.text;
    label.style.color     = lv.labelColor;

    checkMatch();
    updateSubmit();
  }

  function setReq(id, met) {
    const el   = document.getElementById(id);
    const icon = el.querySelector('.req-icon');
    el.classList.toggle('met', met);
    icon.textContent = met ? '✓' : '';
  }

  // ── Konfirmasi cocok ─────────────────────────────────────────────
  function checkMatch() {
    const pw      = document.getElementById('new-password').value;
    const confirm = document.getElementById('confirm-password').value;
    const hint    = document.getElementById('match-hint');

    if (!confirm) {
      hint.textContent = '';
      hint.style.color = '';
    } else if (pw === confirm) {
      hint.textContent = '✓ Password cocok';
      hint.style.color = 'var(--success)';
    } else {
      hint.textContent = '✗ Password tidak cocok';
      hint.style.color = 'var(--danger)';
    }
    updateSubmit();
  }

  // ── Enable/disable submit ────────────────────────────────────────
  function updateSubmit() {
    const old     = document.getElementById('old-password').value;
    const pw      = document.getElementById('new-password').value;
    const confirm = document.getElementById('confirm-password').value;
    const btn     = document.getElementById('btn-submit');

    const valid = old.length > 0
               && pw.length >= 6
               && pw !== old
               && pw === confirm;
    btn.disabled = !valid;
  }

  // Aktifkan submit-check saat field password lama berubah juga
  document.getElementById('old-password')?.addEventListener('input', () => {
    checkStrength();
    checkMatch();
    updateSubmit();
  });

  // ── Submit ───────────────────────────────────────────────────────
  async function submitChange() {
    const btn        = document.getElementById('btn-submit');
    const oldPw      = document.getElementById('old-password').value;
    const newPw      = document.getElementById('new-password').value;
    const confirmPw  = document.getElementById('confirm-password').value;

    if (newPw !== confirmPw) {
      showToast('Konfirmasi password tidak cocok.', 'error');
      return;
    }
    if (newPw.length < 6) {
      showToast('Password baru minimal 6 karakter.', 'error');
      return;
    }

    btn.disabled = true;
    btn.innerHTML = `
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83">
          <animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur=".7s" repeatCount="indefinite"/>
        </path>
      </svg>
      Menyimpan...`;

    try {
      const fd = new FormData();
      fd.append('old_password', oldPw);
      fd.append('new_password', newPw);

      const r = await fetch('/api/auth/change-password', { method: 'POST', body: fd });
      const d = await r.json();

      if (!r.ok) throw new Error(d.detail || 'Gagal mengubah password.');

      showToast('Password berhasil diubah!', 'success');

      // Reset form
      document.getElementById('old-password').value      = '';
      document.getElementById('new-password').value      = '';
      document.getElementById('confirm-password').value  = '';
      document.getElementById('strength-fill').style.width = '0';
      document.getElementById('strength-label').textContent = 'Masukkan password baru';
      document.getElementById('strength-label').style.color = 'var(--muted)';
      document.getElementById('match-hint').textContent  = '';
      ['req-len','req-upper','req-num','req-diff'].forEach(id => setReq(id, false));

    } catch (e) {
      showToast(e.message, 'error');
    } finally {
      btn.disabled = false;
      btn.innerHTML = `
        <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v14a2 2 0 01-2 2z"/>
          <polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>
        </svg>
        Simpan Password Baru`;
      updateSubmit();
    }
  }

  // ── Toast helper ─────────────────────────────────────────────────
  function showToast(msg, type = 'success') {
    const el = document.createElement('div');
    el.className = `toast toast-${type}`;
    el.innerHTML = (type === 'success')
      ? `<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg> ${msg}`
      : `<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> ${msg}`;
    document.body.appendChild(el);
    setTimeout(() => { el.style.opacity = '0'; el.style.transition = 'opacity .4s'; }, 3000);
    setTimeout(() => el.remove(), 3400);
  }
</script>
{% endblock %}