<script lang="ts">
  import { onMount } from 'svelte';
  import { authApi, setToken, getToken, clearToken } from './lib/api';
  import { toasts } from './lib/stores';
  import GuideReader from './components/GuideReader.svelte';

  let authenticated = false;
  let checking = true;
  let email = '';
  let password = '';
  let showPassword = false;
  let loginError = '';
  let loggingIn = false;
  let userInfo: { email: string; role: string } | null = null;

  function decodeJwt(t: string): { email: string; role: string } | null {
    try {
      const p = JSON.parse(atob(t.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
      return { email: p.email ?? '', role: p.role ?? '' };
    } catch { return null; }
  }

  async function checkAuth() {
    const t = getToken();
    if (!t) { checking = false; return; }
    try {
      await authApi.get('/api/users/me', { headers: { Authorization: `Bearer ${t}` } });
      authenticated = true;
      userInfo = decodeJwt(t);
    } catch {
      clearToken();
    } finally {
      checking = false;
    }
  }

  async function login() {
    loginError = '';
    loggingIn = true;
    try {
      const res = await authApi.post('/api/login', { email, password, rememberMe: false });
      const token = res.data.token;
      if (!token) throw new Error('No token in response');
      setToken(token);
      userInfo = decodeJwt(token);
      authenticated = true;
    } catch (e: any) {
      loginError = e?.response?.data?.message ?? 'Invalid email or password.';
    } finally {
      loggingIn = false;
    }
  }

  function logout() { clearToken(); authenticated = false; userInfo = null; }

  onMount(checkAuth);
</script>

{#if checking}
  <div class="splash"><div class="spinner"></div></div>
{:else if !authenticated}
  <div class="login-wrap">
    <div class="login-card">
      <div class="login-logo">
        <img src="/hiveiq_logo.png" alt="HiveIQ" />
      </div>
      <h1>HiveIQ Guide</h1>
      <p class="login-sub">Sign in with your HiveOps account</p>

      {#if loginError}
        <div class="login-error">{loginError}</div>
      {/if}

      <div class="form-group">
        <label for="email">Email</label>
        <input id="email" type="email" bind:value={email} on:keydown={e => e.key === 'Enter' && login()} placeholder="you@example.com" />
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <div class="pw-wrap">
          <input id="password" type={showPassword ? 'text' : 'password'} value={password} on:input={e => password = e.currentTarget.value} on:keydown={e => e.key === 'Enter' && login()} placeholder="••••••••" />
          <button type="button" class="pw-toggle" on:click={() => showPassword = !showPassword} aria-label={showPassword ? 'Hide password' : 'Show password'}>
            {showPassword ? 'Hide' : 'Show'}
          </button>
        </div>
      </div>
      <button class="btn btn-primary btn-md login-btn" on:click={login} disabled={loggingIn}>
        {loggingIn ? 'Signing in…' : 'Sign In'}
      </button>
    </div>
  </div>
{:else}
  <GuideReader on:logout={logout} userEmail={userInfo?.email ?? ''} userRole={userInfo?.role ?? ''} />
{/if}

<!-- Toast notifications -->
<div class="toast-stack">
  {#each $toasts as t (t.id)}
    <div class="toast toast-{t.type}">
      <strong>{t.title}</strong>{#if t.message}<span>{t.message}</span>{/if}
    </div>
  {/each}
</div>

<style>
  .splash { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
  .spinner { width: 36px; height: 36px; border: 3px solid #e5e7eb; border-top-color: #2563eb; border-radius: 50%; animation: spin 0.7s linear infinite; }
  @keyframes spin { to { transform: rotate(360deg); } }

  .login-wrap { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: linear-gradient(160deg, #0b1220 0%, #0f1e3d 100%); }
  .login-card { background: #1e293b; border: 1px solid #334155; border-radius: 12px; box-shadow: 0 8px 40px rgba(0,0,0,0.45); padding: 40px; width: 380px; }
  .login-logo { text-align: center; margin-bottom: 16px; }
  .login-logo img { height: 40px; filter: brightness(0) invert(1); }
  h1 { text-align: center; font-size: 1.4rem; color: #f1f5f9; margin-bottom: 4px; }
  .login-sub { text-align: center; color: #94a3b8; font-size: 0.875rem; margin-bottom: 24px; }
  .login-error { background: #3b1a1a; border: 1px solid #7f1d1d; border-radius: 6px; color: #fca5a5; font-size: 0.85rem; padding: 10px 12px; margin-bottom: 16px; }
  .form-group { display: flex; flex-direction: column; gap: 5px; margin-bottom: 16px; }
  .form-group label { font-size: 0.82rem; font-weight: 600; color: #cbd5e1; }
  .form-group input { padding: 9px 12px; border: 1px solid #334155; border-radius: 6px; font-size: 0.875rem; color: #e2e8f0; background: #0f172a; width: 100%; box-sizing: border-box; }
  .form-group input::placeholder { color: #64748b; }
  .form-group input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 2px rgba(59,130,246,0.25); }
  .pw-wrap { position: relative; display: flex; align-items: center; }
  .pw-wrap input { padding-right: 60px; }
  .pw-toggle { position: absolute; right: 8px; background: none; border: none; color: #93c5fd; font-size: 0.78rem; font-weight: 600; cursor: pointer; padding: 4px 6px; }
  .pw-toggle:hover { color: #bfdbfe; text-decoration: underline; }
  .login-btn { width: 100%; margin-top: 8px; }
  .splash { background: #0b1220; }

  .toast-stack { position: fixed; bottom: 24px; right: 24px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; }
  .toast { padding: 10px 16px; border-radius: 8px; font-size: 0.85rem; display: flex; gap: 8px; align-items: baseline; box-shadow: 0 4px 12px rgba(0,0,0,0.12); animation: fadeIn 0.2s ease; }
  @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
  .toast-success { background: #dcfce7; color: #166534; border: 1px solid #86efac; }
  .toast-error   { background: #fef2f2; color: #b91c1c; border: 1px solid #fca5a5; }
  .toast-info    { background: #eff6ff; color: #1e40af; border: 1px solid #93c5fd; }
</style>
