<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <meta name="theme-color" content="#0EA5E9" />
  <title>Sign in — takedowns</title>
  <link rel="stylesheet" href="/public/css/glass.css?v=2-light" />
</head>
<body>
  <div class="auth">
    <div class="panel">
      <h1>Sign in</h1>
      <p class="sub">Welcome back. <a href="/register">Create an account</a></p>

      <div id="flash"></div>

      <form id="loginForm">
        <div class="field">
          <label for="email">Email</label>
          <input id="email" name="email" type="email" autocomplete="email" required />
        </div>
        <div class="field">
          <label for="password">Password</label>
          <input id="password" name="password" type="password" autocomplete="current-password" required />
        </div>
        <button type="submit" style="width:100%">Sign in</button>
      </form>

      <p class="muted mt-2" style="text-align:center;font-size:.85rem">
        <a href="#" id="forgotLink">Forgot password?</a>
      </p>

      <div id="forgotBox" class="hidden mt-2">
        <form id="forgotForm">
          <label>Email</label>
          <input type="email" name="email" required />
          <button type="submit" class="secondary mt-1" style="width:100%">Send reset link</button>
        </form>
      </div>
    </div>
  </div>

  <script>
    function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));}
    function flash(type, msg) {
      const el = document.getElementById('flash');
      el.innerHTML = `<div class="flash ${esc(type)}">${esc(msg)}</div>`;
      setTimeout(() => el.innerHTML = '', 5000);
    }
    function readQuery() {
      const p = new URLSearchParams(location.search);
      return { verified: p.get('verified'), reset: p.get('reset'), next: p.get('next') };
    }
    (function init() {
      const q = readQuery();
      if (q.verified) flash('ok', 'Email verified. Please sign in.');
      if (q.reset)    flash('info', 'Enter your new password below.');
    })();

    document.getElementById('loginForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const body = Object.fromEntries(new FormData(e.target));
      let r, data;
      try {
        r = await fetch('/auth/login', {
          method: 'POST', headers: { 'content-type': 'application/json' },
          body: JSON.stringify(body),
        });
        data = await r.json().catch(() => ({}));
      } catch (_) {
        flash('err', 'Network error. Try again.');
        return;
      }
      if (!r.ok) {
        // Map common codes to human text. The server also sends a
        // `message` for most cases; we only fall back to a code→message
        // table for ones the server doesn't pre-translate.
        const friendly = data.message
          || ({ IP_COOLDOWN: 'Too many sign-in attempts from this network. Please wait a moment and try again.',
                IP_RATE_LIMITED: 'This network hit the per-hour sign-in limit. Try again later.',
                ACCOUNT_LOCKED: 'This account is temporarily locked. Try again in a few minutes.',
                INVALID_CREDENTIALS: 'Wrong email or password.',
                EMAIL_NOT_VERIFIED: 'Please verify your email first — check your inbox.',
                TWO_FA_REQUIRED: 'Enter the 6-digit code from your authenticator app.',
                SUSPENDED: 'This account is suspended. Contact support.',
              }[data.error])
          || `Sign-in failed (${data.error || r.status})`;
        if (data.error === 'IP_COOLDOWN' && data.retry_after) {
          // Live countdown. Disable the submit button so the user
          // doesn't double-tap and extend the cooldown.
          const btn = e.target.querySelector('button[type=submit]');
          let s = data.retry_after;
          btn.disabled = true;
          const tick = () => {
            if (s <= 0) { btn.disabled = false; flash('info', 'You can try signing in again now.'); return; }
            flash('err', `Too many sign-in attempts from this network. Try again in ${s} second${s === 1 ? '' : 's'}.`);
            s--;
            setTimeout(tick, 1000);
          };
          tick();
          return;
        }
        flash('err', friendly);
        return;
      }
      const q = readQuery();
      location.href = q.next || '/dashboard/';
    });

    document.getElementById('forgotLink').onclick = (e) => {
      e.preventDefault();
      document.getElementById('forgotBox').classList.toggle('hidden');
    };
    document.getElementById('forgotForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const body = Object.fromEntries(new FormData(e.target));
      const r = await fetch('/auth/forgot', {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await r.json();
      flash(data.ok ? 'ok' : 'err', data.message || 'If that email is registered, a reset link has been sent.');
    });

    // handle reset token in URL — show password set form
    (function resetHandler() {
      const q = readQuery();
      if (!q.reset) return;
      const f = document.getElementById('loginForm');
      f.innerHTML = `
        <input type="hidden" name="token" value="${esc(q.reset)}" />
        <div class="field"><label>New password</label>
          <input type="password" name="password" required minlength="10" />
          <small class="muted">Min 10 characters, must include a number and symbol.</small>
        </div>
        <button type="submit" style="width:100%">Set new password</button>
      `;
      f.onsubmit = async (e) => {
        e.preventDefault();
        const body = Object.fromEntries(new FormData(e.target));
        const r = await fetch('/auth/reset', {
          method: 'POST', headers: { 'content-type': 'application/json' },
          body: JSON.stringify(body),
        });
        const data = await r.json();
        if (!r.ok) { flash('err', data.message || 'Reset failed'); return; }
        flash('ok', 'Password set. Sign in with your new password.');
        setTimeout(() => location.href = '/login', 1500);
      };
    })();
  </script>
</body>
</html>
