<div class="container">
  <!-- Estilos integrados -->
  <style>
    :root {
      --primary-blue: #2A4E6D;
      --secondary-blue: #4A90E2;
      --light-bg: #F0F7FF;
      --accent-orange: #FF6B35;
    }
    /* Estilo general del formulario */
    .form-container {
      background: #ffffff;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
      padding: 1.5rem;
      margin-bottom: 2rem;
    }
    /* Inputs, selects, textarea */
    .form-control {
      border: 2px solid #e0e7f1 !important;
      border-radius: 8px !important;
      padding: 0.75rem 1rem !important;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .form-control:focus {
      border-color: var(--secondary-blue) !important;
      box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1) !important;
    }
    /* Grupo de radios */
    .radio-group {
      display: flex;
      gap: 1.5rem;
      align-items: center;
    }
    .radio-group label {
      position: relative;
      padding-left: 28px;
      cursor: pointer;
    }
    .radio-group input[type="radio"] {
      position: absolute;
      opacity: 0;
      width: 0;
      height: 0;
    }
    .radio-group input[type="radio"] + span {
      position: absolute;
      left: 0;
      top: 1px;
      width: 20px;
      height: 20px;
      border: 2px solid var(--primary-blue);
      border-radius: 50%;
    }
    .radio-group input[type="radio"]:checked + span {
      border-color: var(--secondary-blue);
    }
    .radio-group input[type="radio"]:checked + span:after {
      content: '';
      position: absolute;
      width: 12px;
      height: 12px;
      background: var(--secondary-blue);
      border-radius: 50%;
      top: 2px;
      left: 2px;
    }
    /* Fondo para columnas */
    .col-background {
      background: var(--light-bg) !important;
      border-radius: 8px;
      display: flex;
      align-items: center;
      padding: 1rem !important;
    }
    /* Botón de envío */
    .btn-success {
      background: linear-gradient(135deg, var(--secondary-blue), var(--primary-blue));
      border: none;
      padding: 1rem 2.5rem;
      border-radius: 8px;
      font-weight: 600;
      transition: all 0.3s ease;
      color: #fff;
    }
    .btn-success:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(42, 78, 109, 0.3);
    }
    /* Responsive */
    @media (max-width: 768px) {
      .col-background {
        margin-bottom: 1rem;
      }
      .radio-group {
        flex-direction: column;
        align-items: flex-start;
      }
      .form-control {
        padding: 0.6rem 0.8rem !important;
      }
      .btn-success {
        width: 100%;
        padding: 1rem;
      }
    }

    .tag-span {
    background-color: #2A4E6D;
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
    display: inline-flex;
    align-items: center;
  }

  .tag-span .remove-tag {
    margin-left: 8px;
    cursor: pointer;
    font-weight: bold;
    color: #ffdddd;
  }

  .tag-span .remove-tag:hover {
    color: #ffffff;
  }
  </style>

  <!-- Inicio del Formulario -->
  <form name="{{ $name }}" id="{{ $id }}" class="form-container" action="{{ URL::route($action) }}" method="POST" autocomplete="off">
    <!-- Campo base (siempre visible) -->
    <input id="user_id" name="user_id" value="{{ $user->id }}" type="hidden">
    
    <!-- Datos Personales -->
    <div class="container-fluid p-4">
      <div class="row mb-3">
        <div class="col-md-6">
          <div class="form-group">
            <label for="name" class="fw-bold">{{ __("com-form-user.name") }}</label>
            <input type="text" name="name" id="name" class="form-control" placeholder="Ingrese su nombre de usuario">
          </div>
        </div>
        <div class="col-md-6">
          <div class="form-group">
            <label for="email" class="fw-bold">{{ __("com-form-user.mail") }}</label>
            <input type="email" name="email" id="email" class="form-control" placeholder="Ingrese su correo">
          </div>
        </div>
      </div>
      <div class="row mb-3">
        <div class="col-md-6">
          <div class="form-group">
            <label for="password" class="fw-bold">{{ __("com-form-user.password") }}</label>
            <input type="password" name="password" id="password" class="form-control" placeholder="Ingrese contraseña">
          </div>
        </div>
        <div class="col-md-6">
          <div class="form-group">
            <label for="passwordRepeat" class="fw-bold">{{ __("com-form-user.passwordRepeat") }}</label>
            <input type="password" name="passwordRepeat" id="passwordRepeat" class="form-control" placeholder="Repita la contraseña">
          </div>
        </div>
      </div>
      
      <!-- Selección de Rol (siempre visible) -->
      <div class="row mb-3">
        <div class="col-12">
          <p class="fw-bold">{{ __("com-form-user.selectRol") }}</p>
          <div class="d-flex flex-wrap">
            @foreach(config("app.roles") as $key => $value)
              @if(($key === "ADM") && (Auth::user()->hasRole('admin') || Auth::user()->hasRole('root')))
                <div class="form-check me-3">
                @if(isset($_GET["newDoctor"]) && $key === "DOC")
                  <input type="radio" name="role" id="role_{{ $key }}" class="form-check-input" value="{{ $key }}" checked>
                @else
                <input type="radio" name="role" id="role_{{ $key }}" class="form-check-input" value="{{ $key }}">
                @endif


                  <label for="role_{{ $key }}" class="form-check-label">{{ __("com-form-user.".$value) }}</label>
                </div>
              @elseif($key !== "ADM")
                <div class="form-check me-3">
                @if(isset($_GET["newDoctor"]) && $key === "DOC")
                  <input type="radio" name="role" id="role_{{ $key }}" class="form-check-input" value="{{ $key }}" checked>
                @else
                <input type="radio" name="role" id="role_{{ $key }}" class="form-check-input" value="{{ $key }}">
                @endif
                  <label for="role_{{ $key }}" class="form-check-label">{{ __("com-form-user.".$value) }}</label>
                </div>
              @endif
            @endforeach
          </div>
        </div>
      </div>
    </div>
    
    <!-- Contenedor donde se insertarán dinámicamente los campos ADM -->
    <div id="adminFieldsContainer"></div>
    
    <!-- Botón de Envío -->
    <div class="container-fluid p-3">
      <div class="row">
        <div class="col-12 text-center">
          <button type="submit" class="btn btn-success">
            {{ ($new === true) ? __('com-form-user.btnSubmit') : __('com-form-user.btnSubmitUpdate') }}
          </button>
          @csrf
        </div>
      </div>
    </div>
  </form>

  <!-- Template para los campos adicionales del rol ADM -->
  <template id="adminFieldsTemplate">
    <!-- Campo hidden con id de la persona -->
    <!-- Datos Generales -->
    <div class="container-fluid mb-3">
      <div class="row align-items-center">
        <div class="col-12 col-lg-10 col-md-10">
          <div class="mb-2">
            <b><label for="gender">{{ __("com-form-identity.gender") }}</label></b>
          </div>
          <div class="radio-group">
            @if(isset($people->gender))
              @php $gender = strtoupper($people->gender); @endphp
              <label>
                <input type="radio" name="gender" value="F" {{ $gender === 'F' ? 'checked' : '' }}>
                <span></span>{{ __("common.genderFemale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="M" {{ $gender === 'M' ? 'checked' : '' }}>
                <span></span>{{ __("common.genderMale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="O" {{ $gender !== 'F' && $gender !== 'M' ? 'checked' : '' }}>
                <span></span>{{ __("common.genderOther") }}
              </label>
            @else
              <label>
                <input type="radio" name="gender" value="F">
                <span></span>{{ __("common.genderFemale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="M">
                <span></span>{{ __("common.genderMale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="O">
                <span></span>{{ __("common.genderOther") }}
              </label>
            @endif
          </div>
        </div>
      </div>
    </div>
    
    <!-- Campos de Identidad Común -->
    <div class="container-fluid mb-3">
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="firstname">{{ __("com-form-identity.firstname") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.firstname') }}" id="firstname" name="firstname" value="{{ $people->firstname }}" type="text" class="form-control">
        </div>
      </div>
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="lastname">{{ __("com-form-identity.lastname") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.lastname') }}" id="lastname" name="lastname" value="{{ $people->lastname }}" type="text" class="form-control">
        </div>
      </div>
     <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
            <label for="especiality" class="form-label">
            <b>{{ __("com-form-appointment.especiality") }}</b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
           <!-- Campo oculto que almacenará las especialidades seleccionadas -->
            <input type="hidden" name="especialities_selected" id="especialities_selected" value="">

            <!-- Contenedor visual de tags -->
            <div class="form-group mb-2">
            <div id="especialityTags" class="mb-2 d-flex flex-wrap gap-2"></div>
            </div>

            <!-- Select múltiple para agregar especialidades -->
            <div class="form-group">
            <select id="especialitySelect" name="especialitySelect"  class="form-control">
                <option value="">{{ __('com-form-appointment.selectValue') }}</option>
                @foreach($especialities as $key => $option)
                <option value="{{ $key }}">{{ $option }}</option>
                @endforeach
            </select>
            </div>
        </div>
      </div>
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="birthday">{{ __("com-form-identity.birthday") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.birthday') }}" id="birthday" name="birthday" value="{{ $people->birthday }}" type="text" class="form-control">
        </div>
      </div>
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="age">{{ __("com-form-identity.age") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.age') }}" id="age" name="age" value="{{ $people->age }}" type="text" class="form-control" readonly>
        </div>
      </div>
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="phone">{{ __("com-form-identity.phone") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.phone') }}" id="phone" name="phone" value="{{ $people->phone }}" type="text" class="form-control">
        </div>
      </div>
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="address">{{ __("com-form-identity.address") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <textarea placeholder="{{ __('com-form-identity.address') }}" id="address" name="address" class="form-control">{{ $people->address }}</textarea>
        </div>
      </div>
    </div>
  </template>

  <!-- Script para agregar o quitar los campos ADM del DOM -->
  <script>
    function buildRulesBirthday(){
        $('[name="birthday"]').mask('00/00/0000');

        const validateFormatAge = (date)=>{
            const regex = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/\d{4}$/;
            return regex.test(date);
        }

        const  calcuteAge  = (date) => {
            const partsOfDate = date.split("/");
            const day = parseInt(partsOfDate[0], 10);
            const month = parseInt(partsOfDate[1], 10) - 1; // Los meses en JavaScript son 0-11
            const year = parseInt(partsOfDate[2], 10);
            
            const birthday = new Date(year, month, day);
            const currentDate = new Date();
            const currentMonth = currentDate.getMonth();
            const currentDay = currentDate.getDate();
            
            let age = currentDate.getFullYear() - birthday.getFullYear();        
            if (currentMonth < month || (currentMonth === month && currentDay < day)) {
                age--;
            }
            return age;
        }

        $('[name="birthday"]').on("input",(function(e) {
            let input = $('[name="birthday"]').val();
            if(validateFormatAge(input)){
                let age = calcuteAge(input);
                $('#age').val(age).trigger('input');
            }else{
                $('#age').val(null).trigger('input');
            }
        }));
    }


    function buildEventsEspeciality(){
        

        const select = document.getElementById('especialitySelect');
        const tagsContainer = document.getElementById('especialityTags');
        const hiddenInput = document.getElementById('especialities_selected');

        let selectedEspecialities = [];

        function updateHiddenInput() {
        hiddenInput.value = selectedEspecialities.join(',');
        }

        function createTag(value, label) {
        const tag = document.createElement('span');
        tag.classList.add('tag-span');
        tag.setAttribute('data-value', value);
        tag.innerHTML = `${label} <span class="remove-tag">&times;</span>`;

        tag.querySelector('.remove-tag').addEventListener('click', () => {
            tag.remove();
            selectedEspecialities = selectedEspecialities.filter(item => item !== value);
            updateHiddenInput();
        });

        tagsContainer.appendChild(tag);
        }

        select.addEventListener('change', function () {
        const selectedValue = this.value;
        const selectedText = this.options[this.selectedIndex].text;

        if (selectedValue && !selectedEspecialities.includes(selectedValue)) {
            selectedEspecialities.push(selectedValue);
            createTag(selectedValue, selectedText);
            updateHiddenInput();
        }

        // Reset select
        this.value = '';

        $.fn.validations = function(){
            return [
                {
                    "name":"noEmpty",
                    "message":window.translations["create-patient"].fieldRequired,
                    "run":function (field){
                        if(field.key === "user_id") return true;
                        if(field.key === "especialitySelect") return true;
                        let valid = ((field.value != undefined) && (field.value.trim() !== "")); 
                        console.log("name " + field.key + "value " +  valid);
                        return valid;
                    }
                }
            ];
        }
    });

    // Opcional: Si ya vienen especialidades preseleccionadas (modo edición)
    const preloaded = hiddenInput.value.split(',').filter(v => v);
    preloaded.forEach(val => {
      const label = select.querySelector(`option[value="${val}"]`)?.textContent || val;
      selectedEspecialities.push(val);
      createTag(val, label);
    });
    }

    document.addEventListener('DOMContentLoaded', function () {

        // Selecciona el input por su ID
      var inputName = document.getElementById('name');

    // Agrega un listener al evento "keydown"
    inputName.addEventListener('keydown', function(e) {
      // Verifica si la tecla presionada es el espacio
      if (e.key === ' ' || e.keyCode === 32) {
        e.preventDefault(); // Evita que se inserte el espacio
      }
    });
   

      // Contenedor donde se agregarán los campos ADM
      const adminContainer = document.getElementById('adminFieldsContainer');
      // Obtenemos el template
      const adminTemplate = document.getElementById('adminFieldsTemplate');

      function toggleAdminFields() {
        const selectedRole = document.querySelector('input[name="role"]:checked');
        // Si se selecciona ADM y aún no están en el DOM, los agregamos
        if (selectedRole && selectedRole.value.toUpperCase() === 'DOC' || selectedRole && selectedRole.value.toUpperCase() === 'ADM') {
          if (!adminContainer.hasChildNodes()) {
            adminContainer.appendChild(adminTemplate.content.cloneNode(true));
            buildRulesBirthday();
            buildEventsEspeciality();
          }
        } else {
          // Si el rol no es ADM, removemos los campos del DOM
          adminContainer.innerHTML = '';
        }
      }

      const roleRadios = document.querySelectorAll('input[name="role"]');
      roleRadios.forEach(function (radio) {
        radio.addEventListener('change', toggleAdminFields);
      });

      // Verificamos la selección inicial (en caso de edición)
      toggleAdminFields();
    });



  </script>
</div>
