<h1>Welcome to Your Dashboard</h1>

<div class="dashboard-welcome panel">
  <h2>Welcome back, <%= user.email %>!</h2>
  <p class="welcome-message">Here's an overview of your URL Slicer activity:</p>

  <div class="dashboard-stats">
    <div class="stat-box">
      <i data-feather="link"></i>
      <span class="stat-value"><%= urls.length %></span>
      <span class="stat-label">Total URLs</span>
    </div>
    <div class="stat-box">
      <i data-feather="bar-chart-2"></i>
      <span class="stat-value" id="total-clicks">Loading...</span>
      <span class="stat-label">Total Clicks</span>
    </div>
    <div class="stat-box">
      <i data-feather="globe"></i>
      <span class="stat-value" id="total-countries">Loading...</span>
      <span class="stat-label">Countries Reached</span>
    </div>
  </div>
</div>

<div class="dashboard-tabs">
  <button id="shortener-tab" class="tab-button active">URL Shortener</button>
  <button id="urls-tab" class="tab-button">Shortened URLs</button>
  <button id="qr-codes-tab" class="tab-button">QR Codes</button>
</div>

<div id="shortener-content" class="tab-content">
  <div class="panel">
    <h2>Shorten a New URL</h2>
    <form id="shorten-form">
      <div class="form-group">
        <label for="original-url">Original URL:</label>
        <input type="text" id="original-url" name="originalUrl" required placeholder="https://example.com">
        <small id="url-error" class="error tab-content">Please enter a valid URL.</small>
      </div>
      <div class="form-group">
        <label for="custom-alias">Custom Alias (optional, 3-50 symbols):</label>
        <input type="text" id="custom-alias" name="customAlias" minlength="3" maxlength="50" pattern="[a-zA-Z0-9-_]+" placeholder="my-custom-url">
      </div>
      <div class="form-row">
        <div class="form-col">
          <label for="max-uses">Max Uses:</label>
          <input type="number" id="max-uses" name="maxUses" min="1" placeholder="Unlimited">
        </div>
        <div class="form-col">
          <label for="auto-delete-at">Auto Delete At:</label>
          <input type="datetime-local" id="auto-delete-at" name="autoDeleteAt">
        </div>
      </div>
      <div class="form-group">
        <label for="whitelist-mode">
          <input type="checkbox" id="whitelist-mode" name="whitelistMode">
          Enable Whitelist Mode
        </label>
      </div>
      <div class="form-group">
        <label for="allowed-countries">Allowed Countries (comma-separated):</label>
        <input type="text" id="allowed-countries" name="allowedCountries" placeholder="US, CA, UK">
      </div>
      <div class="form-group">
        <label for="blocked-countries">Blocked Countries (comma-separated):</label>
        <input type="text" id="blocked-countries" name="blockedCountries" placeholder="RU, CN">
      </div>
      <div class="form-group">
        <label for="password">Password Protection (optional):</label>
        <input type="password" id="password" name="password" placeholder="Leave blank for no password">
      </div>
      <button type="submit" class="btn btn-primary">Shorten URL</button>
    </form>
  </div>
</div>

<div id="urls-content" class="tab-content" style="display: none;">
  <div class="panel">
    <h2>Your Shortened URLs</h2>
    <div class="url-list-header">
      <span>Original URL</span>
      <span>Short URL</span>
      <span>Actions</span>
    </div>
    <ul class="url-list">
      <% urls.forEach(function(url) { %>
        <li class="url-item">
          <div class="url-info">
            <h3 class="original-url"><%= url.original_url %></h3>
            <p class="short-url">
              <a href="/<%= url.custom_alias || url.short_code %>" target="_blank">
                <%= url.custom_alias || url.short_code %>
              </a>
            </p>
            <p class="click-count" data-short-code="<%= url.custom_alias || url.short_code %>"></p>
            <p class="last-click">Last Clicked: <%= url.last_clicked_at ? new Date(url.last_clicked_at).toLocaleString() : 'Never' %></p> <!-- New Line -->
          </div>
          <div class="url-meta">
            <p>Created: <%= new Date(url.created_at).toLocaleString() %></p>
            <p>Max Uses: <%= url.max_uses || 'Unlimited' %></p>
            <p>Auto Delete: <%= url.auto_delete_at ? new Date(url.auto_delete_at).toLocaleString() : 'Never' %></p>
            <p>Whitelist Mode: <%= url.whitelist_mode ? 'On' : 'Off' %></p>
            <p>Allowed Countries: <%= url.allowed_countries || 'All' %></p>
            <p>Blocked Countries: <%= url.blocked_countries || 'None' %></p>
            <p>Password Protected: <%= url.password ? 'Yes' : 'No' %></p>
          </div>
          <div class="url-actions">
            <button class="btn btn-secondary view-stats" data-short-code="<%= url.custom_alias || url.short_code %>">
              <i data-feather="bar-chart-2"></i> <span>Stats</span>
            </button>
            <button class="btn btn-secondary edit-url" data-short-code="<%= url.custom_alias || url.short_code %>">
              <i data-feather="edit"></i> <span>Edit</span>
            </button>
            <button class="btn btn-secondary open-modal" data-modal="delete" data-short-code="<%= url.custom_alias || url.short_code %>">
              <i data-feather="trash-2"></i> <span>Delete</span>
            </button>
            <button class="btn btn-secondary" id="copy-button" data-short-code="<%= url.custom_alias || url.short_code %>">
              <i data-feather="copy"></i> <span>Copy</span>
            </button>
          </div>
        </li>
      <% }); %>
    </ul>
  </div>
