<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useChatStore } from '../stores/chat';

const router = useRouter();
const chatStore = useChatStore();
const isConnecting = ref(false);
const error = ref(null);

const connectWallet = async () => {
  isConnecting.value = true;
  error.value = null;

  try {
    const { solana } = window;

    if (solana && solana.isPhantom) {
      const response = await solana.connect();
      const wallet = response.publicKey.toString();
      
      // Sign message for authentication
      const message = `Sign this message to login to Plexus: ${new Date().toDateString()}`;
      const encodedMessage = new TextEncoder().encode(message);
      const signedMessage = await solana.signMessage(encodedMessage, "utf8");
      const signature = btoa(String.fromCharCode.apply(null, signedMessage.signature));

      // Simple username generation or prompt
      const username = wallet.slice(0, 4) + '...' + wallet.slice(-4);
      chatStore.connect(wallet, username, signature);
      
      // Redirect to chat after successful login
      router.push('/chat/nebula');
    } else {
      alert('Solana object not found! Get a Phantom Wallet 👻');
      window.open('https://phantom.app/', '_blank');
    }
  } catch (err) {
    console.error(err);
    error.value = "Connection failed or rejected";
  } finally {
    isConnecting.value = false;
  }
};
</script>

<template>
  <div class="flex flex-col items-center justify-center h-screen bg-black/50 backdrop-blur-sm">
    <div class="p-8 bg-crypto-panel rounded-2xl shadow-2xl border border-violet-500/20 text-center max-w-md w-full backdrop-blur-xl">
      <!-- Logo -->
      <div class="w-20 h-20 mx-auto mb-6 rounded-2xl bg-gradient-to-br from-violet-600 via-fuchsia-600 to-pink-600 flex items-center justify-center shadow-xl shadow-violet-600/30">
        <span class="text-3xl font-black text-white">P</span>
      </div>
      
      <h1 class="text-4xl font-black mb-2 bg-gradient-to-r from-violet-400 via-fuchsia-400 to-pink-400 text-transparent bg-clip-text">
        Plexus
      </h1>
      <p class="text-crypto-muted mb-8 text-sm">
        Web3 Social Chat • Connect wallet to join
      </p>
      
      <button 
        :disabled="isConnecting" 
        class="w-full py-4 px-6 bg-gradient-to-r from-violet-600 to-fuchsia-600 hover:from-violet-500 hover:to-fuchsia-500 text-white rounded-xl font-bold transition-all transform hover:scale-[1.02] hover:shadow-xl hover:shadow-violet-600/30 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100 flex items-center justify-center gap-3"
        @click="connectWallet"
      >
        <span v-if="isConnecting" class="flex items-center gap-2">
          <div class="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
          Connecting...
        </span>
        <span v-else class="flex items-center gap-2">
          <svg class="w-5 h-5" viewBox="0 0 128 128" fill="none">
            <circle cx="64" cy="64" r="64" fill="url(#phantom-gradient)"/>
            <path d="M110.5 64C110.5 90.5 89.5 112 64 112C38.5 112 17.5 90.5 17.5 64C17.5 37.5 38.5 16 64 16" stroke="white" stroke-width="8" stroke-linecap="round"/>
            <defs>
              <linearGradient id="phantom-gradient" x1="0" y1="0" x2="128" y2="128">
                <stop offset="0%" stop-color="#AB9FF2"/>
                <stop offset="100%" stop-color="#534BB1"/>
              </linearGradient>
            </defs>
          </svg>
          Connect Phantom Wallet
        </span>
      </button>

      <p
        v-if="error"
        class="mt-4 text-red-400 text-sm bg-red-500/10 border border-red-500/20 rounded-lg py-2 px-3"
      >
        {{ error }}
      </p>
      
      <p class="mt-6 text-xs text-gray-600">
        Don't have a wallet? 
        <a href="https://phantom.app/" target="_blank" class="text-violet-400 hover:text-violet-300 underline">Get Phantom</a>
      </p>
    </div>
  </div>
</template>
