<%# app/views/admin/timeline/show.html.erb %>
<%# Instance variables: @users_with_timeline_data, @primary_user, @date, @next_date, @prev_date %>

<% content_for :head do %>
  <meta name="current-user-admin-level" content="<%= current_user&.admin_level %>">
<% end %>

<%
  primary_user_tz = @primary_user&.timezone || (current_user&.timezone || 'UTC')

  timeline_start_hour = 0
  timeline_end_hour = 23

  user_colors = ['#7C3AED', '#10B981', '#3B82F6', '#F59E0B', '#EF4444', '#DB2777', '#6D28D9']

  users_data_array = Array(@users_with_timeline_data)
  num_users = users_data_array.count
  num_users = 1 if num_users == 0 # Ensure num_users is at least 1 for calculations

  pixels_per_hour = 128 # Controls vertical scale
  pixels_per_minute = pixels_per_hour / 60.0
  min_column_width_px = 186 # Minimum width for each user column
  gutter_px = 4

  # Current admin user and selected users for Stimulus
  current_admin_user = {
    id: current_user.id,
    display_name: current_user.display_name,
    avatar_url: current_user.avatar_url
  }
  current_admin_user_json = current_admin_user.to_json

  initial_selected_users_json = @initial_selected_user_objects.to_json
  current_date_for_form = @date.to_s
%>

<style>
@keyframes spin {to {transform: rotate(360deg);}}
.spinny {animation: spin 0.2s linear infinite;}
</style>

