<script lang="ts">
  // import Header from "./Header.svelte";
  import Footer from "../components/Footer.svelte";
  import Tabs from "../shared/Tabs.svelte";
  import Card from "../pieces/Card.svelte";
  import Canvas from "../pieces/Canvas.svelte";
  import ScrollTo from "../shared/ScrollTo.svelte";
  import UserStore from "./UserStore.js";
  import { createEventDispatcher } from "svelte";
  import {push} from "svelte-spa-router";

  let dispatch = createEventDispatcher();
// Tabs
  let items: string[] = ['Login', 'Create Account'];
	let activeItem: string = 'Login';
	
	const tabChange = (e) => {
		activeItem = e.detail;
	};


  import axios from 'axios';
  import { onMount } from 'svelte';

	let user = {logedIn: false};

	onMount(async () => {
		// console.log('PROFIL SVELTE');
		const {data} = await axios.get('http://transcendance:8080/api/v2/user');
		if (data)
			user.logedIn = true;
	});

	const submit = async() => {
    document.body.scrollIntoView();
    push
		window.location.href = 'http://transcendance:8080/api/v2/auth';
	}

	const logout = async() => {
		await fetch('http://transcendance:8080/api/v2/auth/logout',);
		user.logedIn = false;
	};







  // for toLogin

  let bottomHalf;
  // console.log(bottomHalf);
  // const element = document.body;


  // in theory this could be a Store, but for now this will do
  // also in future we'll do this with urls
  export let pages;
  export let currentPage;
  // this shit has overstayed it's welcome, fuck having userId all over the place
  export let userId;


  // maybe we put this in the login Component?
  // tmp
  let login = { username: '', password: ''};
  // let's us track any errors in a submited form
  let errors = { username: '', password: ''};
  let valid:boolean = false;

	const loginHandler = () => {
		console.log('hi from loginHandler');


    // 
    // Basic Checks
    // 
    valid = false;

    // checkin Username
    if (login.username.length < 1)
    {
      valid = false;
      errors.username = 'please enter a username';
    } else {
      valid = true;
      errors.username = '';
    }

    // Checking Password
    if (login.password.length < 1)
    {
      valid = false;
      errors.password = 'please enter your password';
    } else {
      valid = true;
      errors.password = '';
    }

    // 
    // Advanded Checks
    // 

    // Comparing to UserStore
    let users;
    const unsubscribe = UserStore.subscribe(objs => {
      users = objs;
      console.log('subscribed');
    });
  
    // could i do $users.length ? doesn't look like it...
    // let len = $users.length;

    // userId = 0;
    // userId = users.filter(user => user.username === login.username);
    // this shit returns an array, it would be nice if it weren't an array
    // let user = users.filter(user => user.username === login.username);
    let user = users.find(user => user.username === login.username);

    console.log(user);
    // console.log(user.password);


    // all this shit is a bit wordy... maybe a better way to handle this stuff?

    // if (userIndex > users.length) {
    if (!user) {
      valid = false;
      errors.username = 'user not found';
      // something better?
    } else {
      valid = true;
      errors.username = '';
    }

    // if (users[userIndex].password !== login.password) {
    if (user && user.password !== login.password) {
      valid = false;
      errors.password = 'Wrong Password';
      // Maybe clear the fields?
    } else {
      valid = true;
      errors.password = '';
    }

    // 
    // Validation
    // 
    unsubscribe();

    if (valid) {
      // yea don't modify this here...
      currentPage = 'user';
      // something like: indicate that userIndex is the one we want...
      console.log('valid Credentials');

      // making sure we start at the top of the page, way less jarring
        // leave for now just in case...
      document.body.scrollIntoView();

      // may not actually want a dispatch?
      // pass data userIndex?
      // dispatch('loggedIn');
      // from svelte-spa-router
      push("/user");
    }
	};

  //
  const createAccountHandler = () => {
		console.log('hi from accunt handler');
	};


  


</script>


