"use client";
import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import styled from "styled-components";
import { BackgroundRippleEffect } from "@/components/layout/BackgroundRippleEffect";
import Shuffle from "@/components/ui/Shuffle";
import ColourfulText from "@/components/ui/colourful-text";
import { PlaceholdersAndVanishInput } from "@/components/ui/placeholders-and-vanish-input";
import { MultiStepLoader } from "@/components/ui/multi-step-loader";
import { IPhoneNotification } from "@/components/ui/iphone-notification";
import { parseEbayAccount } from "@/services/ebayParserService";
import { createManagedAccount, fetchManagedAccounts } from "@/services/accountsService";
import { account, databases, databaseId, usersCollectionId } from "@/lib/appwrite";
import { DottedGlowBackground } from "@/components/ui/dotted-glow-background";

const StyledDownloadButton = styled.div`
  .button {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 5.3em;
    height: 5.3em;
    border: none;
    cursor: pointer;
    border-radius: 0.4em;
    background: rgba(66, 67, 67, 0.6);
    text-decoration: none;
  }

  .container {
    position: relative;
    width: 3.5em;
    height: 3.1em;
    background: none;
    overflow: hidden;
  }

  .folder {
    content: "";
    position: absolute;
  }

  .folder_one {
    bottom: 0;
    width: 100%;
    height: 88%;
    border-radius: 3px;
    border-top: 2px solid rgb(206, 167, 39);
    background: linear-gradient(-35deg, rgb(238, 194, 47) 5%, rgb(255, 223, 118));
  }

  .folder_two {
    top: 5%;
    width: 38%;
    height: 19%;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    background-color: rgb(206, 167, 39);
    box-shadow: 0 1px 5px -2px rgba(0, 0, 0, 0.5);
  }

  .folder_two::before {
    content: "";
    position: absolute;
    display: inline;
    left: 88%;
    width: 0;
    height: 0;
    border-left: 7px solid rgb(206, 167, 39);
    border-top: 0.3em solid transparent;
    border-bottom: 0.3em solid transparent;
  }

  .folder_three {
    display: flex;
    align-items: center;
    justify-content: center;
    left: 0.5em;
    bottom: 0;
    width: 2.5em;
    height: 0.9em;
    border-radius: 4px 4px 0 0;
    background: linear-gradient(-35deg, rgb(25, 102, 218), rgb(109, 165, 249));
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
  }

  .folder_four {
    left: 1em;
    bottom: 0.3em;
    width: 1.5em;
    height: 0.18em;
    border-radius: 1em;
    background-color: rgb(20, 77, 163);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .active_line {
    content: "";
    position: absolute;
    bottom: 0;
    width: 0.9em;
    height: 0.4em;
    background-color: #999;
    border: none;
    border-radius: 1em;
    transition: all 0.15s linear;
  }

  .button:active .active_line,
  .button:focus .active_line {
    width: 2.3em;
    background-color: rgb(41, 126, 255);
  }

  .button:focus .container {
    animation: wow 1s forwards;
  }

  @keyframes wow {
    20% {
      scale: 0.8;
    }

    30% {
      scale: 1;
      transform: translateY(0);
    }

    50% {
      transform: translateY(-6px);
    }

    65% {
      transform: translateY(4px);
    }

    80% {
      transform: translateY(0);
    }

    100% {
      scale: 1;
    }
  }

  .text {
    content: "";
    position: absolute;
    top: -4.5em;
    width: 7.7em;
    height: 2.6em;
    background-color: #666;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    border: none;
    border-radius: 5px;
    text-shadow: 0 0 10px rgb(0, 0, 0);
    opacity: 0;
    transition: all 0.25s linear;
    font-size: 0.7em;
    white-space: nowrap;
    padding: 0 0.5em;
  }

  .button:hover .text {
    opacity: 1;
  }
`;

