<script>
  import { CardHeader, CardTitle, Button, Card, Input, Form, CardBody, FormGroup } from '@sveltestrap/sveltestrap';
  import { navigate } from 'svelte-routing';
  
  let email = $state("")
  let contraseña = $state("")
  let errorMessage = $state("")
  
  // @ts-ignore
  async function submitForm(event) {
    event.preventDefault();
    
    const data = {email, contraseña};
    try{
      const response = await fetch("http://127.0.0.1:5007/api/login",{ 
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
        credentials: "include"
      });

      if (!response.ok){
       const errorData = await response.json()
       errorMessage = errorData.message;
       return;
      }

      const ret = await response.json();
      localStorage.clear();
      localStorage.setItem('email', ret.email);
      sessionStorage.setItem('token', ret.token);
      //setTimeout(() => console.log("50ms") ,50);
      navigate(ret.redirect);
    } catch (e) {
    }
   
  }

</script>

<Card class="position-sticky top-50 start-50 translate-middle-x" style="width: 20rem; height: auto;" theme="auto" color="dark" outline>
  <CardHeader>
    <CardTitle>Iniciar Sesión</CardTitle>
  </CardHeader>
  <CardBody>
    <Form on:submit={submitForm}>
      <FormGroup floating label="Email">
        <Input type="email" placeholder="ejemplo@mail.com" bind:value={email} required/>
      </FormGroup>
      <FormGroup floating label="Contraseña">
        <Input type="password" placeholder="*********" bind:value={contraseña} required/>
      </FormGroup>     
      <FormGroup>
        <Button color="primary" type="submit">Ingresar</Button>
      </FormGroup>     
    </Form>
{#if errorMessage}
    <div class='alert alert-warning alert-dismissible fade show' role='alert'>
      <strong>{errorMessage}</strong> 
      <button type="button" class="btn-close close" aria-label="Close" data-bs-dismiss="alert"></button>
    </div>
{/if}
  </CardBody>
</Card>
