---
import Layout from "../../layouts/Layout.astro";
import type { Locale } from "../../i18n/config";
import { useTranslations } from "../../i18n/ui";

const lang: Locale = "de";
const t = useTranslations(lang);
---
<Layout title="Mein Konto" description="Gastbestellung oder Kundenkonto bei Van's DIY & Bastelbedarf." lang={lang} path="/konto/">
  <section class="section-tight">
    <div class="container">
      <span class="eyebrow">{t.account.eyebrow}</span>
      <h1>{t.account.title}</h1>
    </div>
  </section>

  <section class="section-tight">
    <div class="container grid grid-2 account-grid">
      <form class="frm card" id="login-form">
        <h2>{t.account.loginTitle}</h2>

        {/* Echtes Google-/PayPal-Login (OAuth 2.0 + PKCE, server-seitig geprüft — siehe
            functions/api/auth/ + functions/_shared/oauth.js). Ganz normale Links, kein JS
            nötig, damit der Login auch ohne JavaScript funktioniert (progressive enhancement).
            Apple bewusst NICHT dabei — auf ausdrücklichen Wunsch entfernt (kostet 99 $/Jahr
            Apple-Entwicklerprogramm allein für den Web-Login, siehe Vault-Notiz). */}
        <div class="social-login">
          <p class="small" style="margin:0 0 -0.2rem;">{t.account.socialHeading}</p>
          <a class="btn-social btn-social-google" href="/api/auth/google/start">
            <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true"><path fill="#FFC107" d="M43.611,20.083H42V20H24v8h11.303c-1.649,4.657-6.08,8-11.303,8c-6.627,0-12-5.373-12-12c0-6.627,5.373-12,12-12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C12.955,4,4,12.955,4,24c0,11.045,8.955,20,20,20c11.045,0,20-8.955,20-20C44,22.659,43.862,21.35,43.611,20.083z"/><path fill="#FF3D00" d="M6.306,14.691l6.571,4.819C14.655,15.108,18.961,12,24,12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C16.318,4,9.656,8.337,6.306,14.691z"/><path fill="#4CAF50" d="M24,44c5.166,0,9.86-1.977,13.409-5.192l-6.19-5.238C29.211,35.091,26.715,36,24,36c-5.202,0-9.619-3.317-11.283-7.946l-6.522,5.025C9.505,39.556,16.227,44,24,44z"/><path fill="#1976D2" d="M43.611,20.083H42V20H24v8h11.303c-0.792,2.237-2.231,4.166-4.087,5.571c0.001-0.001,0.002-0.001,0.003-0.002l6.19,5.238C36.971,39.205,44,34,44,24C44,22.659,43.862,21.35,43.611,20.083z"/></svg>
            {t.account.socialGoogle}
          </a>
          <a class="btn-social btn-social-paypal" href="/api/auth/paypal/start">
            <span class="social-icon-badge" aria-hidden="true">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="#fff" aria-hidden="true"><path d="M15.607 4.653H8.941L6.645 19.251H1.82L4.862 0h7.995c3.754 0 6.375 2.294 6.473 5.513-.648-.478-2.105-.86-3.722-.86m6.57 5.546c0 3.41-3.01 6.853-6.958 6.853h-2.493L11.595 24H6.74l1.845-11.538h3.592c4.208 0 7.346-3.634 7.153-6.949a5.24 5.24 0 0 1 2.848 4.686M9.653 5.546h6.408c.907 0 1.942.222 2.363.541-.195 2.741-2.655 5.483-6.441 5.483H8.714Z"></path></svg>
            </span>
            {t.account.socialPaypal}
          </a>
          <p class="small social-note" id="social-note" role="alert" aria-live="assertive" style="display:none;"></p>
        </div>

        <div class="social-divider">{t.account.orDivider}</div>

        <div><label for="login-email">{t.account.email}</label><input id="login-email" type="email" required autocomplete="email" /></div>
        <div>
          <label for="login-pw">{t.account.password}</label>
          <div class="pw-field">
            <input id="login-pw" type="password" autocomplete="current-password" />
            <button
              type="button"
              class="pw-toggle"
              id="login-pw-toggle"
              data-show-label={t.account.showPassword}
              data-hide-label={t.account.hidePassword}
              aria-label={t.account.showPassword}
              aria-pressed="false"
            >
              <svg id="login-pw-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7Z"></path><circle cx="12" cy="12" r="3"></circle></svg>
            </button>
          </div>
        </div>

        <div class="checkbox-row">
          <input id="login-remember" type="checkbox" />
          <label for="login-remember">{t.account.rememberMe}</label>
        </div>

        <button class="btn btn-primary btn-block" type="submit">{t.account.loginButton}</button>
        <p class="small" id="login-error" role="alert" aria-live="assertive" style="display:none; color: var(--c-sale);">{t.account.loginError}</p>
        <a class="small" href="#">{t.account.forgotPassword}</a>

        <p class="small login-consent">{t.account.consentPrefix} <a href="/datenschutz/">{t.account.consentLink}</a>{t.account.consentSuffix}</p>
      </form>

      <div class="card">
        <h2>{t.account.newTitle}</h2>
        <p class="small">{t.account.newText}</p>
        <a class="btn btn-outline btn-block" href="/shop/">{t.account.guestButton}</a>
      </div>
    </div>
  </section>

  {/* Direkter Vorschau-Link auf den Kundenbereich für VanVan (und für uns zum Weiterarbeiten) —
      loggt clientseitig mit einem Demo-Konto ein und leitet direkt zum Dashboard weiter, ganz
      ohne das Formular jedes Mal neu auszufüllen. Rein clientseitig/localStorage, siehe
      scripts/account.ts — es werden keine echten Kundendaten angelegt. */}
  <section class="section-tight">
    <div class="container">
      <a class="small" href="#" id="preview-link" data-preview-name={t.account.previewName}>{t.account.previewLink}</a>
    </div>
  </section>

  <section class="section-tight">
    <div class="container">
      <p class="todo-note">{t.account.todoNote}</p>
    </div>
  </section>
