<% @title = t('.header') %>

<%= render 'account/shared/workflow/box' do |p| %>
  <% p.content_for :title, @title %>
  <% p.content_for :body do %>
    <% within_fields_namespace(:self) do %>
      <%= form_for @user, url: account_onboarding_user_detail_path(@user), method: :put, html: {class: 'form'} do |f| %>
        <%= render 'account/shared/forms/errors', form: f %>

        <div class="grid grid-cols-1 gap-y gap-x sm:grid-cols-2">
          <div class="sm:col-span-1">
            <%= render 'shared/fields/text_field', form: f, method: :first_name, options: {autofocus: true} %>
          </div>

          <div class="sm:col-span-1">
            <%= render 'shared/fields/text_field', form: f, method: :last_name %>
          </div>

          <div class="sm:col-span-2">
            <% # only edit the team name if this user is an admin and they are the first user. %>
            <% # yes, that's redundant. %>
            <% if can?(:edit, f.object.current_team) && f.object.current_team.users.count == 1 %>
              <%= f.fields_for :current_team do |tf| %>
                <%= render 'shared/fields/text_field', form: tf, method: :name %>
              <% end %>
            <% end %>
          </div>

          <div class="sm:col-span-2">
            <%= render 'shared/fields/super_select', form: f, method: :time_zone,
              choices: time_zone_options_for_select(@user.time_zone, nil, ActiveSupport::TimeZone),
              other_options: {search: true} %>
          </div>
        </div>

        <div class="buttons">
          <%= f.submit t('.buttons.next'), class: first_button_primary %>
          <% if other_teams.any? %>
            <%= link_to t('global.buttons.back'), main_app.account_teams_path, class: first_button_primary %>
          <% else %>
            <%= link_to t('menus.main.labels.logout'), main_app.destroy_user_session_path, class: first_button_primary, method: 'delete' %>
          <% end %>
        </div>
      <% end %>
    <% end %>
  <% end %>
<% end %>

<script type="text/javascript">
  $(document).on('turbo:load', function() {

    // generate a mapping of js timezones compared to rails timezones.
    var jsTimezoneMapping = {
      <% ActiveSupport::TimeZone::MAPPING.each do |key, value| %>
      "<%= value.html_safe %>": "<%= key.html_safe %>",
      <% end %>
    }

    // figure out the rails timezone value.
    var railsValue = jsTimezoneMapping[jstz.determine().name()];

    // set the form accordingly.
    var $option = $("#user_time_zone option[value=\"" + railsValue + "\"]")
    $option.prop('selected', true);

    // update the select2 as well. is there a better way to handle this?
    // why don't _they_ handle this for us?
    $("#select2-user_time_zone-container").attr('title', $option.text());
    $("#select2-user_time_zone-container").text($option.text());

  });
</script>