</div>

<div id="qr-codes-content" class="tab-content" style="display: none;">
  <div class="panel">
    <h2>QR Codes for Your Shortened URLs</h2>
    <div class="qr-code-list">
      <% urls.forEach(function(url) { %>
        <div class="qr-code-item">
          <h3><%= url.original_url %></h3>
          <p>Short URL: <%= url.custom_alias || url.short_code %></p>
          <div class="qr-code-image" id="qr-<%= url.custom_alias || url.short_code %>">
            <p>Loading QR code...</p>
          </div>
          <button class="btn btn-secondary download-qr" data-short-code="<%= url.custom_alias || url.short_code %>">
            <i data-feather="download"></i> Download QR Code
          </button>
        </div>
      <% }); %>
    </div>
  </div>
</div>

<!-- Universal Modal -->
<div id="universal-modal" class="modal">
  <div class="modal-content panel">
    <span class="close-modal">&times;</span>
    <h2 id="modal-title"></h2>
    <div id="modal-body"></div>
    <div id="modal-actions"></div>
  </div>
</div>

<!-- Stats Modal -->
<div id="stats-modal" class="modal">
  <div class="modal-content panel">
    <span class="close-modal">&times;</span>
    <h2>URL Statistics</h2>
    <div id="stats-content"></div>
  </div>
</div>

<!-- Edit Modal -->
<div id="edit-modal" class="modal">
  <div class="modal-content panel">
    <span class="close-modal">&times;</span>
    <h2>Edit URL</h2>
    <form id="edit-form">
      <input type="hidden" id="edit-short-code" name="shortCode">
      <div class="form-group">
        <label for="edit-max-uses">Max Uses:</label>
        <input type="number" id="edit-max-uses" name="maxUses" min="1">
      </div>
      <div class="form-group">
        <label for="edit-auto-delete-at">Auto Delete At:</label>
        <input type="datetime-local" id="edit-auto-delete-at" name="autoDeleteAt">
      </div>
      <div class="form-group">
        <label for="edit-whitelist-mode">
          <input type="checkbox" id="edit-whitelist-mode" name="whitelistMode">
          Whitelist Mode
        </label>
      </div>
      <div class="form-group">
        <label for="edit-allowed-countries">Allowed Countries (comma-separated):</label>
        <input type="text" id="edit-allowed-countries" name="allowedCountries">
      </div>
      <div class="form-group">
        <label for="edit-blocked-countries">Blocked Countries (comma-separated):</label>
        <input type="text" id="edit-blocked-countries" name="blockedCountries">
      </div>
      <div class="form-group">
        <label for="edit-password">Password Protection:</label>
        <input type="password" id="edit-password" name="password" placeholder="Leave blank to keep current password">
      </div>
      <button type="submit" class="btn btn-primary">Update URL</button>
    </form>
  </div>
</div>

