{% extends "base.html" %}
{% block title %}Dropbox Setup{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
  <div class="mb-8">
    {% if user_mode %}
    <!-- ── User-mode header ──────────────────────────────────────────── -->
    <div class="mb-4">
      <a href="/integrations" class="inline-flex items-center text-sm text-indigo-600 hover:text-indigo-800">
        <i class="fas fa-arrow-left mr-1" aria-hidden="true"></i> Back to Integrations
      </a>
    </div>
    <h1 class="text-3xl font-bold mb-2">
      Connect Dropbox
      {% if integration_name %}<span class="text-gray-500 text-2xl font-normal">— {{ integration_name }}</span>{% endif %}
    </h1>
    <p class="text-gray-600 mb-4">
      Authorize DocuElevate to access your Dropbox account. Your credentials are stored securely in your personal integration record.
    </p>
    {% if is_configured %}
    <div class="bg-green-50 border-l-4 border-green-500 text-green-700 p-4 my-4" role="alert">
      <p class="font-semibold">✓ Already authorized</p>
      <p class="text-sm mt-1">This integration already has credentials. You can re-authorize below to refresh or update them.
      {% if folder_path %}<br><strong>Folder:</strong> {{ folder_path }}{% endif %}
      </p>
    </div>
    {% else %}
    <div class="bg-blue-50 border-l-4 border-blue-500 text-blue-700 p-4 my-4" role="alert">
      <p class="font-semibold">Authorization required</p>
      <p class="text-sm mt-1">Complete the wizard below to grant access to your Dropbox account.
      {% if folder_path %}<br><strong>Target folder:</strong> {{ folder_path }}{% endif %}
      </p>
    </div>
    {% endif %}
    {% else %}
    <!-- ── Admin-mode header ─────────────────────────────────────────── -->
    <h1 class="text-3xl font-bold mb-2">Dropbox Integration Setup</h1>
    <p class="text-gray-600 mb-4">
      Configure the Dropbox integration for DocuElevate using our setup wizard.
    </p>

    <div class="bg-blue-100 border-l-4 border-blue-500 text-blue-700 p-4 my-4" role="alert">
      <p class="font-bold">Current Status:</p>
      <p>Dropbox integration is
        {% if is_configured %}
          <span class="text-green-700 font-semibold">configured</span>.
        {% else %}
          <span class="text-red-700 font-semibold">not configured</span>.
        {% endif %}
      </p>
      {% if folder_path %}
      <p class="mt-2"><strong>Target folder:</strong> {{ folder_path }}</p>
      {% endif %}
    </div>

    <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 my-4">
      <div class="flex">
        <div class="flex-shrink-0">
          <svg class="h-5 w-5 text-yellow-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
          </svg>
        </div>
        <div class="ml-3">
          <p class="text-sm text-yellow-700">
            <strong>Note:</strong> You need to create a Dropbox app and obtain API credentials. The setup wizard will guide you through this process.
          </p>
        </div>
      </div>
    </div>
    {% endif %}
  </div>

  <div class="bg-white shadow-md rounded-lg p-6 mb-8">
    <h2 class="text-2xl font-semibold mb-4">Quick Setup Guide</h2>

    <div class="mb-6">
      <h3 class="text-xl font-medium mb-4">Step 1: Create a Dropbox App</h3>
      <ol class="list-decimal ml-6 space-y-3">
        <li>Go to the <a href="https://www.dropbox.com/developers/apps" target="_blank" class="text-blue-600 hover:underline">Dropbox Developer Apps Console</a></li>
        <li>Click "Create app"</li>
        <li>Select "Scoped access" for API</li>
        <li>Choose "Full Dropbox" access (or "App folder" for more restricted access)</li>
        <li>Give your app a name (e.g., "DocuElevate")</li>
        <li>Click "Create app"</li>
      </ol>
    </div>

    <div class="mb-6">
      <h3 class="text-xl font-medium mb-4">Step 2: Configure App Permissions</h3>
      <ol class="list-decimal ml-6 space-y-3">
        <li>In your app's settings page, go to the "Permissions" tab</li>
        <li>Enable the following permissions:
          <ul class="list-disc ml-6 mt-1">
            <li><code class="bg-gray-100 p-1">files.content.write</code> (to upload files)</li>
            <li><code class="bg-gray-100 p-1">files.content.read</code> (if you need to read file content)</li>
          </ul>
        </li>
        <li>Click "Submit" to save changes</li>
      </ol>
    </div>

    <div class="mb-6">
      <h3 class="text-xl font-medium mb-4">Step 3: Set OAuth 2 Redirect URI</h3>
      <ol class="list-decimal ml-6 space-y-3">
        <li>In your app's settings page, go to the "OAuth 2" section</li>
        <li>Add a redirect URI: <code class="bg-gray-100 p-1">{{ callback_url }}</code></li>
        <li>Click "Add" to save the redirect URI</li>
      </ol>
    </div>
  </div>

  <div class="bg-white shadow-md rounded-lg p-6 mb-8">
    <h2 class="text-2xl font-semibold mb-4">
      {% if user_mode %}OAuth Wizard{% else %}Complete Setup with Wizard{% endif %}
    </h2>

    <div class="space-y-4">
      {% if user_mode and global_creds_available %}
      <!-- Global credentials mode: no app credentials required from the user -->
      <div class="bg-blue-50 border border-blue-200 rounded-md p-4" role="note">
        <div class="flex items-start">
          <svg class="h-5 w-5 text-blue-400 mt-0.5 mr-3 flex-shrink-0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
          </svg>
          <div>
            <p class="text-sm font-medium text-blue-800">Using shared application credentials</p>
            <p class="text-sm text-blue-700 mt-1">Your administrator has enabled shared Dropbox app credentials. You can authorize your account without supplying your own App Key and Secret.</p>
          </div>
        </div>
      </div>

      {% if folder_path %}
      <div class="bg-gray-50 border border-gray-200 rounded-md px-3 py-2">
        <p class="text-xs text-gray-500">Target folder (from integration settings)</p>
        <p class="text-sm font-mono text-gray-700">{{ folder_path }}</p>
      </div>
      {% endif %}

      <div>
        <button id="start-auth-flow-global" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
          <i class="fab fa-dropbox mr-2" aria-hidden="true"></i>
          Authorize with Dropbox
        </button>
      </div>
      {% else %}
      <div>
        <label for="app-key" class="block text-sm font-medium text-gray-700">App Key <span class="text-red-500" aria-hidden="true">*</span></label>
        <input type="text" id="app-key" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="Enter your Dropbox app key" value="{{ app_key_value }}">
      </div>

      <div>
        <label for="app-secret" class="block text-sm font-medium text-gray-700">App Secret <span class="text-red-500" aria-hidden="true">*</span></label>
        <input type="password" id="app-secret" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="Enter your Dropbox app secret" value="{{ app_secret_value }}">
      </div>

      {% if not user_mode %}
      <div>
        <label for="folder-path" class="block text-sm font-medium text-gray-700">Folder Path (Optional)</label>
        <input type="text" id="folder-path" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="/Documents/Uploads" value="{{ folder_path }}">
        <p class="text-xs text-gray-500 mt-1">Enter the folder path where files should be uploaded (e.g., /Documents/Uploads)</p>
      </div>
      {% else %}
      {% if folder_path %}
      <div class="bg-gray-50 border border-gray-200 rounded-md px-3 py-2">
        <p class="text-xs text-gray-500">Target folder (from integration settings)</p>
        <p class="text-sm font-mono text-gray-700">{{ folder_path }}</p>
      </div>
      {% endif %}
      {% endif %}

      <div>
        <button id="start-auth-flow" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
          Start Authentication Flow
        </button>
      </div>
      {% endif %}

      <!-- Token validation and status (admin mode only) -->
      {% if not user_mode %}
      <div id="token-status" class="mt-6 {{ 'hidden' if not is_configured else '' }}">
        <div class="rounded-md {{ 'bg-green-50' if is_configured else 'bg-yellow-50' }} p-4">
          <div class="flex">
            <div class="flex-shrink-0">
              {% if is_configured %}
              <svg class="h-5 w-5 text-green-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
              </svg>
              {% else %}
              <svg class="h-5 w-5 text-yellow-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
              </svg>
              {% endif %}
            </div>
            <div class="ml-3">
              <p class="text-sm font-medium {{ 'text-green-800' if is_configured else 'text-yellow-800' }}">
                {% if is_configured %}
                  Dropbox integration is properly configured! Your refresh token is valid.
                {% else %}
                  Dropbox integration is not completely configured or token may be invalid.
                {% endif %}
              </p>
            </div>
          </div>
        </div>

        <div class="mt-4 flex space-x-3">
          <button id="test-token" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
            Test Token
          </button>
          <button id="refresh-token-btn" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
            Refresh Token
          </button>
        </div>

        <!-- Configuration for Worker Nodes section (admin only) -->
        <div class="mt-6 p-4 bg-gray-100 rounded-md">
          <h3 class="font-medium text-lg mb-2">Configuration for Worker Nodes</h3>
          <p class="text-sm text-gray-600 mb-3">
            Copy these environment variables to configure all worker nodes:
          </p>

          <div class="relative">
            <pre id="env-vars" class="bg-gray-800 text-green-400 text-sm p-3 rounded overflow-x-auto"><code>DROPBOX_APP_KEY={{ app_key_value }}
DROPBOX_APP_SECRET={{ app_secret_value|default('YOUR_APP_SECRET', true) }}
DROPBOX_REFRESH_TOKEN={{ refresh_token_value|default('YOUR_REFRESH_TOKEN', true) }}
DROPBOX_FOLDER={{ folder_path|default('/Documents/Uploads', true) }}</code></pre>

            <button id="copy-env-vars" class="absolute top-2 right-2 bg-gray-700 hover:bg-gray-600 text-white text-xs py-1 px-2 rounded">
              Copy
            </button>
          </div>

          <p class="text-xs text-gray-500 mt-2">
            Add these variables to your .env file or environment configuration.
          </p>
        </div>
      </div>
      {% endif %}
    </div>
  </div>

  <div class="bg-white shadow-md rounded-lg p-6 mb-8">
    <div class="flex items-start">
      <div class="flex-shrink-0">
        <svg class="h-6 w-6 text-blue-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      </div>
      <div class="ml-3">
        <h3 class="text-lg font-medium">Need More Information?</h3>
        <p class="mt-1 text-sm text-gray-600">
          For detailed instructions and troubleshooting, refer to the
          <a href="/docs/DropboxSetup.md" target="_blank" class="text-blue-600 hover:underline">Dropbox Setup Documentation</a>.
        </p>
      </div>
    </div>
  </div>

  <div class="mt-8">
    {% if user_mode %}
    <a href="/integrations" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
      <i class="fas fa-arrow-left mr-2" aria-hidden="true"></i> Back to Integrations
    </a>
    {% else %}
    <a href="/status" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
      Back to Status
    </a>
    {% endif %}
  </div>

  <!-- Result Modal -->
  <div id="resultModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full z-50" aria-modal="true" role="dialog" aria-labelledby="modalTitle">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-1/2 lg:w-1/3 shadow-lg rounded-md bg-white">
      <div class="mt-3 text-center">
        <div id="modalIcon" class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 mb-4">
          <!-- Icon will be injected by JS -->
        </div>
        <h3 id="modalTitle" class="text-lg leading-6 font-medium text-gray-900">Success</h3>
        <div class="mt-2 px-7 py-3">
          <p id="modalMessage" class="text-sm text-gray-500">
            Operation completed successfully.
          </p>
        </div>
        <div class="items-center px-4 py-3">
          <button id="modalClose" class="px-4 py-2 bg-blue-500 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-300">
            Close
          </button>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
  const userMode = {{ 'true' if user_mode else 'false' }};
  const globalCredsAvailable = {{ 'true' if global_creds_available else 'false' }};
  // Redirect URI for OAuth: prefer server-provided value (respects PUBLIC_BASE_URL),
  // fall back to window.location.origin for resilience.
  const dropboxCallbackUrl = {{ callback_url | tojson }} || (window.location.origin + "/dropbox-callback");

  // Store integration_id if provided (for per-user OAuth flow)
  const integrationId = "{{ integration_id or '' }}";
  if (integrationId) {
    sessionStorage.setItem('oauth_integration_id', integrationId);
  }

  // Elements
  const startAuthFlowBtn = document.getElementById('start-auth-flow');
  const startAuthFlowGlobalBtn = document.getElementById('start-auth-flow-global');
  const testTokenBtn = document.getElementById('test-token');
  const refreshTokenBtn = document.getElementById('refresh-token-btn');
  const tokenStatus = document.getElementById('token-status');
  const appSecretInput = document.getElementById('app-secret');

  // Modal elements
  const resultModal = document.getElementById('resultModal');
  const modalTitle = document.getElementById('modalTitle');
  const modalMessage = document.getElementById('modalMessage');
  const modalIcon = document.getElementById('modalIcon');
  const modalClose = document.getElementById('modalClose');

  // Modal functions
  function showModal(status, title, message) {
    modalTitle.textContent = title;
    modalMessage.textContent = message;

    // Set the appropriate icon
    if (status === 'success') {
      modalIcon.innerHTML = `
        <svg class="h-6 w-6 text-green-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
        </svg>
      `;
      modalIcon.className = 'mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 mb-4';
    } else {
      modalIcon.innerHTML = `
        <svg class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
      `;
      modalIcon.className = 'mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 mb-4';
    }

    resultModal.classList.remove('hidden');
  }

  function hideModal() {
    resultModal.classList.add('hidden');
  }

  // Close modal when clicking the close button
  modalClose.addEventListener('click', hideModal);

  // Close modal when clicking outside of it
  resultModal.addEventListener('click', function(e) {
    if (e.target === resultModal) {
      hideModal();
    }
  });

  // Global-credentials "Authorize with Dropbox" button (user mode, admin-provided creds)
  if (startAuthFlowGlobalBtn) {
    startAuthFlowGlobalBtn.addEventListener('click', async function() {
      startAuthFlowGlobalBtn.disabled = true;
      startAuthFlowGlobalBtn.innerHTML = '<span class="animate-spin inline-block mr-2">⟳</span> Redirecting…';
      try {
        const resp = await fetch('/api/dropbox/global-authorize-url');
        if (!resp.ok) {
          const err = await resp.json().catch(() => ({}));
          showModal('error', 'Error', err.detail || 'Could not retrieve authorization URL.');
          startAuthFlowGlobalBtn.disabled = false;
          startAuthFlowGlobalBtn.innerHTML = '<i class="fab fa-dropbox mr-2" aria-hidden="true"></i>Authorize with Dropbox';
          return;
        }
        const data = await resp.json();
        // Signal to the callback that global credentials should be used for the exchange
        sessionStorage.setItem('dropbox_use_global_creds', 'true');
        window.location.href = data.authorize_url;
      } catch (err) {
        showModal('error', 'Network Error', err.message || 'Unknown error');
        startAuthFlowGlobalBtn.disabled = false;
        startAuthFlowGlobalBtn.innerHTML = '<i class="fab fa-dropbox mr-2" aria-hidden="true"></i>Authorize with Dropbox';
      }
    });
  }

  // Start Authentication Flow button click
  if (startAuthFlowBtn) {
    startAuthFlowBtn.addEventListener('click', function() {
    const appKey = document.getElementById('app-key').value.trim();
    const appSecret = appSecretInput.value.trim();
    const redirectUri = dropboxCallbackUrl;

    if (!appKey) {
      showModal('error', 'Validation Error', 'Please enter your App Key');
      return;
    }

    if (!appSecret) {
      showModal('error', 'Validation Error', 'Please enter your App Secret');
      return;
    }

    // Save app key and app secret to session storage temporarily
    sessionStorage.setItem('dropbox_app_key', appKey);
    sessionStorage.setItem('dropbox_app_secret', appSecret);

    // In admin mode also store folder path; in user mode the config is already set
    if (!userMode) {
      const folderPathEl = document.getElementById('folder-path');
      if (folderPathEl && folderPathEl.value.trim()) {
        sessionStorage.setItem('dropbox_folder_path', folderPathEl.value.trim());
      }
    }

    // Generate the authorization URL
    const authUrl = `https://www.dropbox.com/oauth2/authorize?client_id=${encodeURIComponent(appKey)}&response_type=code&token_access_type=offline&redirect_uri=${encodeURIComponent(redirectUri)}`;

    // Redirect the user to the Dropbox login page
    window.location.href = authUrl;
  });
  } // end if (startAuthFlowBtn)

  // Test Token button click (admin mode only)
  if (testTokenBtn) {
    testTokenBtn.addEventListener('click', function() {
      testTokenBtn.innerHTML = '<span class="animate-spin inline-block mr-2">⟳</span> Testing...';
      testTokenBtn.disabled = true;

      fetch('/api/dropbox/test-token')
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') {
            showModal('success', 'Token Valid', `${data.message} ${data.account ? 'as ' + data.account : ''}`);
          } else {
            if (data.message && data.message.includes('invalid_grant') || data.needs_reauth) {
              showModal('error', 'Token Invalid', 'Your Dropbox token has expired or is invalid. Please obtain a new token.');
              // Give option to start new auth flow
              modalClose.textContent = "Get New Token";
              modalClose.addEventListener('click', function onGetNewToken() {
                startAuthFlowBtn.click();
                // Remove this special event handler after use
                modalClose.removeEventListener('click', onGetNewToken);
                modalClose.textContent = "Close";
              }, { once: true });
            } else {
              showModal('error', 'Token Test Failed', data.message);
            }
          }
        })
        .catch(error => {
          showModal('error', 'Connection Error', 'Error testing token: ' + error.message);
        })
        .finally(() => {
          testTokenBtn.innerHTML = 'Test Token';
          testTokenBtn.disabled = false;
        });
    });
  }

  // Refresh Token button click (admin mode only)
  if (refreshTokenBtn) {
    refreshTokenBtn.addEventListener('click', function() {
      showModal('info', 'Confirm', 'This will start a new authentication flow to obtain a fresh token from Dropbox. Continue?');
      modalClose.textContent = "Cancel";

      // Add a confirm button
      const confirmBtn = document.createElement('button');
      confirmBtn.className = 'ml-2 px-4 py-2 bg-green-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-300';
      confirmBtn.textContent = 'Continue';
      confirmBtn.addEventListener('click', function() {
        hideModal();
        startAuthFlowBtn.click();
      });

      // Add to modal
      modalClose.parentNode.appendChild(confirmBtn);

      // Make sure to remove the confirm button when modal is closed
      const removeConfirmBtn = function() {
        if (confirmBtn.parentNode) {
          confirmBtn.parentNode.removeChild(confirmBtn);
        }
        modalClose.textContent = "Close";
        modalClose.removeEventListener('click', removeConfirmBtn);
      };

      modalClose.addEventListener('click', removeConfirmBtn, { once: true });
    });
  }

  // Copy Environment Variables Button (admin mode only)
  const copyEnvVarsBtn = document.getElementById('copy-env-vars');
  if (copyEnvVarsBtn) {
    copyEnvVarsBtn.addEventListener('click', function() {
      const envVarsText = document.getElementById('env-vars').textContent;
      navigator.clipboard.writeText(envVarsText)
        .then(() => {
          const originalText = copyEnvVarsBtn.textContent;
          copyEnvVarsBtn.textContent = 'Copied!';
          copyEnvVarsBtn.classList.add('bg-green-700');
          setTimeout(() => {
            copyEnvVarsBtn.textContent = originalText;
            copyEnvVarsBtn.classList.remove('bg-green-700');
          }, 2000);
        })
        .catch(err => {
          console.error('Failed to copy: ', err);
          showModal('error', 'Copy Failed', 'Failed to copy text to clipboard');
        });
    });
  }

  // Try to retrieve app secret from session storage (if coming back from auth)
  if (appSecretInput && !appSecretInput.value && sessionStorage.getItem('dropbox_app_secret')) {
    appSecretInput.value = sessionStorage.getItem('dropbox_app_secret');
    // Clear it after use
    sessionStorage.removeItem('dropbox_app_secret');
  }

  // If token is not configured but we have an app key, show the token status section (admin mode)
  if (tokenStatus && document.getElementById('app-key').value && !tokenStatus.classList.contains('hidden')) {
    tokenStatus.classList.remove('hidden');
  }
});
</script>
{% endblock %}
