{{define "web-upload"}}
<h2>Web upload</h2>
<p>Upload files directly from your browser. Files are temporary and automatically deleted after 24 hours.</p>

<div class="upload-card">
  <form id="web-upload-form" class="upload-form" aria-label="Web upload form">
    <div class="form-row">
      <input type="file" id="file-input" name="file" multiple required aria-label="Choose files to upload" data-rybbit-event="Select files">
    </div>
    <div class="form-row">
      <button type="submit" id="upload-btn" class="btn-primary" data-rybbit-event="Upload">Upload</button>
    </div>
  </form>

  <div id="upload-status" class="upload-status" role="status" aria-live="polite" hidden></div>

  <div id="upload-result" class="upload-result" hidden>
    <div id="upload-results-list"></div>
  </div>
</div>

<script>
(function(){
  const form = document.getElementById('web-upload-form');
  const fileInput = document.getElementById('file-input');
  const statusEl = document.getElementById('upload-status');
  const resultEl = document.getElementById('upload-result');
  const uploadBtn = document.getElementById('upload-btn');

  function showStatus(msg, type) {
    statusEl.textContent = msg;
    statusEl.hidden = false;
    statusEl.className = 'upload-status ' + (type || '');
  }
  function clearStatus(){
    statusEl.hidden = true;
    statusEl.textContent = '';
  }
  function setLoading(isLoading){
    uploadBtn.disabled = isLoading;
    uploadBtn.textContent = isLoading ? 'Uploading…' : 'Upload';
  }

  form.addEventListener('submit', async function(e){
    e.preventDefault();
    clearStatus();
    resultEl.hidden = true;

    const files = fileInput.files;
    if(!files || files.length === 0){
      showStatus('Please choose at least one file.', 'error');
      return;
    }

    setLoading(true);
    const resultsList = document.getElementById('upload-results-list');
    resultsList.innerHTML = '';
    
    let successCount = 0;
    let totalFiles = files.length;
    
    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        showStatus(`Uploading file ${i + 1} of ${totalFiles}: ${file.name}`, 'info');
        
        const data = new FormData();
        data.append('file', file);
        
        try {
          const resp = await fetch('/upload', { method: 'POST', body: data });
          const contentType = resp.headers.get('content-type') || '';
          
          if(!resp.ok){
            let message = 'Upload failed';
            if (contentType.includes('application/json')) {
              const errJson = await resp.json().catch(()=>({}));
              if (errJson && errJson.error) message = errJson.error;
            } else {
              message = await resp.text();
            }
            addFileResult(file.name, null, message, false);
            continue;
          }
          
          const json = contentType.includes('application/json') ? await resp.json() : null;
          const url = json && json.url ? json.url : null;
          
          if(!url){
            addFileResult(file.name, null, 'Upload succeeded but no URL was returned', false);
            continue;
          }
          
          addFileResult(file.name, url, 'Success', true);
          successCount++;
        } catch (err) {
          addFileResult(file.name, null, 'Network error', false);
        }
      }
      
      resultEl.hidden = false;
      if (successCount === totalFiles) {
        showStatus(`All ${totalFiles} files uploaded successfully!`, 'success');
      } else if (successCount > 0) {
        showStatus(`${successCount} of ${totalFiles} files uploaded successfully.`, 'warning');
      } else {
        showStatus('All uploads failed.', 'error');
      }
    } finally {
      setLoading(false);
    }
  });

  function addFileResult(filename, url, message, success) {
    const resultsList = document.getElementById('upload-results-list');
    const resultDiv = document.createElement('div');
    resultDiv.className = 'file-result ' + (success ? 'success' : 'error');
    
    if (success && url) {
      resultDiv.innerHTML = `
        <p><strong>${filename}</strong> - ${message}</p>
        <p>
          <span>Download URL:</span>
          <a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>
        </p>
        <div class="actions">
          <button class="btn-secondary copy-link-btn" type="button" data-url="${url}">Copy link</button>
        </div>
      `;
    } else {
      resultDiv.innerHTML = `
        <p><strong>${filename}</strong> - ${message}</p>
      `;
    }
    
    resultsList.appendChild(resultDiv);
  }
  
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('copy-link-btn')) {
      const url = e.target.getAttribute('data-url');
      if (!url) return;
      
      navigator.clipboard.writeText(url).then(() => {
        const original = e.target.textContent;
        e.target.textContent = 'Copied!';
        e.target.classList.add('copied');
        setTimeout(() => {
          e.target.textContent = original;
          e.target.classList.remove('copied');
        }, 1500);
      }).catch(() => {
        const original = e.target.textContent;
        e.target.textContent = 'Failed';
        setTimeout(() => {
          e.target.textContent = original;
        }, 1500);
      });
    }
  });
})();
</script>
{{end}}
