<script>
  import { createEventDispatcher } from "svelte";
  import { t } from "svelte-i18n";

  /** @type {string} */
  export let name;

  /** @type {string} */
  export let type = "text";

  /** @type {string} */
  export let value = "";

  /** @type {string} */
  export let placeholder = "";

  /** @type {string} */
  export let label = "";

  const dispatch = createEventDispatcher();

  /**
   * @param {Event} event - The input event
   */
  function handleInput(event) {
    const target = event.target;

    if (target instanceof HTMLInputElement) {
      const inputValue = target.value;
      value = inputValue;
      // dispatch("input", { name, value: inputValue });
    }
  }

  /**
   * Validates the field
   * @param {string} name - The name of the field
   * @param {string} value - The value of the field
   * @returns {string|null} The error message or null if valid
   */
  function validateField(name, value) {
    switch (name) {
      case "first_name":
      case "last_name":
        return value.trim() ? null : $t("required");
      case "email":
        return /^\S+@\S+\.\S+$/.test(value) ? null : $t("invalid_email");
      case "password":
        return !value.trim() || value.length >= 8
          ? null
          : $t("required_password");
      // case "password2":
      //   // Note: This case might need special handling as it depends on another field
      //   return $t("required_password_match");
      default:
        return null;
    }
  }

  $: error = validateField(name, value);
</script>

<div class="input-box">
  <span class="label">{label}</span>
  <div class="input-error-container">
    {#if error}
      <span class="error-message">{error}</span>
    {/if}
    <input
      {name}
      {type}
      {placeholder}
      {value}
      on:input={handleInput}
      on:blur={handleInput}
      class="input"
    />
  </div>
</div>

<style>
  .input-error-container {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 100%;
    max-width: 444px;
  }

  .error-message {
    color: #eb5424;
    font-size: 12px;
    margin-bottom: 5px;
    align-self: flex-start;
  }

  .input {
    width: 100%;
  }
</style>