<script>
$(document).ready(function() {
  // Tab functionality
  $('.tab-button').click(function() {
    $('.tab-content').hide();
    $('.tab-button').removeClass('active');
    $(this).addClass('active');
    $('#' + $(this).attr('id').replace('-tab', '-content')).show();
  });

  $('#shortener-tab').click();

  // Form submission for shortening URLs
  $('#shorten-form').submit(function (e) {
    e.preventDefault(); // Prevent form submission
    const urlInput = $('#original-url');
    const urlError = $('#url-error');
    const urlPattern = /^(https?:\/\/[^\s$.?#].[^\s]*)$/i;
    // Validate URL
    if (!urlPattern.test(urlInput.val())) {
      urlError.show(); // Show the error message
      urlInput.focus(); // Focus the input field
    } else {
      urlError.hide(); // Hide the error message
      $.ajax({
        url: '/shorten',
        method: 'POST',
        data: $(this).serialize(),
        success: function (response) {
          var shortUrl = response.customAlias || response.shortCode;
          showModal('URL Shortened', 'URL shortened successfully! Short URL: ' + shortUrl, [
            { text: 'OK', class: 'btn-primary', click: function () { location.reload(); } }
          ]);
        },
        error: function (xhr) {
          showModal('Error', 'Error: ' + xhr.responseJSON.error, [
            { text: 'OK', class: 'btn-primary', click: function () { closeModal(); } }
          ]);
        }
      });
    }
  });

  // View stats
  $('.view-stats').click(function() {
    var shortCode = $(this).data('short-code');
    $.ajax({
      url: '/stats/' + shortCode,
      method: 'GET',
      success: function(response) {
        var statsHtml = '<p>Original URL: ' + response.url.original_url + '</p>';
        statsHtml += '<p>Total Clicks: ' + response.clicks.length + '</p>';
        statsHtml += '<p>Failed Authentication Attempts: ' + response.failedAttempts + '</p>';
        
        var countryStats = {};
        response.clicks.forEach(function(click) {
          countryStats[click.country] = (countryStats[click.country] || 0) + 1;
        });

        statsHtml += '<h3>Clicks by Country:</h3>';
        statsHtml += '<ul>';
        for (var country in countryStats) {
          statsHtml += '<li>' + country + ': ' + countryStats[country] + '</li>';
        }
        statsHtml += '</ul>';

        $('#stats-content').html(statsHtml);
        $('#stats-modal').show();
      },
      error: function(xhr) {
        showModal('Error', 'Error: ' + xhr.responseJSON.error, [
          {text: 'OK', class: 'btn-primary', click: function() { closeModal(); }}
        ]);
      }
    });
  });

  // Edit URL
  $('.edit-url').click(function() {
    var shortCode = $(this).data('short-code');
    $.ajax({
      url: '/url/' + shortCode,
      method: 'GET',
      success: function(response) {
        $('#edit-short-code').val(shortCode);
        $('#edit-max-uses').val(response.max_uses);
        $('#edit-auto-delete-at').val(new Date(response.auto_delete_at).toISOString().slice(0, 16));
        $('#edit-whitelist-mode').prop('checked', response.whitelist_mode);
        $('#edit-allowed-countries').val(response.allowed_countries);
        $('#edit-blocked-countries').val(response.blocked_countries);
        $('#edit-password').val(''); // Clear password field
        $('#edit-modal').show();
      },
      error: function(xhr) {
        showModal('Error', 'Error: ' + xhr.responseJSON.error, [
          {text: 'OK', class: 'btn-primary', click: function() { closeModal(); }}
        ]);
      }
    });
  });

  $('#edit-form').submit(function(e) {
    e.preventDefault();
    var shortCode = $('#edit-short-code').val();
    $.ajax({
      url: '/url/' + shortCode,
      method: 'PUT',
      data: $(this).serialize(),
      success: function() {
        showModal('Success', 'URL updated successfully!', [
          {text: 'OK', class: 'btn-primary', click: function() { location.reload(); }}
        ]);
      },
      error: function(xhr) {
        showModal('Error', 'Error: ' + xhr.responseJSON.error, [
          {text: 'OK', class: 'btn-primary', click: function() { closeModal(); }}
        ]);
      }
    });
  });

  // Universal modal opener
  $('.open-modal').click(function() {
    var modalType = $(this).data('modal');
    var shortCode = $(this).data('short-code');
    
    if (modalType === 'delete') {
      showModal('Confirm Deletion', 'Are you sure you want to delete this URL?<br>Short URL: <span class="highlight">' + shortCode + '</span>', [
        {text: 'Delete', class: 'btn-primary', click: function() { deleteUrl(shortCode); }},
        {text: 'Cancel', class: 'btn-secondary', click: function() { closeModal(); }}
      ]);
    }
  });

  // Close modals
  $('.close-modal').click(function() {
    closeModal();
  });

  $(window).click(function(event) {
    if ($(event.target).hasClass('modal')) {
      closeModal();
    }
  });

  // Universal modal functions
  function showModal(title, body, actions) {
    $('#modal-title').html(title);
    $('#modal-body').html(body);
    $('#modal-actions').empty();
    actions.forEach(function(action) {
      $('<button>')
        .text(action.text)
        .addClass('btn ' + action.class)
        .click(action.click)
        .appendTo('#modal-actions');
    });
    $('#universal-modal').show();
  }

  function closeModal() {
    $('.modal').hide();
  }

  // Delete URL function
  function deleteUrl(shortCode) {
    $.ajax({
      url: '/url/' + shortCode,
      method: 'DELETE',
      success: function() {
        showModal('Success', 'URL deleted successfully!', [
          {text: 'OK', class: 'btn-primary', click: function() { location.reload(); }}
        ]);
      },
      error: function(xhr) {
        showModal('Error', 'Error: ' + xhr.responseJSON.error, [
          {text: 'OK', class: 'btn-primary', click: function() { closeModal(); }}
        ]);
      }
    });
  }

  // Copy to clipboard
  $('.url-actions').on('click', '#copy-button', function() {
    var shortCode = $(this).data('short-code');
    var dummy = document.createElement('input');
    document.body.appendChild(dummy);
    $.ajax({
      url: '/find/' + shortCode,
      method: 'GET',
      success: function(response) {
        dummy.value = response.fullUrl;
        dummy.select();
        document.execCommand('copy');
        document.body.removeChild(dummy);
        showModal('Success', 'Short URL copied to clipboard!', [
          {text: 'OK', class: 'btn-primary', click: function() { closeModal(); }}
        ]);
      },
      error: function(xhr) {
        showModal('Error', 'Error: ' + xhr.responseJSON.error, [
          {text: 'OK', class: 'btn-primary', click: function() { closeModal(); }}
        ]);
      }
    });
  });

  // Update dashboard stats
  function updateDashboardStats() {
    let totalClicks = 0;
    let countries = new Set();

    $('.click-count').each(function() {
      const urlId = $(this).data('short-code');
      $.get('/stats/' + urlId, function(data) {
        const clicks = data.clicks.length;
        totalClicks += clicks;
        $(this).text(clicks + ' clicks');

        data.clicks.forEach(click => countries.add(click.country));

        $('#total-clicks').text(totalClicks);
        $('#total-countries').text(countries.size);
      });
    });
  }

  updateDashboardStats();

  // Toggle whitelist mode
  $('#whitelist-mode').change(function() {
    if ($(this).is(':checked')) {
      $('#blocked-countries').prop('disabled', true).val('');
      $('#allowed-countries').prop('disabled', false);
    } else {
      $('#blocked-countries').prop('disabled', false);
      $('#allowed-countries').prop('disabled', true).val('');
    }
  });

  $('#edit-whitelist-mode').change(function() {
    if ($(this).is(':checked')) {
      $('#edit-blocked-countries').prop('disabled', true).val('');
      $('#edit-allowed-countries').prop('disabled', false);
    } else {
      $('#edit-blocked-countries').prop('disabled', false);
      $('#edit-allowed-countries').prop('disabled', true).val('');
    }
  });

  // Initialize whitelist mode state
  $('#whitelist-mode').trigger('change');
  $('#edit-whitelist-mode').trigger('change');

  // Refresh stats periodically
  setInterval(updateDashboardStats, 60000); // Update every minute

  // QR Code tab functionality
  $('#qr-codes-tab').click(function() {
    $('.tab-content').hide();
    $('.tab-button').removeClass('active');
    $(this).addClass('active');
    $('#qr-codes-content').show();
    loadQRCodes();
  });

  function loadQRCodes() {
    $('.qr-code-image').each(function() {
      const shortCode = $(this).attr('id').split('-')[1];
      $.get(`/qr/${shortCode}`, function(data) {
        $(`#qr-${shortCode}`).html(`<img src="${data.qrCode}" alt="QR Code for ${shortCode}">`);
      }).fail(function() {
        $(`#qr-${shortCode}`).html('<p>Failed to load QR code</p>');
      });
    });
  }

  $('.download-qr').click(function() {
    const shortCode = $(this).data('short-code');
    const qrImage = $(`#qr-${shortCode} img`).attr('src');
    if (qrImage) {
      const link = document.createElement('a');
      link.href = qrImage;
      link.download = `qr-code-${shortCode}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  });

  // Initialize Feather icons
  feather.replace();
});
</script>
