<div class="container">
  <p-card [header]="cardHeader">
    <ng-template pTemplate="header">
      <div class="flex justify-content-between align-items-center">
        <h1 style="margin-left: 1rem">Port Knocker</h1>
        <!-- <div class="animated-title" [class.animating]="isAnimating">
            <span *ngIf="cardHeader">{{ cardHeader }}</span>
          </div> -->
        <div class="flex gap-2">
          <button
            *ngIf="!enableFSA"
            pButton
            type="button"
            label="📁 Info"
            class="p-button-text p-button-sm"
            (click)="showInfoDialog = true"
          ></button>
          <button
            *ngIf="canUseFSA && !enableFSA"
            pButton
            type="button"
            label="🚀 FSA Version"
            class="p-button-text p-button-sm"
            routerLink="/fsa"
          ></button>
        </div>
      </div>
    </ng-template>
    <form [formGroup]="form" (ngSubmit)="execute()" class="p-fluid">
      <div class="grid">
        <div class="col-12 md:col-6">
          <label>Password</label>
          <p-password
            formControlName="password"
            [feedback]="false"
            toggleMask
            inputStyleClass="w-full"
            placeholder="GO_KNOCKER_SERVE_PASS"
          ></p-password>
          <div class="mt-1 text-sm" *ngIf="!form.value.password || wrongPass">
            <span class="text-red-500" *ngIf="wrongPass">Invalid password</span>
            <span class="text-600" *ngIf="!wrongPass && !form.value.password"
              >Password is required</span
            >
          </div>
        </div>

        <div class="col-12 md:col-6">
          <label>Mode</label>
          <p-dropdown
            formControlName="mode"
            [options]="[
              { label: 'Inline', value: 'inline' },
              { label: 'YAML', value: 'yaml' }
            ]"
            optionLabel="label"
            optionValue="value"
            class="w-full"
          ></p-dropdown>
        </div>

        <div class="col-12" *ngIf="form.value.mode === 'inline'">
          <label>Targets</label>
          <input
            pInputText
            type="text"
            formControlName="targets"
            placeholder="tcp:host:port;udp:host:port"
            class="w-full"
          />
        </div>

        <div class="col-12 md:col-4" *ngIf="form.value.mode === 'inline'">
          <label>Delay</label>
          <input
            pInputText
            type="text"
            formControlName="delay"
            placeholder="1s"
            class="w-full"
          />
        </div>

        <div class="col-6 md:col-4 flex align-items-center gap-2">
          <p-checkbox formControlName="verbose" [binary]="true"></p-checkbox>
          <label class="checkbox-label">Verbose</label>
        </div>

        <div class="col-6 md:col-4 flex align-items-center gap-2">
          <p-checkbox
            formControlName="waitConnection"
            [binary]="true"
          ></p-checkbox>
          <label class="checkbox-label">Wait connection</label>
        </div>

        <div class="col-12">
          <label>Gateway</label>
          <input
            pInputText
            type="text"
            formControlName="gateway"
            placeholder="optional local ip:port"
            class="w-full"
          />
        </div>

        <div class="col-12" *ngIf="form.value.mode === 'yaml'">
          <label>YAML</label>
          <textarea
            pInputTextarea
            formControlName="configYAML"
            rows="12"
            placeholder="paste YAML or ENCRYPTED:"
            class="w-full"
          ></textarea>
        </div>

        <!-- File controls directly under YAML -->
        <div class="col-12" *ngIf="form.value.mode === 'yaml'">
          <div class="flex flex-wrap gap-2 align-items-center">
            <!-- FSA version -->
            <button
              *ngIf="enableFSA"
              pButton
              type="button"
              label="Open File (with write access)"
              (click)="openFileWithWriteAccess()"
              class="p-button-outlined"
            ></button>
            <span
              *ngIf="enableFSA && selectedFileName"
              class="text-sm text-600"
              >{{ selectedFileName }}</span
            >

            <!-- Basic version -->
            <p-fileUpload
              *ngIf="!enableFSA"
              mode="basic"
              name="file"
              chooseLabel="Choose File"
              (onSelect)="onFileUpload($event)"
              [customUpload]="true"
              [auto]="false"
              accept=".yaml,.yml,.txt,.encrypted"
              [maxFileSize]="1048576"
            ></p-fileUpload>
            <input
              *ngIf="!enableFSA && !isYamlEncrypted()"
              pInputText
              type="text"
              class="w-full md:w-6"
              placeholder="Server file path (optional)"
              formControlName="serverFilePath"
            />
          </div>
        </div>

        <!-- Row 1: Execute full width -->
        <div class="col-12">
          <button
            pButton
            type="submit"
            label="Execute"
            class="w-full"
            [loading]="executing"
            [disabled]="executing || !form.value.password || wrongPass"
            [ngClass]="{ 'p-button-danger': !form.value.password || wrongPass }"
          ></button>
        </div>
        <!-- Row 2: Encrypt / Decrypt half/half on desktop; stacked on mobile (только для YAML режима) -->
        <div class="col-12 md:col-6" *ngIf="!isInlineMode()">
          <button
            pButton
            type="button"
            label="Encrypt"
            (click)="encrypt()"
            class="p-button-secondary w-full"
            [disabled]="
              executing ||
              !form.value.password ||
              wrongPass ||
              isYamlEncrypted()
            "
          ></button>
        </div>
        <div class="col-12 md:col-6" *ngIf="!isInlineMode()">
          <button
            pButton
            type="button"
            label="Decrypt"
            (click)="decrypt()"
            class="p-button-secondary w-full"
            [disabled]="
              executing ||
              !form.value.password ||
              wrongPass ||
              !isYamlEncrypted()
            "
          ></button>
        </div>
        <!-- Row 3: Download actions half/half on desktop; stacked on mobile (только для YAML режима) -->
        <div class="col-12 md:col-6" *ngIf="!isInlineMode()">
          <button
            pButton
            type="button"
            label="Download YAML"
            (click)="downloadYaml()"
            class="p-button-text w-full"
          ></button>
        </div>
        <div class="col-12 md:col-6" *ngIf="!isInlineMode()">
          <button
            pButton
            type="button"
            label="Download Result"
            (click)="downloadResult()"
            class="p-button-text w-full"
          ></button>
        </div>
      </div>
    </form>

    <p-divider></p-divider>

    <div class="grid">
      <div class="col-12">
        <p-progressBar
          [value]="executing ? 100 : 0"
          [mode]="executing ? 'indeterminate' : 'determinate'"
        ></p-progressBar>
        <div class="mt-2 text-600" *ngIf="executing">
          Elapsed: {{ elapsedMs / 1000 | number : "1.1-1" }}s
        </div>
        <div class="mt-2 text-600" *ngIf="!executing && elapsedMs > 0">
          Last run: {{ elapsedMs / 1000 | number : "1.1-1" }}s
          <span *ngIf="lastRunTime" class="ml-2 text-500">
            ({{ lastRunTime | date : "short" }})
          </span>
        </div>
      </div>
    </div>
  </p-card>
