<nav class="navbar navbar-expand-md navbar-dark">
  <div class="container-fluid">
    <a class="navbar-brand d-flex align-items-center" href="#">
      <img src="assets/icons/android-chrome-192x192.png" alt="MeTube Logo" height="32" class="me-2">
      MeTube
    </a>
    <div class="download-metrics">
      <div class="metric" *ngIf="activeDownloads > 0">
        <fa-icon [icon]="faDownload" class="text-primary"></fa-icon>
        <span>{{activeDownloads}} downloading</span>
      </div>
      <div class="metric" *ngIf="queuedDownloads > 0">
        <fa-icon [icon]="faClock" class="text-warning"></fa-icon>
        <span>{{queuedDownloads}} queued</span>
      </div>
      <div class="metric" *ngIf="completedDownloads > 0">
        <fa-icon [icon]="faCheck" class="text-success"></fa-icon>
        <span>{{completedDownloads}} completed</span>
      </div>
      <div class="metric" *ngIf="failedDownloads > 0">
        <fa-icon [icon]="faTimesCircle" class="text-danger"></fa-icon>
        <span>{{failedDownloads}} failed</span>
      </div>
      <div class="metric" *ngIf="(totalSpeed | speed) !== ''">
        <fa-icon [icon]="faTachometerAlt" class="text-info"></fa-icon>
        <span>{{totalSpeed | speed }}</span>
      </div>
    </div>
    <!--
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsDefault" aria-controls="navbarsDefault" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarsDefault">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
        </li>
      </ul>
    </div>
    -->
    <div class="navbar-nav ms-auto">
      <div class="nav-item dropdown">
        <button class="btn btn-link nav-link py-2 px-0 px-sm-2 dropdown-toggle d-flex align-items-center"
                id="theme-select"
                type="button"
                aria-expanded="false"
                data-bs-toggle="dropdown"
                data-bs-display="static">
          <fa-icon [icon]="activeTheme.icon"></fa-icon>
        </button>
        <ul class="dropdown-menu dropdown-menu-end position-absolute" aria-labelledby="theme-select">
          <li *ngFor="let theme of themes">
            <button type="button" class="dropdown-item d-flex align-items-center" [ngClass]="{'active' : activeTheme == theme}" (click)="themeChanged(theme)">
              <span class="me-2 opacity-50">
                <fa-icon [icon]="theme.icon"></fa-icon>
              </span>
              {{ theme.displayName }}
              <span class="ms-auto" [ngClass]="{'d-none' : activeTheme != theme}">
                <fa-icon [icon]="faCheck"></fa-icon>
              </span>
            </button>
          </li>
        </ul>
      </div>
    </div>
  </div>
</nav>

