<template>
  <div class="min-h-screen relative flex items-center justify-center p-4 overflow-hidden bg-gradient-hero">
    <div class="absolute inset-0 grid-pattern opacity-40" />
    <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-primary/10 rounded-full blur-[120px]" />

    <div
      v-motion
      :initial="{ opacity: 0, y: 20 }"
      :enter="{ opacity: 1, y: 0 }"
      class="w-full max-w-[440px] relative z-10"
    >
      <!-- Top bar -->
      <div class="mb-8 flex items-center justify-between">
        <RouterLink to="/" class="inline-flex items-center text-xs font-medium text-muted-foreground hover:text-primary transition-colors gap-2 px-1 py-1">
          <ArrowLeft class="w-3.5 h-3.5" />{{ t("auth.back") }}
        </RouterLink>
        <LanguageSwitcher />
      </div>

      <div class="flex justify-center mb-10 text-center flex-col items-center">
        <Logo />
        <p class="text-[10px] uppercase tracking-[0.2em] text-muted-foreground mt-2 opacity-50">{{ t("auth.studio") }}</p>
      </div>

      <div class="bg-card/40 backdrop-blur-xl border border-border/50 rounded-3xl p-8 shadow-card overflow-hidden">
        <div class="text-center mb-8">
          <h1 class="font-display text-2xl font-bold mb-2">{{ getTitle() }}</h1>
          <Transition mode="out-in" enter-active-class="transition duration-150" enter-from-class="opacity-0 translate-y-1" enter-to-class="opacity-100 translate-y-0" leave-active-class="transition duration-100" leave-from-class="opacity-100" leave-to-class="opacity-0 -translate-y-1">
            <p :key="mode" class="text-muted-foreground text-sm">{{ getSubtitle() }}</p>
          </Transition>
        </div>

        <!-- Captcha Warning -->
        <div v-if="requiresCaptcha && mode === 'login'" 
          class="mb-6 p-3 bg-amber-500/10 border border-amber-500/20 rounded-xl flex items-center gap-3 animate-in fade-in slide-in-from-top-2">
          <ShieldAlert class="w-5 h-5 text-amber-500" />
          <p class="text-[11px] font-semibold text-amber-500">{{ t("nav.captcha_required") }}</p>
        </div>

        <form @submit.prevent="handleSubmit" class="space-y-5">
          <!-- Email -->
          <div v-if="mode !== 'reset'" class="space-y-2">
            <label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground ml-1">{{ t("auth.fields.email") }}</label>
            <div class="relative group">
              <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-muted-foreground group-focus-within:text-primary transition-colors">
                <Mail class="w-4 h-4" />
              </div>
              <input v-model="formData.email" type="email" required placeholder="john@example.com"
                class="w-full bg-background/50 border border-border/50 rounded-xl pl-11 pr-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm" />
            </div>
          </div>

          <!-- Captcha Field -->
          <div v-if="mode === 'login' && requiresCaptcha" class="space-y-2 animate-in zoom-in-95">
             <label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground ml-1">{{ t("auth.fields.captcha_label") }}</label>
             <div class="relative group">
               <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-muted-foreground group-focus-within:text-primary transition-colors">
                 <ShieldCheck class="w-4 h-4" />
               </div>
               <input v-model="formData.captcha" type="text" :placeholder="t('auth.fields.captcha_placeholder')"
                 class="w-full bg-background/50 border border-border/50 rounded-xl pl-11 pr-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm" />
             </div>
          </div>

          <!-- Reset Token -->
          <div v-if="mode === 'reset'" class="space-y-2">
            <label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground ml-1">{{ t("auth.reset.token") }}</label>
            <div class="relative group">
              <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-muted-foreground group-focus-within:text-primary transition-colors">
                <KeyRound class="w-4 h-4" />
              </div>
              <input v-model="formData.token" type="text" required
                class="w-full bg-background/50 border border-border/50 rounded-xl pl-11 pr-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm" />
            </div>
          </div>

          <!-- Register extra fields -->
          <div v-if="mode === 'register'" class="space-y-4">
            <!-- Account Type Selector -->
            <div class="space-y-2">
              <label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground ml-1">{{ t("auth.fields.accountType") }}</label>
              <div class="flex p-1 bg-background/50 border border-border/50 rounded-2xl gap-1">
                <button type="button" @click="formData.is_company = false"
                  :class="['flex-1 px-4 py-2 rounded-xl text-[11px] font-bold uppercase transition-all', !formData.is_company ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:bg-white/5']">
                  {{ t("auth.fields.individual") }}
                </button>
                <button type="button" @click="formData.is_company = true"
                  :class="['flex-1 px-4 py-2 rounded-xl text-[11px] font-bold uppercase transition-all', formData.is_company ? 'bg-primary text-primary-foreground shadow-sm' : 'text-muted-foreground hover:bg-white/5']">
                  {{ t("auth.fields.company") }}
                </button>
              </div>
            </div>

            <div class="grid grid-cols-2 gap-3">
              <div class="space-y-1.5">
                <label class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 ml-1">{{ t("upload.firstName") }}</label>
                <input v-model="formData.firstName" type="text"
                  class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-1 focus:ring-primary/30 text-sm" />
              </div>
              <div class="space-y-1.5">
                <label class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 ml-1">{{ t("upload.lastName") }}</label>
                <input v-model="formData.lastName" type="text"
                  class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-1 focus:ring-primary/30 text-sm" />
              </div>
            </div>
            <div class="space-y-1.5">
              <label class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 ml-1">{{ t("upload.phone") }}</label>
              <input v-model="formData.phone" type="tel"
                class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-1 focus:ring-primary/30 text-sm" />
            </div>
            <div class="space-y-1.5">
              <label class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 ml-1">{{ t("upload.shippingAddress") }}</label>
              <textarea v-model="formData.address" rows="2"
                class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-1 focus:ring-primary/30 text-sm resize-none" />
            </div>

            <!-- Company specific fields -->
            <Transition enter-active-class="transition duration-200" enter-from-class="opacity-0 -translate-y-2" enter-to-class="opacity-100 translate-y-0">
               <div v-if="formData.is_company" class="space-y-4 pt-4 border-t border-border/50">
                  <div class="space-y-1.5">
                    <label class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 ml-1">{{ t("auth.fields.companyName") }}</label>
                    <input v-model="formData.company_name" type="text" :required="formData.is_company"
                      class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-1 focus:ring-primary/30 text-sm" />
                  </div>
                  <div class="space-y-1.5">
                    <label class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 ml-1">{{ t("auth.fields.companyPIB") }}</label>
                    <input v-model="formData.company_pib" type="text" :required="formData.is_company"
                      class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-1 focus:ring-primary/30 text-sm" />
                  </div>
                  <div class="space-y-1.5">
                    <label class="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 ml-1">{{ t("auth.fields.companyAddress") }}</label>
                    <textarea v-model="formData.company_address" rows="2"
                      class="w-full bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-1 focus:ring-primary/30 text-sm resize-none" />
                  </div>
               </div>
            </Transition>
          </div>

          <!-- Password -->
          <div v-if="mode !== 'forgot'" class="space-y-5">
            <div class="space-y-2 pt-2">
              <div class="flex justify-between items-center px-1">
                <label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                  {{ mode === "reset" ? t("auth.fields.newPassword") : t("auth.fields.password") }}
                </label>
                <button v-if="mode === 'login'" type="button" @click="mode = 'forgot'"
                  class="text-[11px] text-primary hover:underline font-medium">{{ t("auth.forgot.link") }}</button>
              </div>
              <div class="relative group">
                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-muted-foreground group-focus-within:text-primary transition-colors">
                  <Lock class="w-4 h-4" />
                </div>
                <input v-model="formData.password" type="password" required placeholder="••••••••"
                  class="w-full bg-background/50 border border-border/50 rounded-xl pl-11 pr-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm" />
              </div>
            </div>

            <div v-if="mode === 'register' || mode === 'reset'" class="space-y-2">
              <label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground ml-1">{{ t("auth.fields.confirmPassword") }}</label>
              <div class="relative group">
                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-muted-foreground group-focus-within:text-primary transition-colors">
                  <ShieldCheck class="w-4 h-4" />
                </div>
                <input v-model="formData.confirmPassword" type="password" required placeholder="••••••••"
                  class="w-full bg-background/50 border border-border/50 rounded-xl pl-11 pr-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all text-sm" />
              </div>
            </div>
          </div>

          <Button type="submit" variant="hero" class="w-full mt-4" :disabled="isLoading">
            <Loader2 v-if="isLoading" class="w-5 h-5 animate-spin" />
            <template v-else>
              <span>
                {{ mode === "login" ? t("auth.login.submit") : "" }}
                {{ mode === "register" ? t("auth.register.submit") : "" }}
                {{ mode === "forgot" ? t("auth.forgot.submit") : "" }}
                {{ mode === "reset" ? t("auth.reset.submit") : "" }}
              </span>
              <ArrowRight class="w-4 h-4 ml-2" />
            </template>
          </Button>

          <!-- Social -->
          <div v-if="mode === 'login' || mode === 'register'" class="space-y-4 pt-2">
            <div class="relative">
              <div class="absolute inset-0 flex items-center"><span class="w-full border-t border-border/50" /></div>
              <div class="relative flex justify-center text-[10px] uppercase tracking-widest">
                <span class="bg-card/40 px-2 text-muted-foreground backdrop-blur-md">{{ t("auth.orContinueWith") }}</span>
              </div>
            </div>
            <div class="flex flex-col gap-3">
              <div id="google-login-btn" class="w-full flex justify-center"></div>
            </div>
          </div>
        </form>

        <div class="mt-8 pt-6 border-t border-border/50 text-center">
          <button @click="toggleMode" class="text-sm text-muted-foreground hover:text-primary transition-colors font-medium">
            {{ mode === "login" ? t("auth.login.toggle") : "" }}
            {{ mode === "register" ? t("auth.register.toggle") : "" }}
            {{ (mode === "forgot" || mode === "reset") ? t("auth.forgot.toggle") : "" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { toast } from "vue-sonner";
import { Mail, Lock, ArrowRight, Loader2, ShieldCheck, KeyRound, ArrowLeft, ShieldAlert } from "lucide-vue-next";
import Button from "@/components/ui/button.vue";
import Logo from "@/components/Logo.vue";
import LanguageSwitcher from "@/components/LanguageSwitcher.vue";
import { loginUser, registerUser, forgotPassword, resetPassword, socialLogin } from "@/lib/api";
import { useAuthStore } from "@/stores/auth";
import { currentLanguage } from "@/i18n";

type AuthMode = "login" | "register" | "forgot" | "reset";
const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const mode = ref<AuthMode>("login");
const isLoading = ref(false);
const requiresCaptcha = ref(false);
const formData = reactive({ 
  email: "", 
  password: "", 
  confirmPassword: "", 
  firstName: "", 
  lastName: "", 
  phone: "", 
  address: "", 
  token: "",
  is_company: false,
  company_name: "",
  company_pib: "",
  company_address: "",
  captcha: ""
});

onMounted(() => {
  const token = route.query.token as string;
  if (token) { mode.value = "reset"; formData.token = token; }
  
  // Load Google Identity Services script
  const script = document.createElement('script');
  script.src = 'https://accounts.google.com/gsi/client';
  script.async = true;
  script.defer = true;
  script.onload = initGoogleLogin;
  document.head.appendChild(script);
});

function initGoogleLogin() {
  const google = (window as any).google;
  if (!google) return;

  const clientId = import.meta.env.VITE_GOOGLE_CLIENT_ID;
  if (!clientId) {
    console.warn("GOOGLE_CLIENT_ID not found in environment");
    return;
  }

  google.accounts.id.initialize({
    client_id: clientId,
    callback: handleGoogleResponse,
    auto_select: false,
    cancel_on_tap_outside: true,
  });

  google.accounts.id.renderButton(
    document.getElementById("google-login-btn"),
    { 
      type: "standard",
      theme: "outline", 
      size: "large", 
      text: "continue_with",
      shape: "rectangular",
      logo_alignment: "left",
      width: "100%"
    }
  );
}


async function handleGoogleResponse(response: any) {
  isLoading.value = true;
  try {
    const res = await socialLogin({
      provider: "google",
      token: response.credential,
      preferred_language: currentLanguage()
    });
    
    localStorage.setItem("token", res.access_token);
    await authStore.refreshUser();
    toast.success(t("auth.toasts.welcomeBack"));
    
    // Redirect with language prefix
    const lang = i18n.global.locale.value;
    router.push(`/${lang}/`);
  } catch (err: any) {
    toast.error(err.message || "Google Login failed");
  } finally {
    isLoading.value = false;
  }
}

function getTitle() {
  return { login: t("auth.login.title"), register: t("auth.register.title"), forgot: t("auth.forgot.title"), reset: t("auth.reset.title") }[mode.value];
}
function getSubtitle() {
  return { login: t("auth.login.subtitle"), register: t("auth.register.subtitle"), forgot: t("auth.forgot.subtitle"), reset: t("auth.reset.subtitle") }[mode.value];
}
function toggleMode() {
  requiresCaptcha.value = false;
  if (mode.value === "login") mode.value = "register";
  else if (mode.value === "register") mode.value = "login";
  else mode.value = "login";
}

async function handleSubmit() {
  if ((mode.value === "register" || mode.value === "reset") && formData.password !== formData.confirmPassword) {
    toast.error(t("auth.toasts.passwordsNoMatch")); return;
  }
  isLoading.value = true;
  try {
    if (mode.value === "login") {
      // For our MOCK captcha, we send 'valid-captcha-token' if the text matches (case-insensitive)
      const captchaToken = formData.captcha.trim().toLowerCase() === "radionica3d" ? "valid-captcha-token" : formData.captcha;
      
      const res = await loginUser({ 
        email: formData.email, 
        password: formData.password,
        captcha_token: requiresCaptcha.value ? captchaToken : undefined
      });
      localStorage.setItem("token", res.access_token);
      await authStore.refreshUser();
      toast.success(t("auth.toasts.welcomeBack"));
      router.push("/");
    } else if (mode.value === "register") {
      await registerUser({ 
        email: formData.email, 
        password: formData.password, 
        first_name: formData.firstName, 
        last_name: formData.lastName, 
        phone: formData.phone, 
        shipping_address: formData.address, 
        preferred_language: currentLanguage(),
        is_company: formData.is_company,
        company_name: formData.is_company ? formData.company_name : null,
        company_pib: formData.is_company ? formData.company_pib : null,
        company_address: formData.is_company ? formData.company_address : null
      });
      toast.success(t("auth.toasts.accountCreated"));
      mode.value = "login";
    } else if (mode.value === "forgot") {
      const res = await forgotPassword(formData.email);
      toast.success(t("auth.toasts.resetLinkSent"));
      if (res.demo_token) { formData.token = res.demo_token; mode.value = "reset"; }
    } else if (mode.value === "reset") {
      await resetPassword({ token: formData.token, new_password: formData.password });
      toast.success(t("auth.toasts.passwordChanged"));
      mode.value = "login";
    }
  } catch (err: any) {
    if (err.message.includes("captcha") || err.message.includes("подтверждение") || err.message.includes("капча")) {
      requiresCaptcha.value = true;
    }
    toast.error(err.message);
  } finally {
    isLoading.value = false;
  }
}
</script>