</div>

<!-- Модальное окно с результатом выполнения -->
<p-dialog
  header="Результат выполнения"
  [(visible)]="showResultDialog"
  [modal]="true"
  [closable]="true"
  [draggable]="false"
  [resizable]="false"
  styleClass="result-dialog"
>
  <div class="dialog-content">
    <div *ngIf="result" class="mb-3">
      <h4 class="text-green-600 mb-2">✅ Успешно выполнено</h4>
      <pre class="bg-gray-50 p-3 border-round text-sm">{{ result }}</pre>
    </div>
    <div *ngIf="error" class="mb-3">
      <h4 class="text-red-600 mb-2">❌ Ошибка</h4>
      <pre class="bg-red-50 p-3 border-round text-sm text-red-700">{{
        error
      }}</pre>
    </div>
    <div *ngIf="lastRunTime" class="text-sm text-600">
      Время выполнения: {{ elapsedMs / 1000 | number : "1.1-1" }}s
      <br />
      Завершено: {{ lastRunTime | date : "short" }}
    </div>
  </div>
  <ng-template pTemplate="footer">
    <button
      pButton
      type="button"
      label="OK"
      class="p-button-primary"
      (click)="showResultDialog = false"
    ></button>
  </ng-template>
</p-dialog>

<!-- Информационное модальное окно -->
<p-dialog
  header="📁 Базовая версия"
  [(visible)]="showInfoDialog"
  [modal]="true"
  [closable]="true"
  [draggable]="false"
  [resizable]="false"
  styleClass="info-dialog"
>
  <div class="dialog-content">
    <p class="mb-3">
      Эта версия работает в любом браузере, но файлы загружаются/скачиваются
      через стандартные диалоги браузера.
    </p>
    <div *ngIf="canUseFSA" class="p-3 bg-blue-50 border-round">
      <p class="text-sm mb-2">
        💡 <strong>Доступна расширенная версия!</strong>
      </p>
      <p class="text-sm mb-3">
        Ваш браузер поддерживает прямое редактирование файлов на диске.
      </p>
      <button
        pButton
        type="button"
        label="Перейти к расширенной версии"
        class="p-button-success p-button-sm"
        routerLink="/fsa"
        (click)="showInfoDialog = false"
      ></button>
    </div>
  </div>
</p-dialog>