<main role="main" class="container container-xl">
  <!-- Events Display Area -->
  <div *ngIf="events.length > 0" class="events-container mb-3">
    <div class="events-header">
      <div class="d-flex align-items-center justify-content-between">
        <h6 class="mb-0">
          <fa-icon [icon]="faClock" class="me-2"></fa-icon>
          Recent Events
        </h6>
        <button type="button" 
                class="btn btn-sm btn-outline-secondary" 
                (click)="clearEvents()"
                title="Clear all events">
          <fa-icon [icon]="faTrashAlt" class="me-1"></fa-icon>
          Clear
        </button>
      </div>
    </div>
    <div class="events-list">
      <div *ngFor="let event of events" class="event-item" [ngClass]="'event-' + event.type">
        <div class="event-icon">
          <fa-icon [icon]="faTimesCircle"></fa-icon>
        </div>
        <div class="event-content">
          <div class="event-message">{{ event.message }}</div>
          <div class="event-url" *ngIf="event.url" [title]="event.url">
            {{ event.url }}
          </div>
        </div>
        <div class="event-time">
          {{ getRelativeTime(event.timestamp) }}
        </div>
      </div>
    </div>
  </div>

  <form #f="ngForm">
    <div class="container add-url-box">
      <!-- Main URL Input with Download Button -->
      <div class="row mb-4">
        <div class="col">
          <div class="input-group input-group-lg shadow-sm">
            <input type="text" 
                   autocomplete="off" 
                   spellcheck="false" 
                   class="form-control form-control-lg" 
                   placeholder="Enter video or playlist URL" 
                   name="addUrl" 
                   [(ngModel)]="addUrl" 
                   [disabled]="addInProgress || downloads.loading">
            <button class="btn btn-primary btn-lg px-4" 
                    type="submit" 
                    (click)="addDownload()" 
                    [disabled]="addInProgress || downloads.loading">
              <span class="spinner-border spinner-border-sm" role="status" id="add-spinner" *ngIf="addInProgress"></span>
              {{ addInProgress ? "Adding..." : "Download" }}
            </button>
          </div>
        </div>
      </div>

      <!-- Options Row -->
      <div class="row mb-3 g-3">
        <div class="col-md-4">
          <div class="input-group">
            <span class="input-group-text">Quality</span>
            <select class="form-select" 
                    name="quality" 
                    [(ngModel)]="quality" 
                    (change)="qualityChanged()" 
                    [disabled]="addInProgress || downloads.loading">
              <option *ngFor="let q of qualities" [ngValue]="q.id">{{ q.text }}</option>
            </select>
          </div>
        </div>
        <div class="col-md-4">
          <div class="input-group">
            <span class="input-group-text">Format</span>
            <select class="form-select" 
                    name="format" 
                    [(ngModel)]="format" 
                    (change)="formatChanged()" 
                    [disabled]="addInProgress || downloads.loading">
              <option *ngFor="let f of formats" [ngValue]="f.id">{{ f.text }}</option>
            </select>
          </div>
        </div>
        <div class="col-md-4">
          <button type="button" 
                  class="btn btn-outline-secondary w-100 h-100" 
                  (click)="toggleAdvanced()">
            Advanced Options
          </button>
        </div>
      </div>

      <!-- Advanced Options Panel -->
      <div class="row">
        <div class="col-12">
          <div class="collapse show" id="advancedOptions" [ngbCollapse]="!isAdvancedOpen">
            <div class="card card-body">
              <!-- Advanced Settings -->
              <div class="row g-3 mb-2">
                <div class="col-md-6">
                  <div class="input-group">
                    <span class="input-group-text">Auto Start</span>
                    <select class="form-select" 
                            name="autoStart" 
                            [(ngModel)]="autoStart" 
                            (change)="autoStartChanged()" 
                            [disabled]="addInProgress || downloads.loading"
                            ngbTooltip="Automatically start downloads when added">
                      <option [ngValue]="true">Yes</option>
                      <option [ngValue]="false">No</option>
                    </select>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="input-group">
                    <span class="input-group-text">Download Folder</span>
                    <ng-select [items]="customDirs$ | async" 
                              placeholder="Default" 
                              [addTag]="allowCustomDir.bind(this)" 
                              addTagText="Create directory" 
                              bindLabel="folder" 
                              [(ngModel)]="folder" 
                              [disabled]="addInProgress || downloads.loading"
                              [virtualScroll]="true"
                              [clearable]="true"
                              [loading]="downloads.loading"
                              [searchable]="true"
                              [closeOnSelect]="true"
                              ngbTooltip="Choose where to save downloads. Type to create a new folder.">
                    </ng-select>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="input-group">
                    <span class="input-group-text">Custom Name Prefix</span>
                    <input type="text" 
                           class="form-control" 
                           placeholder="Default" 
                           name="customNamePrefix" 
                           [(ngModel)]="customNamePrefix" 
                           [disabled]="addInProgress || downloads.loading"
                           ngbTooltip="Add a prefix to downloaded filenames">
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="input-group">
                    <span class="input-group-text">Items Limit</span>
                    <input type="number" 
                           min="0" 
                           class="form-control" 
                           placeholder="Default" 
                           name="playlistItemLimit" 
                           (keydown)="isNumber($event)" 
                           [(ngModel)]="playlistItemLimit" 
                           [disabled]="addInProgress || downloads.loading"
                           ngbTooltip="Maximum number of items to download from a playlist (0 = no limit)">
                  </div>
                </div>
                <div class="col-12">
                  <div class="form-check form-switch">
                    <input class="form-check-input" 
                           type="checkbox" 
                           role="switch" 
                           name="playlistStrictMode" 
                           [(ngModel)]="playlistStrictMode" 
                           [disabled]="addInProgress || downloads.loading"
                           ngbTooltip="Only download playlists when URL explicitly points to a playlist">
                    <label class="form-check-label">Strict Playlist Mode</label>
                  </div>
                </div>
              </div>

              <!-- Advanced Actions -->
              <div class="row">
                <div class="col-12">
                  <hr class="my-3">
                  <div class="row g-2">
                    <div class="col-md-4">
                      <button type="button" 
                              class="btn btn-secondary w-100" 
                              (click)="openBatchImportModal()">
                        <fa-icon [icon]="faFileImport" class="me-2"></fa-icon>
                        Import URLs
                      </button>
                    </div>
                    <div class="col-md-4">
                      <button type="button" 
                              class="btn btn-secondary w-100" 
                              (click)="exportBatchUrls('all')">
                        <fa-icon [icon]="faFileExport" class="me-2"></fa-icon>
                        Export URLs
                      </button>
                    </div>
                    <div class="col-md-4">
                      <button type="button" 
                              class="btn btn-secondary w-100" 
                              (click)="copyBatchUrls('all')">
                        <fa-icon [icon]="faCopy" class="me-2"></fa-icon>
                        Copy URLs
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </form>
  
  <!-- Batch Import Modal -->
  <div class="modal fade" tabindex="-1" role="dialog" [ngClass]="{'show': batchImportModalOpen}" [ngStyle]="{'display': batchImportModalOpen ? 'block' : 'none'}">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Batch Import URLs</h5>
          <button type="button" class="btn-close" aria-label="Close" (click)="closeBatchImportModal()"></button>
        </div>
        <div class="modal-body">
          <textarea [(ngModel)]="batchImportText" class="form-control" rows="6"
            placeholder="Paste one video URL per line"></textarea>
          <div class="mt-2">
            <small *ngIf="batchImportStatus">{{ batchImportStatus }}</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-danger me-auto" *ngIf="importInProgress" (click)="cancelBatchImport()">
            Cancel Import
          </button>
          <button type="button" class="btn btn-secondary" (click)="closeBatchImportModal()">Close</button>
          <button type="button" class="btn btn-primary" (click)="startBatchImport()" [disabled]="importInProgress">
            Import URLs
          </button>
        </div>
      </div>
    </div>
  </div>
  

  <div *ngIf="downloads.loading" class="alert alert-info" role="alert">
    Connecting to server...
  </div>
  <ul class="nav nav-tabs metube-tabs">
    <li class="nav-item">
      <a class="nav-link" role="button" [class.active]="activeTab === 'queue'" (click)="setActiveTab('queue')">
        Downloading <span class="badge text-bg-secondary">{{ downloads.queue.size }}</span>
      </a>
    </li>
    <li class="nav-item">
      <a class="nav-link" role="button" [class.active]="activeTab === 'done'" (click)="setActiveTab('done')">
        Completed <span class="badge text-bg-secondary">{{ downloads.done.size }}</span>
      </a>
    </li>
  </ul>

  <div [class.d-none]="activeTab !== 'queue'">
  <div class="px-2 py-3 border-bottom d-flex align-items-center flex-wrap">
    <button type="button" class="btn btn-link text-decoration-none px-0 me-4" disabled #queueDelSelected (click)="delSelectedDownloads('queue')"><fa-icon [icon]="faTrashAlt"></fa-icon>&nbsp; Cancel selected</button>
    <button type="button" class="btn btn-link text-decoration-none px-0 me-4" disabled #queueDownloadSelected (click)="startSelectedDownloads('queue')"><fa-icon [icon]="faDownload"></fa-icon>&nbsp; Download selected</button>
    <div class="form-check form-switch d-flex align-items-center mb-0 ps-0">
      <input class="form-check-input ms-0 me-2" type="checkbox" role="switch" id="queueGroupByFolder" [(ngModel)]="groupByFolder" (change)="groupByFolderChanged()" ngbTooltip="Group downloads by folder">
      <label class="form-check-label mb-0" for="queueGroupByFolder"><fa-icon [icon]="faFolderOpen"></fa-icon>&nbsp; Group by folder</label>
    </div>
  </div>
  <div class="overflow-auto">
    <table class="table">
      <thead>
        <tr>
          <th scope="col" style="width: 1rem;">
            <app-master-checkbox #queueMasterCheckbox [id]="'queue'" [list]="downloads.queue" (changed)="queueSelectionChanged($event)"></app-master-checkbox>
          </th>
          <th scope="col">Video</th>
          <th scope="col" class="sortable-header" (click)="toggleSortOrder()" ngbTooltip="Sort by creation time">
            Created
            <fa-icon [icon]="sortAscending ? faSortUp : faSortDown"></fa-icon>
          </th>
          <th scope="col">Folder</th>
          <th scope="col" style="width: 8rem;">Speed</th>
          <th scope="col" style="width: 7rem;">ETA</th>
          <th scope="col" style="width: 6rem;"></th>
        </tr>
      </thead>
      <tbody>
        <ng-container *ngFor="let row of displayRows('queue'); trackBy: identifyDisplayRow">
          <tr *ngIf="row.type === 'header'" class="folder-group-header">
            <td colspan="7">
              <fa-icon [icon]="faFolderOpen"></fa-icon>&nbsp; {{ row.folder }}
              <span class="folder-group-count">{{ row.count }}</span>
            </td>
          </tr>
          <tr *ngIf="row.type === 'item'" [class.disabled]='row.value.deleting'>
            <td>
              <app-slave-checkbox [id]="row.key" [master]="queueMasterCheckbox" [checkable]="row.value"></app-slave-checkbox>
            </td>
            <td title="{{ row.value.filename }}">
              <div class="d-flex flex-column flex-sm-row align-items-center row-gap-2 column-gap-3">
                <div>
                  <span class="website-tag" *ngIf="row.value.website" [title]="row.value.website">{{ getSimplifiedDomain(row.value.website) }}</span>
                  {{ row.value.title }}
                </div>
                <ngb-progressbar height="1.5rem" [showValue]="row.value.status != 'preparing'" [striped]="row.value.status == 'preparing'" [animated]="row.value.status == 'preparing'" type="success" [value]="row.value.status == 'preparing' ? 100 : row.value.percent | number:'1.0-0'" class="download-progressbar"></ngb-progressbar>
              </div>
            </td>
            <td>{{ formatTimestamp(row.value.timestamp) }}</td>
            <td>{{ row.value.folder || 'Default' }}</td>
            <td>{{ row.value.speed | speed }}</td>
            <td>{{ row.value.eta | eta }}</td>
            <td>
              <div class="d-flex">
                <button *ngIf="row.value.status === 'pending'" type="button" class="btn btn-link" (click)="downloadItemByKey(row.key)"><fa-icon [icon]="faDownload"></fa-icon></button>
                <button type="button" class="btn btn-link" (click)="delDownload('queue', row.key)"><fa-icon [icon]="faTrashAlt"></fa-icon></button>
                <a href="{{row.value.url}}" target="_blank" class="btn btn-link"><fa-icon [icon]="faExternalLinkAlt"></fa-icon></a>
              </div>
            </td>
          </tr>
        </ng-container>
      </tbody>
    </table>
  </div>
  </div>

  <div [class.d-none]="activeTab !== 'done'">
  <div class="px-2 py-3 border-bottom d-flex align-items-center flex-wrap">
    <button type="button" class="btn btn-link text-decoration-none px-0 me-4" disabled #doneDelSelected (click)="delSelectedDownloads('done')"><fa-icon [icon]="faTrashAlt"></fa-icon>&nbsp; Clear selected</button>
    <button type="button" class="btn btn-link text-decoration-none px-0 me-4" disabled #doneClearCompleted (click)="clearCompletedDownloads()"><fa-icon [icon]="faCheckCircle"></fa-icon>&nbsp; Clear completed</button>
    <button type="button" class="btn btn-link text-decoration-none px-0 me-4" disabled #doneClearFailed (click)="clearFailedDownloads()"><fa-icon [icon]="faTimesCircle"></fa-icon>&nbsp; Clear failed</button>
    <button type="button" class="btn btn-link text-decoration-none px-0 me-4" disabled #doneRetryFailed (click)="retryFailedDownloads()"><fa-icon [icon]="faRedoAlt"></fa-icon>&nbsp; Retry failed</button>
    <button type="button" class="btn btn-link text-decoration-none px-0 me-4" disabled #doneDownloadSelected (click)="downloadSelectedFiles()"><fa-icon [icon]="faDownload"></fa-icon>&nbsp; Download Selected</button>
    <div class="form-check form-switch d-flex align-items-center mb-0 ps-0">
      <input class="form-check-input ms-0 me-2" type="checkbox" role="switch" id="doneGroupByFolder" [(ngModel)]="groupByFolder" (change)="groupByFolderChanged()" ngbTooltip="Group downloads by folder">
      <label class="form-check-label mb-0" for="doneGroupByFolder"><fa-icon [icon]="faFolderOpen"></fa-icon>&nbsp; Group by folder</label>
    </div>
  </div>
  <div class="overflow-auto">
    <table class="table">
      <thead>
        <tr>
          <th scope="col" style="width: 1rem;">
            <app-master-checkbox #doneMasterCheckbox [id]="'done'" [list]="downloads.done" (changed)="doneSelectionChanged($event)"></app-master-checkbox>
          </th>
          <th scope="col">Video</th>
          <th scope="col" class="sortable-header" (click)="toggleSortOrder()" ngbTooltip="Sort by creation time">
            Created
            <fa-icon [icon]="sortAscending ? faSortUp : faSortDown"></fa-icon>
          </th>
          <th scope="col">Folder</th>
          <th scope="col">File Size</th>
          <th scope="col" style="width: 8rem;"></th>
        </tr>
      </thead>
      <tbody>
        <ng-container *ngFor="let row of displayRows('done'); trackBy: identifyDisplayRow">
          <tr *ngIf="row.type === 'header'" class="folder-group-header">
            <td colspan="6">
              <fa-icon [icon]="faFolderOpen"></fa-icon>&nbsp; {{ row.folder }}
              <span class="folder-group-count">{{ row.count }}</span>
            </td>
          </tr>
          <tr *ngIf="row.type === 'item'" [class.disabled]='row.value.deleting'>
            <td>
              <app-slave-checkbox [id]="row.key" [master]="doneMasterCheckbox" [checkable]="row.value"></app-slave-checkbox>
            </td>
            <td>
              <div style="display: inline-block; width: 1.5rem;">
                <fa-icon *ngIf="row.value.status == 'finished'" [icon]="faCheckCircle" class="text-success"></fa-icon>
                <fa-icon *ngIf="row.value.status == 'error'" [icon]="faTimesCircle" class="text-danger"></fa-icon>
              </div>
              <span class="website-tag" *ngIf="row.value.website" [title]="row.value.website">{{ getSimplifiedDomain(row.value.website) }}</span>
              <span class="file-exists-indicator" *ngIf="row.value.filename" [ngClass]="{'file-exists': row.value.file_exists, 'file-missing': row.value.file_exists === false}" [title]="row.value.file_exists ? 'File exists' : 'File not found'">
                <fa-icon *ngIf="row.value.file_exists" [icon]="faCheckCircle" class="text-success"></fa-icon>
                <fa-icon *ngIf="row.value.file_exists === false" [icon]="faTimesCircle" class="text-warning"></fa-icon>
              </span>
              <span ngbTooltip="{{row.value.msg}} | {{row.value.error}}">
                <a *ngIf="!!row.value.filename && row.value.file_exists !== false; else noDownloadLink" href="{{buildDownloadLink(row.value)}}" target="_blank">{{ row.value.title }}</a>
              </span>
              <ng-template #noDownloadLink>
                {{row.value.title}}
                <span *ngIf="row.value.msg"><br>{{row.value.msg}}</span>
                <span *ngIf="row.value.error"><br>Error: {{row.value.error}}</span>
              </ng-template>
            </td>
            <td>{{ formatTimestamp(row.value.timestamp) }}</td>
            <td>{{ row.value.folder || 'Default' }}</td>
            <td>
              <span *ngIf="row.value.size">{{ row.value.size | fileSize }}</span>
            </td>
            <td>
              <div class="d-flex">
                <button *ngIf="row.value.status == 'error'" type="button" class="btn btn-link" (click)="retryDownload(row.key, row.value)"><fa-icon [icon]="faRedoAlt"></fa-icon></button>
                <a *ngIf="row.value.filename" href="{{buildDownloadLink(row.value)}}" download class="btn btn-link"><fa-icon [icon]="faDownload"></fa-icon></a>
                <a href="{{row.value.url}}" target="_blank" class="btn btn-link"><fa-icon [icon]="faExternalLinkAlt"></fa-icon></a>
                <button type="button" class="btn btn-link" (click)="delDownload('done', row.key)"><fa-icon [icon]="faTrashAlt"></fa-icon></button>
              </div>
            </td>
          </tr>
        </ng-container>
      </tbody>
    </table>
  </div>
  </div>
</main><!-- /.container -->

<footer class="footer navbar-dark bg-dark py-3 mt-5">
  <div class="container text-center">
    <div class="footer-content" *ngIf="ytDlpVersion && metubeVersion">
      <div class="version-item">
        <span class="version-label">yt-dlp</span>
        <span class="version-value">{{ytDlpVersion}}</span>
      </div>
      <div class="version-separator"></div>
      <div class="version-item">
        <span class="version-label">MeTube</span>
        <span class="version-value">{{metubeVersion}}</span>
      </div>
      <div class="version-separator"></div>
      <div class="version-item" *ngIf="ytDlpOptionsUpdateTime">
        <span class="version-label">yt-dlp-options</span>
        <span class="version-value">{{ytDlpOptionsUpdateTime}}</span>
      </div>
      <div class="version-separator" *ngIf="ytDlpOptionsUpdateTime"></div>
      <a href="https://github.com/alexta69/metube" target="_blank" class="github-link">
        <fa-icon [icon]="faGithub"></fa-icon>
        <span>GitHub</span>
      </a>
    </div>
  </div>
</footer>