<div class=" text-white flex flex-col font-sans min-h-screen">
  <div
    data-controller="admin-timeline-user-selector"
    data-admin-timeline-user-selector-current-user-json-value='<%= current_admin_user_json %>'
    data-admin-timeline-user-selector-initial-selected-users-json-value='<%= initial_selected_users_json %>'
    data-admin-timeline-user-selector-search-url-value="<%= admin_timeline_search_users_path %>"
    data-admin-timeline-user-selector-leaderboard-users-url-value="<%= admin_timeline_leaderboard_users_path %>"
    class="mb-4 p-3 bg-dark rounded-md flex-shrink-0">
    <form id="timeline-filter-form" action="<%= admin_timeline_path %>" method="get" data-turbo-frame="_top">
      <input type="hidden" name="user_ids" data-admin-timeline-user-selector-target="userIdsInput">
      <input type="hidden" name="date" value="<%= current_date_for_form %>" data-admin-timeline-user-selector-target="dateInput">

      <div class="flex items-center gap-3">
        <div class="flex-1 relative">
          <div class="relative">
            <div class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
              <svg data-admin-timeline-user-selector-target="searchIcon" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
              <svg data-admin-timeline-user-selector-target="searchSpinner" class="w-4 h-4 spinny hidden" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            </div>
            <input type="text"
                  id="user-search-input"
                  placeholder="Add user by name/email/id..."
                  data-admin-timeline-user-selector-target="searchInput"
                  data-action="input->admin-timeline-user-selector#debouncedSearch keydown->admin-timeline-user-selector#handleKeydown focus->admin-timeline-user-selector#search blur->admin-timeline-user-selector#hideResultsDelayed"
                  autocomplete="off"
                  class="w-full pl-10 pr-3 py-2 bg-darker rounded-md text-white placeholder-gray-300 focus:outline-none focus:border-transparent text-sm">
          </div>
          <div class="absolute top-full left-0 w-full bg-dark border border-gray-700 rounded-lg mt-1 z-50 max-h-48 overflow-y-auto hidden shadow-lg"
              data-admin-timeline-user-selector-target="searchResults">
            <%# Search results will appear here %>
          </div>
        </div>
        <button type="button"
                class="px-3 py-2 bg-darker rounded-md text-sm text-white transition-colors"
                data-action="admin-timeline-user-selector#applyPreset"
                data-period="today">
          Top 15 Today
        </button>
        <button type="button"
                class="px-3 py-2 bg-darker rounded-md text-sm text-white transition-colors"
                data-action="admin-timeline-user-selector#applyPreset"
                data-period="last_7_days">
          Top 15 Week
        </button>
        <button type="submit"
                class="px-4 py-2 bg-green-600 rounded-md text-sm text-white transition-colors font-medium">
          View
        </button>
      </div>

      <div class="mt-2 min-h-7" data-admin-timeline-user-selector-target="selectedUsersContainer">
        <%# Selected user pills will appear here %>
      </div>
    </form>
  </div>

  <div class="flex justify-between items-center mb-4 flex-shrink-0">
    <div class="text-lg font-semibold">
      <%= @date.in_time_zone(primary_user_tz).strftime("%A, %B %-d, %Y") %>
    </div>
    <div class="flex gap-2">
      <%= link_to "← Prev", admin_timeline_path(date: @prev_date.to_s),
          class: "px-3 py-1 bg-darker rounded text-sm transition-colors",
          data: { "date-nav-link": "true" } %>
      <%= link_to "Today", admin_timeline_path(date: Time.current.to_date.to_s),
          class: "px-3 py-1 bg-darker rounded text-sm transition-colors",
          data: { "date-nav-link": "true" } %>
      <%= link_to "Next →", admin_timeline_path(date: @next_date.to_s),
          class: "px-3 py-1 bg-darker rounded text-sm transition-colors",
          data: { "date-nav-link": "true" } %>
    </div>
  </div>

  <div class="flex-1 overflow-x-auto overflow-y-auto">
    <% if users_data_array.any? %>
      <%
        hour_label_width = 80
        grid_width = hour_label_width + (users_data_array.count * (min_column_width_px + gutter_px))
        grid_height = 120 + (24 * pixels_per_hour)
      %>

      <div class="relative" style="width: <%= grid_width %>px; height: <%= grid_height %>px;">
        <% (0..23).each do |hour| %>
          <%
            hour_top = 120 + (hour * pixels_per_hour)
            formatted_hour = Time.utc(2000,1,1, hour).strftime("%-l:00 %p")
          %>
          <div class="absolute left-0 w-full border-t border-gray-600"
               style="top: <%= hour_top %>px; height: <%= pixels_per_hour %>px;">
            <div class="absolute left-2 top-2 text-xs text-gray-300 font-mono px-1">
              <%= formatted_hour %>
            </div>
          </div>
        <% end %>

        <% users_data_array.each_with_index do |data, index| %>
          <%
            user = data[:user]
            total_coded_time_seconds = data[:total_coded_time]
            column_left = hour_label_width + (index * (min_column_width_px + gutter_px))
            trust_level_emoji = case user.respond_to?(:trust_level) ? user.trust_level : nil
              when "red" then "🔴"
              when "green" then "🟢"
              when "yellow" then "🟡"
              else "🔵"
            end

            trust_level_bg = case user.respond_to?(:trust_level) ? user.trust_level : nil
              when "red" then "bg-red-500/20"
              when "green" then "bg-green-500/20"
              when "yellow" then "bg-yellow-500/20"
              when "blue" then "bg-blue-500/20"
              else "bg-gray-500/20"
            end
          %>
          <div class="absolute border-r border-gray-700"
               style="left: <%= column_left %>px; width: <%= min_column_width_px %>px; top: 120px; bottom: 0; padding-bottom: 0;">
          </div>
          <div class="absolute top-0 p-3 rounded-lg shadow-lg <%= trust_level_bg %>"
               data-user-id="<%= user.id %>"
               style="left: <%= column_left + 2 %>px; width: <%= min_column_width_px - 4 %>px;"
               title="User ID: <%= user.id %> - <%= user.respond_to?(:display_name) && user.display_name.present? ? h(user.display_name) : h(user.email_addresses.first&.email) %> | Total Coded: <%= total_coded_time_seconds && total_coded_time_seconds > 0 ? short_time_detailed(total_coded_time_seconds) : '0m' %> | TZ: <%= h(user.timezone) %>">
            <div class="flex items-center space-x-1 mb-1">
              <%= render "shared/user_mention", user: user %>
            </div>
            <div class="flex justify-center items-center gap-4 mb-1 text-center">
              <% if current_user && user != current_user && user.slack_uid.present? %>
              <div>
                <%= link_to "Slack", "slack://user?team=T0266FRGM&id=#{user.slack_uid}",
                target: "_blank",
                class: "text-xs text-blue-400 hover:text-blue-300 underline" %>
              </div>
              <% end %>
              <% if user.respond_to?(:github_profile_url) && user.github_profile_url.present? %>
              <div>
                <%= link_to "Git", user.github_profile_url,
                target: "_blank",
                class: "text-xs text-green-400 hover:text-green-300 underline" %>
              </div>
              <% end %>
              <div>
              <span class="text-sm"><%= trust_level_emoji %></span>
              </div>
              <% if current_user && current_user.admin_level.in?(["admin", "superadmin"]) && user != current_user %>
              <div>
                <button onclick="setTrust(<%= user.id %>)"
                  class="text-xs text-gray-300 hover:text-white"
                  title="Set trust level">🔨</button>
              </div>
              <% end %>
            </div>
            <div class="text-sm font-medium mb-1 <%= total_coded_time_seconds && total_coded_time_seconds > 0 ? 'text-green-300' : 'text-gray-400' %>">
              <%= total_coded_time_seconds && total_coded_time_seconds > 0 ? "#{short_time_simple(total_coded_time_seconds)} coded" : "No time coded" %>
            </div>

            <div class="text-xs text-gray-300">
              <%= user.timezone %>
            </div>
          </div>
        <% end %>

        <%
          current_time_in_zone = Time.current.in_time_zone(primary_user_tz)
          is_today = @date == Time.current.in_time_zone(primary_user_tz).to_date
          show_current_time_line = is_today && current_time_in_zone.hour >= timeline_start_hour && current_time_in_zone.hour < (timeline_end_hour + 1)

          if show_current_time_line
            minutes_from_timeline_start = (current_time_in_zone.hour - timeline_start_hour) * 60 + current_time_in_zone.min
            current_time_line_top_px = 120 + (minutes_from_timeline_start * pixels_per_minute)
          end
        %>
        <% if show_current_time_line %>
          <div class="absolute w-full h-0.5 bg-red-500 z-300 flex items-center"
               style="left: <%= hour_label_width %>px; right: 0; top: <%= current_time_line_top_px %>px;">
            <div class="bg-red-500 text-white text-xs px-2 py-1 rounded -ml-16">NOW</div>
          </div>
        <% end %>
        <%
          calculate_span_properties = lambda do |span_data, span_user_tz|
            return nil unless span_data && span_data[:start_time] && span_data[:duration]
            start_time_in_zone = Time.at(span_data[:start_time]).in_time_zone(span_user_tz)
            end_time_value = span_data[:end_time] || (span_data[:start_time] + span_data[:duration])
            end_time_in_zone = Time.at(end_time_value).in_time_zone(span_user_tz)
            today_start_of_day_for_span_user = @date.in_time_zone(span_user_tz).beginning_of_day
            view_start_datetime = today_start_of_day_for_span_user.advance(hours: timeline_start_hour)
            view_end_datetime = today_start_of_day_for_span_user.advance(hours: timeline_end_hour + 1)
            effective_start_time = [start_time_in_zone, view_start_datetime].max
            effective_end_time = [end_time_in_zone, view_end_datetime].min
            return nil if effective_start_time >= effective_end_time
            minutes_from_view_start = ((effective_start_time - view_start_datetime) / 60.0).to_f
            duration_seconds_in_view = effective_end_time - effective_start_time
            height_px = (duration_seconds_in_view / 60.0) * pixels_per_minute
            return nil if height_px <= 0.5
            final_top_px = 120 + (minutes_from_view_start * pixels_per_minute).round
            title_parts = []
            title_parts << "Languages: #{span_data[:languages].join(', ')}" if span_data[:languages]&.any?
            project_title_segments = (span_data[:projects_edited_details] || []).map do |proj_detail|
              "#{proj_detail[:name]}#{proj_detail[:repo_url] ? ' (GitHub)' : ' (No Repo)'}"
            end
            title_parts << "Projects: #{project_title_segments.join('; ')}" if project_title_segments.any?
            title_parts << "Editors: #{span_data[:editors].join(', ')}" if span_data[:editors]&.any?
            files_to_show = span_data[:files_edited] || []
            if files_to_show.any?
              max_files_in_tooltip = 5
              files_display_string = files_to_show.take(max_files_in_tooltip).join(', ')
              files_display_string += ", +#{files_to_show.length - max_files_in_tooltip} more" if files_to_show.length > max_files_in_tooltip
              title_parts << "Files: #{files_display_string}"
            end
            title_parts << "Duration: #{Time.at(span_data[:duration]).utc.strftime('%Hh %Mm %Ss')}"
            title_parts << "Time: #{start_time_in_zone.strftime("%-l:%M %p")} - #{end_time_in_zone.strftime("%-l:%M %p")}"
            new_title_for_span = title_parts.join("\n")
            {
              final_top_px: final_top_px.round(2),
              height_px: height_px.round(2),
              title: new_title_for_span,
              projects_to_display: span_data[:projects_edited_details] || [],
              display_text_line2: span_data[:languages]&.any? ? span_data[:languages].join(", ") : "-",
              display_text_line3: "#{start_time_in_zone.strftime("%-l:%M %p")} - #{end_time_in_zone.strftime("%-l:%M %p")}",
            }
          end
        %>

        <% users_data_array.each_with_index do |data, index| %>
          <%
            user = data[:user]
            user_spans = data[:spans]
            block_color = user_colors[index % user_colors.length]
            column_left = hour_label_width + (index * (min_column_width_px + gutter_px))
          %>
          <% Array(user_spans).each do |span_data| %>
            <% props = calculate_span_properties.call(span_data, user.timezone || primary_user_tz) %>
            <% next unless props %>
            <div class="absolute rounded-md p-2 text-white text-xs overflow-hidden z-10"
                 style="background-color: <%= block_color %>;
                        left: <%= column_left + 2 %>px;
                        width: <%= min_column_width_px - 4 %>px;
                        top: <%= props[:final_top_px] %>px;
                        height: <%= props[:height_px] %>px;"
                 title="<%= props[:title] %>">
              <div class="font-medium truncate">
                <% if props[:projects_to_display]&.any? %>
                  <% props[:projects_to_display].each_with_index do |project_detail, p_idx| %>
                    <% if project_detail[:repo_url].present? %>
                      <a href="<%= project_detail[:repo_url] %>" target="_blank" rel="noopener noreferrer"
                         class="text-white hover:text-gray-200 underline"
                         title="Open <%= h(project_detail[:name]) %> on GitHub"><%= h(project_detail[:name]).truncate(20) %></a>
                    <% else %>
                      <span title="<%= h(project_detail[:name]) %> - No GitHub Repo Mapped"><%= h(project_detail[:name]).truncate(20) %> 🚫</span>
                    <% end %>
                    <% if p_idx < props[:projects_to_display].length - 1 && props[:height_px] > 20 %>
                      <%= " / " %>
                    <% end %>
                  <% end %>
                <% else %>
                  <span>Coding Activity</span>
                <% end %>
              </div>
              <div class="truncate opacity-90">
                <%= props[:display_text_line2] %>
              </div>
              <div class="truncate opacity-75">
                <%= props[:display_text_line3] %>
              </div>
            </div>
          <% end %>
        <% end %>
        <% @timeline_commit_markers.each do |commit| %>
          <% user_index = users_data_array.find_index { |data| data[:user].id == commit[:user_id] } %>
          <% next unless user_index %>
          <% user = users_data_array[user_index][:user] %>
          <% user_tz = user&.timezone || primary_user_tz %>
          <% today_start_of_day_for_user = @date.in_time_zone(user_tz).beginning_of_day %>
          <% view_start_datetime = today_start_of_day_for_user.advance(hours: timeline_start_hour) %>
          <% column_left = hour_label_width + (user_index * (min_column_width_px + gutter_px)) %>
          <% pill_left_px = column_left + 93 %>
          <% commit_minutes_from_view_start = ((Time.at(commit[:timestamp]).in_time_zone(user_tz) - view_start_datetime) / 60.0).to_f %>
          <% commit_top_px = 120 + (commit_minutes_from_view_start * pixels_per_minute).round %>
          <a href="<%= commit[:github_url] %>" target="_blank" rel="noopener noreferrer"
             title="<%= commit[:message] %>"
             class="absolute z-20 bg-darker text-white rounded-full px-2 py-1 text-xs hover:bg-gray-800 transition-colors"
             style="left: <%= pill_left_px %>px; top: <%= commit_top_px %>px; transform: translateX(-50%);">
            <span class="<%= commit[:additions].to_i > 0 ? 'text-green-400 font-semibold' : '' %>">+<%= commit[:additions] %></span>
            /
            <span class="<%= commit[:deletions].to_i > 0 ? 'text-red-400 font-semibold' : '' %>">-<%= commit[:deletions] %></span>
          </a>
        <% end %>
      </div>
    <% else %>
      <div class="flex items-center justify-center h-64 text-gray-400">
        <div class="text-center">
          <div class="text-lg mb-2">No users selected</div>
          <div class="text-sm">Use the search bar above to add users to the timeline</div>
        </div>
      </div>
    <% end %>
  </div>