</Layout>

<script define:vars={{ loginErrorUnconfigured: t.account.loginErrorUnconfigured, loginErrorDenied: t.account.loginErrorDenied, loginErrorGeneric: t.account.loginErrorGeneric, langParam: "" }}>
  window.__loginVars = { loginErrorUnconfigured, loginErrorDenied, loginErrorGeneric, langParam };
</script>
<script>
  import { login, setName, isLoggedIn } from "../../scripts/account";
  const { loginErrorUnconfigured, loginErrorDenied, loginErrorGeneric, langParam } = (window as any).__loginVars;

  const form = document.getElementById("login-form") as HTMLFormElement | null;
  const emailInput = document.getElementById("login-email") as HTMLInputElement | null;
  const error = document.getElementById("login-error");

  form?.addEventListener("submit", (e) => {
    e.preventDefault();
    const email = emailInput?.value.trim() ?? "";
    if (!email) {
      if (error) error.style.display = "block";
      return;
    }
    login(email);
    window.location.href = "/konto/angemeldet/";
  });

  // Vorschau-Link: meldet mit einem Demo-Namen an und leitet direkt zum Kundenbereich weiter.
  document.getElementById("preview-link")?.addEventListener("click", (e) => {
    e.preventDefault();
    const link = document.getElementById("preview-link") as HTMLAnchorElement | null;
    login("vorschau@vans-diy-bastelbedarf.de");
    if (link?.dataset.previewName) setName(link.dataset.previewName);
    window.location.href = "/konto/angemeldet/";
  });

  // Passwort-Sichtbarkeits-Toggle — rein clientseitig, braucht kein Backend.
  const pwInput = document.getElementById("login-pw") as HTMLInputElement | null;
  const pwToggle = document.getElementById("login-pw-toggle") as HTMLButtonElement | null;
  const EYE_OPEN = `<path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7Z"></path><circle cx="12" cy="12" r="3"></circle>`;
  const EYE_CLOSED = `<path d="M3 3l18 18"></path><path d="M10.6 10.6a2 2 0 0 0 2.8 2.8"></path><path d="M9.9 4.24A9.9 9.9 0 0 1 12 4c7 0 11 7 11 7a13.2 13.2 0 0 1-3.4 4.06M6.1 6.1C3.5 7.9 1 12 1 12s4 7 11 7a9.9 9.9 0 0 0 4.9-1.24"></path>`;
  pwToggle?.addEventListener("click", () => {
    if (!pwInput) return;
    const showing = pwInput.type === "text";
    pwInput.type = showing ? "password" : "text";
    pwToggle.setAttribute("aria-pressed", String(!showing));
    pwToggle.setAttribute("aria-label", showing ? (pwToggle.dataset.showLabel ?? "") : (pwToggle.dataset.hideLabel ?? ""));
    const icon = document.getElementById("login-pw-icon");
    if (icon) icon.innerHTML = showing ? EYE_OPEN : EYE_CLOSED;
  });

  // Echtes Google-/PayPal-Login: Sprache als Query-Parameter mitgeben, damit der Rückweg (siehe
  // functions/_shared/oauth-handlers.js) auf die richtige Sprachversion von /konto/angemeldet/
  // zurückführt.
  document.querySelectorAll<HTMLAnchorElement>(".btn-social").forEach((a) => {
    if (langParam) a.href = a.href + "?lang=" + langParam;
  });

  // Fehler-Rückmeldung vom echten OAuth-Ablauf (siehe functions/_shared/oauth-handlers.js) —
  // kommt als ?login_error=... in der URL zurück, wenn z.B. noch keine Google-/PayPal-
  // Zugangsdaten hinterlegt sind oder die Anmeldung abgebrochen wurde.
  const params = new URLSearchParams(window.location.search);
  const loginErrorCode = params.get("login_error");
  if (loginErrorCode) {
    const note = document.getElementById("social-note");
    if (note) {
      let msg = loginErrorGeneric;
      if (loginErrorCode.includes("unconfigured")) msg = loginErrorUnconfigured;
      else if (loginErrorCode.includes("denied")) msg = loginErrorDenied;
      note.textContent = msg;
      note.style.display = "block";
    }
  }

  // Schon eine gültige echte Sitzung? Dann direkt zum Dashboard weiterleiten, statt das
  // Login-Formular nochmal anzuzeigen.
  if (!isLoggedIn()) {
    fetch("/api/account/me")
      .then((r) => r.json())
      .then((data) => {
        if (data?.ok && data.customer) {
          login(data.customer.email);
          if (data.customer.name) setName(data.customer.name);
          window.location.href = "/konto/angemeldet/";
        }
      })
      .catch(() => {});
  }
</script>