export const OnboardingGate = ({ userName, onStart, loading, error, initialPhase = "welcome" }) => {
  const [phase, setPhase] = useState(initialPhase);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [showNotification, setShowNotification] = useState(false);
  const [notificationMessage, setNotificationMessage] = useState("bitte eine gueltige url verwenden!");
  const [skipHovered, setSkipHovered] = useState(false);
  const [extensionDetected, setExtensionDetected] = useState(false);
  const extensionCheckIntervalRef = useRef(null);
  const [showManualContinue, setShowManualContinue] = useState(false);
  const [extensionDownloaded, setExtensionDownloaded] = useState(false);
  const [userExtensionLoaded, setUserExtensionLoaded] = useState(false);

  const loadingStates = [
    { text: "URL wird verarbeitet..." },
    { text: "Account-Daten werden geladen..." },
    { text: "Account wird erstellt..." },
    { text: "Fast fertig..." },
  ];

  const placeholders = [
    "Gib deine eBay-Account-URL ein...",
    "z.B. https://www.ebay.de/str/username",
    "Paste deine eBay Shop-URL hier...",
  ];

  // PostMessage Listener - MUSS IMMER aktiv sein (nicht nur in extension Phase)
  // damit wir auch Nachrichten empfangen, wenn Extension nach dem Laden installiert wird
  useEffect(() => {
    const handleMessage = (event) => {
      if (event.data?.source === "eship-extension" && event.data?.type === "EXTENSION_ID") {
        setExtensionDetected(true);
        return true;
      }
      return false;
    };

    // Registriere Listener IMMER (nicht nur in extension Phase)
    window.addEventListener("message", handleMessage);

    // Sende sofort mehrere Anfragen beim Mount (falls Extension bereits geladen ist)
    // Wichtig: Mehrfach senden, da Timing variieren kann
    const sendPing = () => {
      window.postMessage({
        source: "eship-webapp",
        type: "PING_EXTENSION",
        requestId: Date.now()
      }, "*");
    };
    
    // Sofort, dann nach kurzen Verzögerungen (für verschiedene Timing-Szenarien)
    sendPing();
    setTimeout(sendPing, 100);
    setTimeout(sendPing, 500);
    setTimeout(sendPing, 1000);
    setTimeout(sendPing, 2000);

    return () => {
      window.removeEventListener("message", handleMessage);
    };
  }, []); // Nur einmal beim Mount - Listener bleibt für die gesamte Lebensdauer aktiv

  // Extension-Erkennung: Prüfe window.__EBAY_EXTENSION__ und postMessage
  useEffect(() => {
    if (phase !== "extension") return;

    // Prüfe sofort, ob Extension bereits verfügbar ist
    const checkExtension = () => {
      const hasWindow = typeof window !== 'undefined';
      const ebayExtension = hasWindow ? window.__EBAY_EXTENSION__ : undefined;
      const isDetected = hasWindow && ebayExtension === true;
      
      if (isDetected) {
        setExtensionDetected(true);
        return true;
      }
      return false;
    };

    // Zusätzlicher Listener nur für die extension Phase (für zusätzliche PING-Anfragen)
    // Der globale Listener oben ist bereits aktiv, aber hier senden wir aktive Anfragen

    // Aktive Suche: Sende postMessage an Extension und bitte um Antwort
    const requestExtensionId = () => {
      // Sende eine Nachricht, die der Content Script erkennen sollte
      // Der Content Script sollte darauf antworten
      window.postMessage({
        source: "eship-webapp",
        type: "PING_EXTENSION",
        requestId: Date.now()
      }, "*");
      
      // Zusätzlich: Injiziere ein Script in den Page Context, das nach der Extension sucht
      // Dies funktioniert nur, wenn wir Zugriff auf chrome.runtime haben (was wir nicht haben)
      // Stattdessen: Prüfe, ob ein Script-Tag mit Extension-Marker existiert
      try {
        // Erstelle ein temporäres Script-Element, das postMessage sendet
        const script = document.createElement('script');
        script.textContent = `
          (function() {
            // Prüfe, ob chrome.runtime verfügbar ist (nur im Content Script Context)
            // Da wir im Page Context sind, können wir das nicht direkt prüfen
            // Aber wir können postMessage senden und hoffen, dass der Content Script antwortet
            window.postMessage({
              source: "eship-webapp-page-context",
              type: "PING_EXTENSION",
              requestId: ${Date.now()}
            }, "*");
          })();
        `;
        document.documentElement.appendChild(script);
        document.documentElement.removeChild(script);
      } catch (e) {
        // Script injection failed - ignore
      }
    };

    // Prüfe sofort
    const immediateCheck = checkExtension();
    
    if (immediateCheck) {
      return;
    }

    // Der globale Listener ist bereits aktiv (siehe useEffect oben)
    // Hier starten wir nur das aktive Polling für die extension Phase

    // Aktive Suche: Sende sofort eine Anfrage
    requestExtensionId();

    // Polling-Mechanismus: Prüfe alle 500ms UND sende alle 2 Sekunden eine Anfrage
    extensionCheckIntervalRef.current = setInterval(() => {
      if (checkExtension()) {
        if (extensionCheckIntervalRef.current) {
          clearInterval(extensionCheckIntervalRef.current);
          extensionCheckIntervalRef.current = null;
        }
      }
    }, 500);

    // Aktive Suche: Sende alle 2 Sekunden eine Anfrage an die Extension
    const requestInterval = setInterval(() => {
      if (!extensionDetected) {
        requestExtensionId();
      } else {
        clearInterval(requestInterval);
      }
    }, 2000);

    // Cleanup für requestInterval
    const cleanupRequestInterval = () => {
      clearInterval(requestInterval);
    };

    // Cleanup
    return () => {
      // NICHT window.removeEventListener hier - der globale Listener muss aktiv bleiben!
      if (extensionCheckIntervalRef.current) {
        clearInterval(extensionCheckIntervalRef.current);
        extensionCheckIntervalRef.current = null;
      }
      cleanupRequestInterval();
    };
  }, [phase]);

  // Prüfe beim Mount, ob user_extension_load bereits true ist (nach Reload)
  useEffect(() => {
    const checkUserExtensionLoaded = async () => {
      try {
        const authUser = await account.get();
        if (authUser && databases && databaseId && usersCollectionId) {
          try {
            const userDoc = await databases.getDocument(databaseId, usersCollectionId, authUser.$id);
            if (userDoc.user_extension_load === true) {
              setUserExtensionLoaded(true);
              
              // Prüfe, ob User bereits Accounts hat
              try {
                const existingAccounts = await fetchManagedAccounts(authUser.$id);
                
                // Debug: Log in Browser-Konsole
                console.log("[OnboardingGate] checkUserExtensionLoaded: Accounts-Prüfung", {
                  userId: authUser.$id,
                  accountsArray: existingAccounts,
                  accountsCount: Array.isArray(existingAccounts) ? existingAccounts.length : 0,
                  hasAccounts: Array.isArray(existingAccounts) && existingAccounts.length > 0
                });
                
                // Prüfe explizit: Ist es ein Array und hat es Einträge?
                const hasAccounts = Array.isArray(existingAccounts) && existingAccounts.length > 0;
                
                if (hasAccounts) {
                  // User hat bereits Accounts → direkt zum Dashboard
                  console.log("[OnboardingGate] checkUserExtensionLoaded: Accounts gefunden, rufe onStart() auf", {
                    accountsCount: existingAccounts.length
                  });
                  if (onStart) {
                    onStart();
                  }
                } else {
                  // User hat keine Accounts → zur Input-Phase
                  console.log("[OnboardingGate] checkUserExtensionLoaded: KEINE Accounts gefunden, wechsle zur Input-Phase", {
                    accountsCount: Array.isArray(existingAccounts) ? existingAccounts.length : 0,
                    currentPhase: phase
                  });
                  // Wechsle zur Input-Phase, unabhängig von der aktuellen Phase
                  setTimeout(() => {
                    setPhase("input");
                  }, 1000);
                }
              } catch (accountsErr) {
                // Fehler beim Laden der Accounts → zur Input-Phase
                console.warn("Fehler beim Laden der Accounts:", accountsErr);
                setTimeout(() => {
                  setPhase("input");
                }, 1000);
              }
            } else if (userDoc.user_extension_load === false) {
              // User hat Extension noch nicht geladen → zur Extension-Phase (sofort, ohne Delay)
              console.log("[OnboardingGate] checkUserExtensionLoaded: user_extension_load ist false, wechsle zur Extension-Phase", {
                currentPhase: phase
              });
              if (phase !== "extension") {
                // Setze Phase sofort, ohne Delay
                setPhase("extension");
              }
            }
          } catch (e) {
            // Dokument existiert nicht oder Fehler - ignorieren
          }
        }
      } catch (err) {
        // User nicht eingeloggt oder Fehler - ignorieren
      }
    };
    
    checkUserExtensionLoaded();
  }, []); // Nur einmal beim Mount

  // Prüfe kontinuierlich, ob user_extension_load true wurde (während extension Phase)
  useEffect(() => {
    if (phase !== "extension" || userExtensionLoaded) return;

    const checkInterval = setInterval(async () => {
      try {
        const authUser = await account.get();
        if (authUser && databases && databaseId && usersCollectionId) {
          try {
            const userDoc = await databases.getDocument(databaseId, usersCollectionId, authUser.$id);
            if (userDoc.user_extension_load === true) {
              setUserExtensionLoaded(true);
              
              // Prüfe, ob User bereits Accounts hat
              try {
                const existingAccounts = await fetchManagedAccounts(authUser.$id);
                
                // Debug: Log in Browser-Konsole
                console.log("[OnboardingGate] checkInterval: Accounts-Prüfung", {
                  userId: authUser.$id,
                  accountsArray: existingAccounts,
                  accountsCount: Array.isArray(existingAccounts) ? existingAccounts.length : 0,
                  hasAccounts: Array.isArray(existingAccounts) && existingAccounts.length > 0
                });
                
                // Prüfe explizit: Ist es ein Array und hat es Einträge?
                const hasAccounts = Array.isArray(existingAccounts) && existingAccounts.length > 0;
                
                if (hasAccounts) {
                  // User hat bereits Accounts → direkt zum Dashboard
                  console.log("[OnboardingGate] checkInterval: Accounts gefunden, rufe onStart() auf", {
                    accountsCount: existingAccounts.length
                  });
                  // Interval stoppen, bevor onStart() aufgerufen wird
                  clearInterval(checkInterval);
                  if (onStart) {
                    onStart();
                  }
                } else {
                  // User hat keine Accounts → zur Input-Phase
                  console.log("[OnboardingGate] checkInterval: KEINE Accounts gefunden, wechsle zur Input-Phase", {
                    accountsCount: Array.isArray(existingAccounts) ? existingAccounts.length : 0
                  });
                  // Interval stoppen, bevor zur Input-Phase gewechselt wird
                  clearInterval(checkInterval);
                  setTimeout(() => {
                    setPhase("input");
                  }, 1000);
                }
              } catch (accountsErr) {
                // Fehler beim Laden der Accounts → zur Input-Phase
                console.warn("Fehler beim Laden der Accounts:", accountsErr);
                // Interval stoppen bei Fehler
                clearInterval(checkInterval);
                setTimeout(() => {
                  setPhase("input");
                }, 1000);
              }
            }
          } catch (e) {
            // Dokument existiert nicht oder Fehler - ignorieren
          }
        }
      } catch (err) {
        // User nicht eingeloggt oder Fehler - ignorieren
      }
    }, 2000); // Alle 2 Sekunden prüfen

    return () => clearInterval(checkInterval);
  }, [phase, userExtensionLoaded, onStart]);

  // Zeige manuellen "Weiter"-Button nach 10 Sekunden, wenn Extension nicht erkannt wurde
  useEffect(() => {
    if (phase === "extension" && !extensionDetected && !userExtensionLoaded) {
      const timer = setTimeout(() => {
        setShowManualContinue(true);
      }, 10000); // 10 Sekunden
      return () => clearTimeout(timer);
    } else {
      setShowManualContinue(false);
    }
  }, [phase, extensionDetected, userExtensionLoaded]);

  // Automatischer Übergang zu "input" Phase, wenn Extension erkannt wurde
  useEffect(() => {
    if (phase === "extension" && extensionDetected) {
      // Warte 1-2 Sekunden, dann wechsle zur input Phase
      const timer = setTimeout(() => {
        setPhase("input");
      }, 1500);
      return () => clearTimeout(timer);
    }
  }, [phase, extensionDetected]);

  const handleManualContinue = () => {
    setPhase("input");
  };

  const handleOverlayClick = async (e) => {
    // Only handle clicks on the overlay itself or when in welcome phase
    if (phase === "welcome") {
      // Create user document first (but don't call onStart, as that would hide the gate)
      // We need to create it directly to ensure it exists for account creation later
      try {
        const authUser = await account.get();
        if (authUser && databases && databaseId && usersCollectionId) {
          try {
            await databases.createDocument(
              databaseId,
              usersCollectionId,
              authUser.$id,
              {
                user_name: authUser.name || "User",
                user_extension_load: false
              }
            );
          } catch (docErr) {
            // 409 Conflict means document already exists - that's ok
            if (docErr.code !== 409 && docErr.type !== 'document_already_exists') {
              console.warn("Fehler beim Erstellen des User-Dokuments:", docErr);
            }
          }
        }
      } catch (err) {
        console.error("Fehler beim Abrufen des Users oder Erstellen des Dokuments:", err);
        // Continue anyway - might already exist
      }
      
      // Add small delay to let the shuffle exit animation complete
      // Exit animation is 0.5s, so we wait a bit longer to see it fully
      setTimeout(() => {
        setPhase("extension");
      }, 600); // 600ms delay - slightly longer than exit animation (500ms)
    }
  };

  const handleSkip = async () => {
    // Skip onboarding - directly call onStart to proceed to dashboard
    // Must await to ensure User document is created before proceeding
    if (onStart) {
      await onStart();
    }
  };

  // Validate eBay URL
  const isValidEbayUrl = (url) => {
    if (!url || !url.trim()) {
      return false;
    }
    
    // Pattern for hostname only (without protocol/path)
    const ebayHostnamePattern = /^(www\.)?(ebay\.(de|com|co\.uk|fr|it|es|nl|at|ch|com\.au|ca)|ebay-kleinanzeigen\.de)$/i;
    
    try {
      const urlObj = new URL(url);
      const hostname = urlObj.hostname;
      const patternMatches = ebayHostnamePattern.test(hostname);
      
      return patternMatches;
    } catch (e) {
      // Invalid URL format
      return false;
    }
  };

  const handleAccountSubmit = async (e, url) => {
    e.preventDefault();
    
    // #region agent log
    fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:418',message:'handleAccountSubmit: entry',data:{url,hasUrl:!!url,phase},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
    // #endregion
    
    if (!url || !url.trim()) {
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:422',message:'handleAccountSubmit: empty url',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
      // #endregion
      setNotificationMessage("bitte eine gueltige url verwenden!");
      setShowNotification(true);
      return;
    }

    // Validate eBay URL
    const isValid = isValidEbayUrl(url);
    // #region agent log
    fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:430',message:'handleAccountSubmit: validation result',data:{url,isValid},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
    // #endregion
    
    if (!isValid) {
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:434',message:'handleAccountSubmit: invalid url',data:{url},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
      // #endregion
      setNotificationMessage("bitte eine gueltige url verwenden!");
      setShowNotification(true);
      return;
    }

    setSubmitting(true);
    setSubmitError("");

    // Wait 2 seconds for vanish animation, then switch to loading phase
    setTimeout(async () => {
      // Switch to loading phase first
      // #region agent log
      fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:444',message:'handleAccountSubmit: switching to loading phase',data:{url},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
      // #endregion
      setPhase("loading");

      try {
        // Parse eBay account
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:449',message:'handleAccountSubmit: before parseEbayAccount',data:{url},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
        // #endregion
        const accountData = await parseEbayAccount(url);
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:452',message:'handleAccountSubmit: parseEbayAccount success',data:{url,hasAccountData:!!accountData,market:accountData?.market,sellerId:accountData?.sellerId},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
        // #endregion

        // Validate that sellerId was extracted successfully
        if (!accountData.sellerId || accountData.sellerId.trim() === "") {
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:456',message:'handleAccountSubmit: sellerId validation failed',data:{accountData},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
          // #endregion
          throw new Error("Die eBay-URL konnte nicht verarbeitet werden. Bitte stelle sicher, dass es eine gültige eBay-Shop-URL ist.");
        }

        // Get current user
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:462',message:'handleAccountSubmit: before account.get',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H3'})}).catch(()=>{});
        // #endregion
        const authUser = await account.get();
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:465',message:'handleAccountSubmit: account.get success',data:{hasAuthUser:!!authUser,userId:authUser?.$id},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H3'})}).catch(()=>{});
        // #endregion

        // Check for duplicate account before creating
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:469',message:'handleAccountSubmit: before fetchManagedAccounts',data:{userId:authUser.$id},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H3'})}).catch(()=>{});
        // #endregion
        const existingAccounts = await fetchManagedAccounts(authUser.$id);
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:472',message:'handleAccountSubmit: fetchManagedAccounts success',data:{accountsCount:existingAccounts?.length || 0},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H3'})}).catch(()=>{});
        // #endregion
        const duplicateAccount = existingAccounts.find(
          (acc) =>
            acc.account_platform_account_id === accountData.sellerId &&
            acc.account_platform_market === accountData.market
        );

        if (duplicateAccount) {
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:480',message:'handleAccountSubmit: duplicate account found',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H3'})}).catch(()=>{});
          // #endregion
          throw new Error("Dieser Account ist bereits verbunden.");
        }

        // Create account in database
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:485',message:'handleAccountSubmit: before createManagedAccount',data:{userId:authUser.$id,accountData,itemsSold:accountData.stats?.itemsSold},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H3'})}).catch(()=>{});
        // #endregion
        await createManagedAccount(authUser.$id, {
          account_platform_market: accountData.market,
          account_platform_account_id: accountData.sellerId,
          account_shop_name: accountData.shopName || null,
          account_url: url,
          account_status: accountData.status || "active",
          account_sells: accountData.stats?.itemsSold ?? null, // Setze account_sells wenn verfügbar
        });
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:494',message:'handleAccountSubmit: createManagedAccount success',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H3'})}).catch(()=>{});
        // #endregion

        // Account erstellt erfolgreich, rufe onStart auf
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:498',message:'handleAccountSubmit: before onStart',data:{hasOnStart:!!onStart},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H1'})}).catch(()=>{});
        // #endregion
        if (onStart) {
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:501',message:'handleAccountSubmit: calling onStart',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H1'})}).catch(()=>{});
          // #endregion
          await onStart();
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:504',message:'handleAccountSubmit: onStart completed, resetting phase',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H1'})}).catch(()=>{});
          // #endregion
          // Phase zurücksetzen, damit der Loading-Screen verschwindet
          // (onStart versteckt das Gate, aber die Phase bleibt auf "loading")
          setPhase("input");
          setSubmitting(false);
        }
        
        // Trigger event to reload Dashboard accounts
        window.dispatchEvent(new CustomEvent('accountsUpdated'));
      } catch (err) {
        console.error("Fehler beim Erstellen des Accounts:", err);
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:512',message:'handleAccountSubmit: error caught',data:{url,errorMessage:err.message,errorCode:err.code,errorType:err.type,errorStack:err.stack?.substring(0,200)},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
        // #endregion
        
        // Show notification for URL validation, duplicate, or parsing errors
        if (
          err.message?.includes("URL") || 
          err.message?.includes("ungültig") || 
          err.message?.includes("invalid") ||
          err.message?.includes("bereits verbunden") ||
          err.message?.includes("already")
        ) {
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:523',message:'handleAccountSubmit: URL/duplicate error, showing notification',data:{errorMessage:err.message},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
          // #endregion
          // Use the actual error message or default message
          setNotificationMessage(err.message || "bitte eine gueltige url verwenden!");
          setShowNotification(true);
        } else {
          // #region agent log
          fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:530',message:'handleAccountSubmit: non-URL error, setting submitError',data:{errorMessage:err.message},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H2'})}).catch(()=>{});
          // #endregion
          setSubmitError(err.message || "Fehler beim Erstellen des Accounts. Bitte versuche es erneut.");
        }
        // #region agent log
        fetch('http://127.0.0.1:7242/ingest/246fe132-ecc5-435f-bd9c-fe5e8e26089d',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'OnboardingGate.jsx:534',message:'handleAccountSubmit: error handler - switching back to input phase',data:{},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'H4'})}).catch(()=>{});
        // #endregion
        setPhase("input");
        setSubmitting(false);
      }
    }, 2000); // 2 second delay for vanish animation
  };

  return (
    <div 
      style={{...styles.overlay, cursor: phase === "welcome" ? "pointer" : "default"}} 
      onClick={handleOverlayClick}
    >
      <BackgroundRippleEffect />
      
      {/* Skip Button - Bottom Left */}
      <button
        onClick={handleSkip}
        style={{
          ...styles.skipButton,
          width: skipHovered ? "90px" : "32px",
          borderRadius: skipHovered ? "40px" : "50%",
        }}
        onMouseEnter={() => setSkipHovered(true)}
        onMouseLeave={() => setSkipHovered(false)}
      >
        <div style={{
          ...styles.skipSign,
          width: skipHovered ? "30%" : "100%",
          paddingLeft: skipHovered ? "15px" : "0",
        }}>
          <svg viewBox="0 0 512 512" style={{ width: "12px" }}>
            <path fill="white" d="M470.6 278.6c12.5-12.5 12.5-32.8 0-45.3l-160-160c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L402.7 256 265.4 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l160-160zm-352 160l160-160c12.5-12.5 12.5-32.8 0-45.3l-160-160c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L210.7 256 73.4 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0z" />
          </svg>
        </div>
        <div style={{
          ...styles.skipText,
          opacity: skipHovered ? 1 : 0,
          width: skipHovered ? "70%" : "0%",
          paddingRight: skipHovered ? "8px" : "0",
        }}>Skip</div>
      </button>
      
      {/* iPhone-style Notification */}
      <IPhoneNotification
        show={showNotification}
        title="Einstellungen"
        message={notificationMessage}
        onClose={() => setShowNotification(false)}
        duration={4000}
      />
      
      {/* Welcome, Extension and Input Phases - Combined AnimatePresence for smooth transition */}
      <AnimatePresence mode="wait">
        {phase === "welcome" && (
          <motion.div
            key="welcome"
            initial={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 100 }}
            transition={{ duration: 0.5, ease: "easeInOut" }}
            style={styles.centerContent}
            onClick={(e) => {
              e.stopPropagation(); // Prevent double-triggering
              handleOverlayClick(e);
            }}
          >
            <div style={styles.shuffleContainer}>
              <Shuffle
                text="Willkommen"
                duration={1}
                stagger={0.08}
                shuffleDirection="down"
                loop={true}
                loopDelay={2}
                triggerOnHover={false}
                style={{ letterSpacing: '0.2em' }}
              />
              <span style={styles.staticComma}>,</span>
              <Shuffle
                text={userName}
                duration={1}
                stagger={0.08}
                shuffleDirection="down"
                loop={true}
                loopDelay={2}
                triggerOnHover={false}
                style={{ letterSpacing: '0.2em', marginLeft: '0.3em' }}
              />
            </div>
          </motion.div>
        )}

        {phase === "extension" && (
          <motion.div
            key="extension"
            initial={{ opacity: 0, y: -100 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -100 }}
            transition={{ duration: 0.5, ease: "easeInOut" }}
            style={styles.extensionSection}
          >
            <div style={styles.extensionContent}>
              <div style={styles.extensionTitle}>
                <span style={{ color: "rgb(231, 170, 240)" }}>Lade die </span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>C</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(174, 182, 192)", filter: "blur(0px)", opacity: 1 }}>h</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>r</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>o</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(217, 141, 233)", filter: "blur(0px)", opacity: 1 }}>m</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(212, 170, 235)", filter: "blur(0px)", opacity: 1 }}>e</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(230, 170, 239)", filter: "blur(0px)", opacity: 1 }}> </span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>E</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>x</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>t</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>e</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(174, 182, 192)", filter: "blur(0px)", opacity: 1 }}>n</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>s</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(231, 170, 240)", filter: "blur(0px)", opacity: 1 }}>i</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(217, 141, 233)", filter: "blur(0px)", opacity: 1 }}>o</span>
                <span className="inline-block whitespace-pre font-sans tracking-tight" style={{ transform: "none", color: "rgb(212, 170, 235)", filter: "blur(0px)", opacity: 1 }}>n</span>
                <span style={{ color: "rgb(231, 170, 240)" }}> herunter und aktiviere sie</span>
              </div>
              
              {!extensionDownloaded ? (
                <div style={styles.downloadButtonContainer}>
                  <DottedGlowBackground
                    className="pointer-events-none"
                    opacity={1}
                    gap={10}
                    radius={1.6}
                    color="rgba(231, 170, 240, 0.3)"
                    glowColor="rgba(231, 170, 240, 0.6)"
                    backgroundOpacity={0}
                    speedMin={0.3}
                    speedMax={1.6}
                    speedScale={1}
                  />
                  <StyledDownloadButton>
                    <a
                      href="/extension.zip"
                      download="extension.zip"
                      className="button"
                      onClick={() => {
                        setExtensionDownloaded(true);
                      }}
                    >
                      <div className="container">
                        <div className="folder folder_one" />
                        <div className="folder folder_two" />
                        <div className="folder folder_three" />
                        <div className="folder folder_four" />
                      </div>
                      <div className="active_line" />
                      <span className="text">Download as .zip</span>
                    </a>
                  </StyledDownloadButton>
                </div>
              ) : (
                <button
                  onClick={() => {
                    window.location.reload();
                  }}
                  style={styles.reloadButton}
                >
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ marginRight: "8px" }}>
                    <polyline points="23 4 23 10 17 10"></polyline>
                    <polyline points="1 20 1 14 7 14"></polyline>
                    <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
                  </svg>
                  Seite neu laden
                </button>
              )}

              {userExtensionLoaded ? (
                <div style={styles.extensionDetected}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#4ade80" strokeWidth="2" style={{ marginRight: "8px" }}>
                    <polyline points="20 6 9 17 4 12"></polyline>
                  </svg>
                  <span>Extension aktiviert! Weiterleitung...</span>
                </div>
              ) : extensionDetected ? (
                <div style={styles.extensionDetected}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#4ade80" strokeWidth="2" style={{ marginRight: "8px" }}>
                    <polyline points="20 6 9 17 4 12"></polyline>
                  </svg>
                  <span>Extension erkannt! Weiterleitung...</span>
                </div>
              ) : (
                <>
                  <div style={styles.extensionChecking}>
                    <div style={styles.loadingSpinner}></div>
                    <span style={{ marginLeft: "12px" }}>Warte auf Extension...</span>
                  </div>
                </>
              )}
            </div>
          </motion.div>
        )}
        
        {phase === "input" && (
          <motion.div
            key="input"
            initial={{ opacity: 0, y: -100 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -100 }}
            transition={{ duration: 0.5, ease: "easeInOut" }}
            style={styles.centerContent}
          >
            <div style={styles.inputContainer}>
              <div style={styles.colourfulTextContainer}>
                <span style={styles.textPrefix}>Gib deine </span>
                <ColourfulText text="ebay account url" />
                <span style={styles.textPrefix}> ein</span>
              </div>
              
              <PlaceholdersAndVanishInput
                placeholders={placeholders}
                onChange={() => {
                  setSubmitError("");
                  setShowNotification(false);
                  setNotificationMessage("bitte eine gueltige url verwenden!"); // Reset to default
                }}
                onSubmit={handleAccountSubmit}
              />

              {(submitError || error) && !showNotification && (
                <div style={styles.error}>
                  {submitError || error}
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Loading Phase */}
      {phase === "loading" && (
        <MultiStepLoader
          loadingStates={loadingStates}
          loading={true}
          duration={2000}
          loop={false}
        />
      )}
    </div>
  );
};

const styles = {
  overlay: {
    position: "fixed",
    inset: 0,
    background: "rgba(0,0,0,0.75)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: 18,
    zIndex: 9998,
    overflow: "hidden",
  },
  centerContent: {
    position: "relative",
    zIndex: 10, // Higher than BackgroundRippleEffect (z-[3] = z-index: 3) to ensure input is clickable
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    maxWidth: "800px",
    padding: "0 20px",
    cursor: "default",
  },
  shuffleContainer: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    flexWrap: "wrap",
    gap: "0",
  },
  staticComma: {
    fontSize: "4rem",
    fontWeight: 800,
    color: "#e7aaf0",
    marginLeft: "0.1em",
    marginRight: "0.1em",
    display: "inline-block",
  },
  inputContainer: {
    width: "100%",
    maxWidth: "600px",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    gap: "24px",
  },
  colourfulTextContainer: {
    display: "flex",
    alignItems: "center",
    flexWrap: "wrap",
    justifyContent: "center",
    gap: "4px",
    fontSize: "24px",
    fontWeight: 600,
    color: "#e7aaf0",
    marginBottom: "8px",
    textAlign: "center",
  },
  textPrefix: {
    color: "#e7aaf0",
  },
  error: {
    marginTop: 12,
    color: "#ffb3b3",
    fontSize: 13,
    textAlign: "center",
    padding: "8px 16px",
    backgroundColor: "rgba(255, 179, 179, 0.1)",
    borderRadius: "8px",
    border: "1px solid rgba(255, 179, 179, 0.3)",
  },
  skipButton: {
    position: "fixed",
    bottom: 20,
    left: 20,
    display: "flex",
    alignItems: "center",
    justifyContent: "flex-start",
    width: "32px",
    height: "32px",
    border: "none",
    borderRadius: "50%",
    cursor: "pointer",
    backgroundColor: "rgb(255, 65, 65)",
    boxShadow: "2px 2px 10px rgba(0, 0, 0, 0.199)",
    transition: "all 0.3s ease",
    overflow: "hidden",
    zIndex: 10001,
  },
  skipSign: {
    width: "100%",
    transition: "all 0.3s ease",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
  },
  skipText: {
    position: "absolute",
    right: "0%",
    width: "0%",
    opacity: 0,
    color: "white",
    fontSize: "0.9em",
    fontWeight: 600,
    transition: "all 0.3s ease",
    whiteSpace: "nowrap",
  },
  welcomeHint: {
    marginTop: "24px",
    fontSize: "18px",
    color: "#e7aaf0",
    textAlign: "center",
    opacity: 0.8,
  },
  extensionSection: {
    position: "relative",
    zIndex: 10,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    maxWidth: "800px",
    padding: "0px 20px",
    cursor: "default",
    opacity: 1,
    transform: "none",
  },
  extensionContent: {
    width: "100%",
    maxWidth: "600px",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    gap: "24px",
  },
  extensionTitle: {
    display: "flex",
    alignItems: "center",
    flexWrap: "wrap",
    justifyContent: "center",
    gap: "4px",
    fontSize: "24px",
    fontWeight: 600,
    color: "rgb(231, 170, 240)",
    marginBottom: "8px",
    textAlign: "center",
    lineHeight: "1.5",
  },
  downloadButtonContainer: {
    position: "relative",
    width: "250px",
    height: "250px",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    overflow: "hidden",
    borderRadius: "12px",
    padding: "40px",
  },
  downloadButton: {
    position: "relative",
    zIndex: 10,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: "14px 28px",
    backgroundColor: "rgb(231, 170, 240)",
    color: "rgb(0, 0, 0)",
    fontSize: "16px",
    fontWeight: 600,
    borderRadius: "12px",
    textDecoration: "none",
    transition: "0.3s",
    boxShadow: "rgba(231, 170, 240, 0.3) 0px 4px 12px",
    cursor: "pointer",
  },
  installationInstructions: {
    width: "100%",
    maxWidth: "500px",
    padding: "20px",
    backgroundColor: "rgba(231, 170, 240, 0.1)",
    borderRadius: "12px",
    border: "1px solid rgba(231, 170, 240, 0.3)",
  },
  instructionTitle: {
    margin: "0 0 12px 0",
    fontSize: "14px",
    fontWeight: 600,
    color: "#e7aaf0",
  },
  instructionList: {
    margin: 0,
    paddingLeft: "20px",
    fontSize: "13px",
    color: "#e7aaf0",
    lineHeight: "1.8",
  },
  code: {
    padding: "2px 6px",
    backgroundColor: "rgba(0, 0, 0, 0.3)",
    borderRadius: "4px",
    fontFamily: "monospace",
    fontSize: "12px",
  },
  extensionDetected: {
    display: "flex",
    alignItems: "center",
    padding: "12px 20px",
    backgroundColor: "rgba(74, 222, 128, 0.1)",
    borderRadius: "8px",
    border: "1px solid rgba(74, 222, 128, 0.3)",
    color: "#4ade80",
    fontSize: "14px",
    fontWeight: 500,
  },
  extensionChecking: {
    display: "flex",
    alignItems: "center",
    padding: "12px 20px",
    color: "rgb(231, 170, 240)",
    fontSize: "14px",
  },
  loadingSpinner: {
    width: "16px",
    height: "16px",
    borderWidth: "2px",
    borderStyle: "solid",
    borderColor: "rgb(231, 170, 240) rgba(231, 170, 240, 0.3) rgba(231, 170, 240, 0.3)",
    borderRadius: "50%",
    animation: "spin 0.8s linear infinite",
  },
  manualContinueButton: {
    marginTop: "16px",
    padding: "10px 24px",
    backgroundColor: "rgba(231, 170, 240, 0.2)",
    color: "rgb(231, 170, 240)",
    border: "1px solid rgba(231, 170, 240, 0.5)",
    borderRadius: "8px",
    fontSize: "14px",
    fontWeight: 500,
    cursor: "pointer",
    transition: "0.3s",
    padding: "10px 24px",
    backgroundColor: "rgba(231, 170, 240, 0.2)",
    color: "#e7aaf0",
    border: "1px solid rgba(231, 170, 240, 0.5)",
    borderRadius: "8px",
    fontSize: "14px",
    fontWeight: 500,
    cursor: "pointer",
    transition: "all 0.3s ease",
  },
  reloadButton: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: "14px 28px",
    backgroundColor: "#e7aaf0",
    color: "#000",
    fontSize: "16px",
    fontWeight: 600,
    borderRadius: "12px",
    textDecoration: "none",
    transition: "all 0.3s ease",
    boxShadow: "0 4px 12px rgba(231, 170, 240, 0.3)",
    cursor: "pointer",
    border: "none",
  },
  reloadHint: {
    marginTop: "12px",
    padding: "12px 16px",
    backgroundColor: "rgba(231, 170, 240, 0.1)",
    borderRadius: "8px",
    border: "1px solid rgba(231, 170, 240, 0.3)",
    textAlign: "center",
  },
};