</div>

<script>
const trusts = {
  'green': { emoji: '🟢', name: 'Green - Trusted', bg: 'bg-green-500/20' },
  'yellow': { emoji: '🟡', name: 'Yellow - Suspected', bg: 'bg-yellow-500/20' },
  'red': { emoji: '🔴', name: 'Red - Convicted (banned)', bg: 'bg-red-500/20' },
  'blue': { emoji: '🔵', name: 'Blue - Unscored', bg: 'bg-blue-500/20' },
  '1': { emoji: '🟢', name: 'Green - Trusted', bg: 'bg-green-500/20', level: 'green' },
  '2': { emoji: '🟡', name: 'Yellow - Suspected', bg: 'bg-yellow-500/20', level: 'yellow' },
  '3': { emoji: '🔴', name: 'Red - Convicted (banned)', bg: 'bg-red-500/20', level: 'red' },
  '4': { emoji: '🔵', name: 'Blue - Unscored', bg: 'bg-blue-500/20', level: 'blue' }
};

window.setTrust = function(userId) {
  const adminLevel = document.querySelector('meta[name="current-user-admin-level"]')?.content;
  const isAdmin = adminLevel === 'admin' || adminLevel === 'superadmin';
  const isSuperadmin = adminLevel === 'superadmin';
  // we validate this on the server, dont kill me

  if (!isAdmin) {
    alert('you dont have human rights to do that');
    return;
  }

  let options = '🟢 Green (1) - Trusted\n🟡 Yellow (2) - Suspected\n🔵 Blue (4) - Unscored';
  if (isSuperadmin) {
    options = '🟢 Green (1) - Trusted\n🟡 Yellow (2) - Suspected\n🔴Red (3) - Convicted (banned)\n🔵 Blue (4) - Unscored';
  }

  const input = prompt(`set the trust for ${userId}\n\n${options}\n\nenter number or color`);
  if (!input) return;

  const normalizedInput = input.toLowerCase().trim();
  const trust = trusts[normalizedInput];

  if (!trust) {
    alert('read the popup idiot');
    return;
  }

  const levelForAPI = trust.level || normalizedInput;

  if (levelForAPI === 'red' && !isSuperadmin) {
    alert('nice try neon');
    return;
  }

  const reason = prompt('please explain why you are doing this to this poor soul');
  if (!reason || reason.trim() === '') {
    alert('you gotta put something down silly');
    return;
  }

  const notes = prompt('anything else you wanna add? (optional)');

  fetch(`/users/${userId}/update_trust_level`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
    },
    body: JSON.stringify({
      trust_level: levelForAPI,
      reason: reason.trim(),
      notes: notes ? notes.trim() : ''
    })
  })
  .then(response => {
    if (!response.ok) {
      return response.json().then(err => {
        throw new Error(err.error || `${response.status} ${response.statusText}`);
      });
    }
    return response.json();
  })
  .then(data => {
    const card = Array.from(document.querySelectorAll('[data-user-id]')).find(card => {
      const title = card.getAttribute('title') || '';
      return title.match(new RegExp(`User ID:\\s*${userId}\\b`));
      // what the fuck is this
    });
    if (card) {
      card.classList.remove('bg-red-500/20', 'bg-green-500/20', 'bg-yellow-500/20', 'bg-blue-500/20', 'bg-gray-500/20');
      card.classList.add(trust.bg);
      const span = card.querySelector('span.text-sm');
      if (span) {
        span.textContent = trust.emoji;
      }
    }

    alert(`set trust to ${trust.name}\nreason: ${reason}${notes ? '\nanything else? ' + notes : ''}`);
  })
  .catch(error => {
    console.error(error);
    alert('shit ' + error.message);
  });
};
</script>