<header class="grid-container">

  <!-- <div on:mouseenter={enter} on:mouseleave={leave} class:active > -->
    <h1>Potato Pong</h1>
  <!-- </div> -->
  <nav>
    <!-- placeholder links -->
    <a href="/">Somewhere</a>
    <!-- <a href="/">SomewhereElse</a> -->
    {#if !user.logedIn}
      <ScrollTo element={bottomHalf}/>
    {:else}
      <div class="logout" on:click={logout}>Log Out</div>
    {/if}
    <!-- one of these will be login and it will scroll you down to the login part -->
  </nav>
  <h2>
    <div>Welcome to</div>
    <div>Potato Pong</div>
  </h2>

  <!-- here i want a flashing arrow pointing down to the login part -->

</header>
<!-- <Canvas class=".canvas2"/> -->
<Canvas/>



<section class="register" bind:this={bottomHalf}>

  <!-- My beautiful tabs are useless now, whatever, kill your darlings... -->
  <!-- i could have a toggle tab to login or create a new account -->
  <!-- This shit is kinda unnecessary cuz there is no Create Account option... -->

  <Tabs items={items} {activeItem} on:tabChange={tabChange}/>
  {#if activeItem === 'Login'}
    <div class="card">
      <Card>
      <h2>Login</h2>
      <form on:submit|preventDefault={loginHandler}>
        <div class="form-field">
          <input type="text" id="username" placeholder="username" bind:value={login.username}>
          <div class="error">{ errors.username }</div>
        </div>
        <div class="form-field">
          <input type="password" id="password" placeholder="password" bind:value={login.password}>
          <div class="error">{ errors.password }</div>
        </div>
        <!-- type="" but flat={}  cuz type is a string but flat is a bool--> 
        <!-- <Button type="secondary" flat={true}>Add Poll</Button> -->
        <button>Login</button>
      </form>
      </Card>
    </div>
  {:else if activeItem = 'Create Account'}
    <!-- Create Account -->
    <div class="card">
      <Card>
        <h2>Create Account</h2>
        <form on:submit|preventDefault={createAccountHandler}>
          <div class="form-field">
            <input type="text" id="username" placeholder="username" bind:value={login.username}>
            <div class="error">{ errors.username }</div>
          </div>
          <div class="form-field">
            <input type="password" id="password" placeholder="password" bind:value={login.password}>
            <div class="error">{ errors.password }</div>
          </div>
          <!-- type="" but flat={}  cuz type is a string but flat is a bool--> 
          <!-- <Button type="secondary" flat={true}>Add Poll</Button> -->
          <button>Login</button>
        </form>
      </Card>
    </div>
  {/if}


</section>
<!-- below this i could say, this is where i might have put an explanation of what you can do on this page but fuck you i didn't -->
<!-- or maybe in the end i will, something like: Fun, Game, Colors, enjoy Friendship, or don't, it's your choice! -->

<Footer />

<!-- </div> -->


<style>
  /* currently useless */
  /* No styles get applied to the canvas from here, maybe i should move them to the Canvas Component... */
  /* tho tbh, why bother, i'm gonna change it anyway... */
  .canvas{
    /* grid-column: 1 / 13;
    grid-row: 1 / 3; */
    /* don't rely on Z-Index!!!! */
    z-index: -1;
    position: relative;
    width: 100%;
    height: 100%;
    white-space: nowrap;

    /* Tmp? */
    /* background-color: #666; */

    /* somehow this got rid of they annoying white space under the canvas */
    padding-bottom: 0;
    margin-bottom: 0px;
    overflow: hidden;
  }

  .canvas2{
    z-index: -1;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    white-space: nowrap;

    /* Tmp? */
    /* background-color: #666; */

    /* somehow this got rid of they annoying white space under the canvas */
    padding-bottom: 0;
    margin-bottom: 0px;
    overflow: hidden;
  }


  /* .canvas .grid-container{ */
  .grid-container{
    position: absolute;
    left: 0;
    top: 0;


    box-sizing: border-box;
    width: 100%;
    height: 100%;
    white-space: nowrap;
    /* padding-bottom: 0; */
    margin-bottom: 0px;
    overflow: hidden;
    padding: 20px 40px;


    display: grid;
    grid-template-columns: repeat(12, 1fr);
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr;
    align-items: center;
  }

  header h1, header nav a{
    /* tmp ? well i kinda like it */
    color: bisque;
  }
  header h1{
    grid-column: 1 / 7;
    grid-row: 1;
    /* grid-column: span 6; */
    /* tmp? */
    padding: 20px;
    border: 1px solid bisque;
  }
  header nav{
    /* make it a flexbox? */
    grid-column: 7 / 13;
    grid-row: 1;
    justify-self: end;
    /* tmp? */
    padding: 20px;
    border: 1px solid bisque;
  }
  header nav a{
    margin-left: 10px;
    text-decoration: none;
  }

  /* testing */
  header nav a:hover{
    font-weight: bold;
    background-color: blue;
  }
  header h2:hover{
    background: blue;
  }


  header h2{
    grid-row: 3;
    grid-column: 5 / span 4;
    justify-self: center;
    /* tmp */
    border: 1px solid black;
    z-index: 3;
  }
  header h2 div{
    font-size: 2em;
  }

  /* the login / register part */

  /* What do i want?
  I want it to be the same size as a full screen so you don't see the canvas at all anymore */

  /* doesn't work... */
  /* body{
    background: bisque;
  } */

  .bottom-half{
    /* doesn't quite work... */
    background: bisque;
    /* also doesn't work... */
    /* height: 1vw; */

    /* testing */
    /* position: absolute; */
  }

  section.register{
    min-height: 400px;
  }

  .error{
    font-size: 0.8em;
    font-weight: bold;
    color: red;
  }


</style>