<p-dialog
  styleClass="feedback-modal-dialog"
  [header]="(showHistory() ? 'FEEDBACK.HISTORY' : 'FEEDBACK.TITLE') | translate"
  [(visible)]="visible"
  [modal]="true"
  [style]="{ width: '900px', maxWidth: '95vw' }"
  [contentStyle]="{ maxHeight: '80vh', overflowY: 'auto', overflowX: 'hidden' }"
  [maximizable]="true"
  [closable]="true"
  position="center"
  (onShow)="onShow()"
  (onHide)="showHistory.set(false)"
>
  <!-- Header bar -->
  <div class="flex items-center justify-between mb-4">
    <div class="flex items-center gap-2 text-sm text-text-secondary">
      <i class="pi pi-map-marker"></i>
      <span>{{ moduleName() }} > {{ screenName() }}</span>
    </div>
    <div class="flex items-center gap-2">
      <p-button
        icon="pi pi-cog"
        severity="secondary"
        [text]="true"
        size="small"
        (onClick)="showAiSettings.set(!showAiSettings())"
        pTooltip="AI Settings"
      />
      <p-button
        [icon]="showHistory() ? 'pi pi-plus' : 'pi pi-history'"
        severity="secondary"
        [text]="true"
        size="small"
        (onClick)="showHistory.set(!showHistory())"
        [pTooltip]="(showHistory() ? 'FEEDBACK.NEW' : 'FEEDBACK.HISTORY') | translate"
      />
    </div>
  </div>

  <!-- AI Settings Panel -->
  @if (showAiSettings()) {
    <div class="mb-4 p-4 border rounded-lg bg-surface-50 dark:bg-surface-900">
      <h4 class="text-sm font-bold mb-3">{{ 'FEEDBACK.AI_SETTINGS' | translate }}</h4>
      <div class="grid grid-cols-1 gap-3">
        <div>
          <label class="block text-sm mb-1">{{ 'FEEDBACK.AI_PROVIDER' | translate }}</label>
          <p-select
            [options]="providerOptions"
            [ngModel]="aiConfigProvider()"
            (ngModelChange)="aiConfigProvider.set($event)"
            [style]="{ width: '100%' }"
            optionLabel="label"
            optionValue="value"
          />
        </div>
        <div>
          <label class="block text-sm mb-1">DeepSeek API Key</label>
          <input
            pInputText
            type="password"
            [ngModel]="aiConfigDeepseekKey()"
            (ngModelChange)="aiConfigDeepseekKey.set($event)"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm mb-1">ChatGPT API Key</label>
          <input
            pInputText
            type="password"
            [ngModel]="aiConfigChatgptKey()"
            (ngModelChange)="aiConfigChatgptKey.set($event)"
            class="w-full"
          />
        </div>
        <p-button
          [label]="'COMMON.SAVE' | translate"
          icon="pi pi-check"
          size="small"
          (onClick)="saveAiConfig()"
        />
      </div>
    </div>
  }

  <!-- History View -->
  @if (showHistory()) {
    <div class="space-y-3">
      @if (storageService.reports().length === 0) {
        <p class="text-center text-text-secondary py-8">
          {{ 'FEEDBACK.NO_REPORTS' | translate }}
        </p>
      }
      @for (report of storageService.reports(); track report.id) {
        <div
          class="border rounded-lg p-4 hover:bg-surface-50 dark:hover:bg-surface-900 transition-colors"
        >
          <div class="flex items-center justify-between mb-2">
            <div class="flex items-center gap-2">
              @switch (report.type) {
                @case ('bug') {
                  <p-tag severity="danger" value="Bug" />
                }
                @case ('change_request') {
                  <p-tag severity="warn" value="Change" />
                }
                @case ('improvement') {
                  <p-tag severity="info" value="Improve" />
                }
                @case ('feature_request') {
                  <p-tag severity="success" value="Feature" />
                }
              }
              <span class="text-sm font-medium">
                {{ report.description | slice: 0 : 60
                }}{{ report.description.length > 60 ? '...' : '' }}
              </span>
            </div>
            <div class="flex items-center gap-1">
              <span class="text-xs text-text-secondary">{{
                report.created_at | date: 'short'
              }}</span>
              <p-button
                icon="pi pi-trash"
                severity="danger"
                [text]="true"
                size="small"
                (onClick)="storageService.delete(report.id)"
              />
            </div>
          </div>
          @if (report.ai_report) {
            <div
              class="text-xs bg-surface-100 dark:bg-surface-800 rounded p-3 mt-2 max-h-32 overflow-y-auto whitespace-pre-wrap font-mono"
            >
              {{ report.ai_report }}
            </div>
          }
          <div class="text-xs text-text-secondary mt-1">
            {{ report.module }} > {{ report.screen_name }}
            @if (report.ai_provider) {
              <span class="ms-2">({{ report.ai_provider }})</span>
            }
          </div>
        </div>
      }
    </div>
  } @else {
    <!-- New Feedback Form -->

    <!-- Step 0: Type Selection -->
    @if (currentStep() === 0) {
      <div class="grid grid-cols-2 gap-3">
        @for (type of feedbackTypes; track type.value) {
          <button
            class="type-card"
            (click)="selectType(type.value)"
            [class.selected]="feedbackType() === type.value"
          >
            <i [class]="type.icon + ' text-2xl mb-2'"></i>
            <span class="font-bold text-sm">{{ type.label | translate }}</span>
            <span class="text-xs text-text-secondary mt-1">{{
              type.desc | translate
            }}</span>
          </button>
        }
      </div>
    }

    <!-- Step 1: Details -->
    @if (currentStep() === 1) {
      <div class="space-y-4">
        <!-- Bug fields -->
        @if (feedbackType() === 'bug') {
          <div>
            <label class="block text-sm font-medium mb-1"
              >{{ 'FEEDBACK.STEPS' | translate }} *</label
            >
            <textarea
              pTextarea
              [ngModel]="stepsToReproduce()"
              (ngModelChange)="stepsToReproduce.set($event)"
              rows="3"
              class="w-full"
              [placeholder]="'FEEDBACK.STEPS_HINT' | translate"
            ></textarea>
          </div>
          <div class="grid grid-cols-2 gap-3">
            <div>
              <label class="block text-sm font-medium mb-1">{{
                'FEEDBACK.EXPECTED' | translate
              }}</label>
              <textarea
                pTextarea
                [ngModel]="expectedResult()"
                (ngModelChange)="expectedResult.set($event)"
                rows="2"
                class="w-full"
              ></textarea>
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">{{
                'FEEDBACK.ACTUAL' | translate
              }}</label>
              <textarea
                pTextarea
                [ngModel]="actualResult()"
                (ngModelChange)="actualResult.set($event)"
                rows="2"
                class="w-full"
              ></textarea>
            </div>
          </div>
        }

        <!-- Change Request fields -->
        @if (feedbackType() === 'change_request') {
          <div>
            <label class="block text-sm font-medium mb-1"
              >{{ 'FEEDBACK.CHANGE_TYPE' | translate }} *</label
            >
            <p-select
              [options]="changeTypes"
              [ngModel]="changeType()"
              (ngModelChange)="changeType.set($event)"
              optionLabel="label"
              optionValue="value"
              [placeholder]="'FEEDBACK.SELECT_CHANGE_TYPE' | translate"
              [style]="{ width: '100%' }"
            >
              <ng-template let-item pTemplate="item">
                {{ item.label | translate }}
              </ng-template>
              <ng-template let-item pTemplate="selectedItem">
                {{ item.label | translate }}
              </ng-template>
            </p-select>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1"
              >{{ 'FEEDBACK.AS_IS' | translate }} *</label
            >
            <textarea
              pTextarea
              [ngModel]="asIs()"
              (ngModelChange)="asIs.set($event)"
              rows="2"
              class="w-full"
              [placeholder]="'FEEDBACK.AS_IS_HINT' | translate"
            ></textarea>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1"
              >{{ 'FEEDBACK.TO_BE' | translate }} *</label
            >
            <textarea
              pTextarea
              [ngModel]="toBe()"
              (ngModelChange)="toBe.set($event)"
              rows="2"
              class="w-full"
              [placeholder]="'FEEDBACK.TO_BE_HINT' | translate"
            ></textarea>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">{{
              'FEEDBACK.WHY' | translate
            }}</label>
            <textarea
              pTextarea
              [ngModel]="why()"
              (ngModelChange)="why.set($event)"
              rows="2"
              class="w-full"
              [placeholder]="'FEEDBACK.WHY_HINT' | translate"
            ></textarea>
          </div>
        }

        <!-- Improvement / Feature Request -->
        @if (feedbackType() === 'improvement' || feedbackType() === 'feature_request') {
          <div>
            <label class="block text-sm font-medium mb-1">{{
              'FEEDBACK.PRIORITY' | translate
            }}</label>
            <div class="flex gap-3">
              @for (p of priorities; track p.value) {
                <label class="flex items-center gap-2 cursor-pointer">
                  <p-radioButton
                    [value]="p.value"
                    [ngModel]="priority()"
                    (ngModelChange)="priority.set($event)"
                    name="priority"
                  />
                  <p-tag [severity]="p.severity" [value]="p.label | translate" />
                </label>
              }
            </div>
          </div>
        }

        @if (feedbackType() === 'feature_request') {
          <div>
            <label class="block text-sm font-medium mb-1">{{
              'FEEDBACK.TEMPLATE' | translate
            }}</label>
            <div class="flex gap-2 flex-wrap">
              @for (tpl of templateTypes; track tpl.value) {
                <button
                  class="px-3 py-2 rounded-lg border text-sm flex items-center gap-2 transition-colors"
                  [class.bg-accent]="templateType() === tpl.value"
                  [class.text-brand]="templateType() === tpl.value"
                  [class.border-accent]="templateType() === tpl.value"
                  (click)="
                    templateType.set(templateType() === tpl.value ? null : tpl.value)
                  "
                >
                  <i [class]="tpl.icon"></i>
                  {{ tpl.label | translate }}
                </button>
              }
            </div>
          </div>
        }

        <!-- Common description -->
        <div>
          <label class="block text-sm font-medium mb-1"
            >{{ 'FEEDBACK.DESCRIPTION' | translate }} *</label
          >
          <textarea
            pTextarea
            [ngModel]="description()"
            (ngModelChange)="description.set($event)"
            rows="3"
            class="w-full"
            [placeholder]="'FEEDBACK.DESCRIPTION_HINT' | translate"
          ></textarea>
        </div>

        <!-- Navigation -->
        <div class="nav-buttons flex justify-between">
          <p-button
            [label]="'COMMON.BACK' | translate"
            icon="pi pi-arrow-right"
            severity="secondary"
            (onClick)="currentStep.set(0)"
          />
          <p-button
            [label]="'COMMON.NEXT' | translate"
            icon="pi pi-arrow-left"
            iconPos="right"
            (onClick)="currentStep.set(2)"
            [disabled]="!canProceedToStep3()"
          />
        </div>
      </div>
    }

    <!-- Step 2: Element + Screenshot -->
    @if (currentStep() === 2) {
      <div class="space-y-4">
        <!-- Target Elements -->
        <div>
          <div class="flex items-center justify-between mb-2">
            <label class="text-sm font-medium">{{
              'FEEDBACK.TARGET_ELEMENTS' | translate
            }}</label>
            <p-button
              [label]="'FEEDBACK.SELECT_ELEMENT' | translate"
              icon="pi pi-search"
              severity="secondary"
              size="small"
              (onClick)="startInspector()"
            />
          </div>
          @if (targetElements().length > 0) {
            <div class="space-y-2">
              @for (el of targetElements(); track el.css_path; let i = $index) {
                <div
                  class="flex items-center gap-2 bg-surface-100 dark:bg-surface-800 rounded-lg px-3 py-2"
                >
                  <i class="pi pi-code text-xs text-text-secondary"></i>
                  <span class="text-xs font-mono flex-1 truncate">
                    &lt;{{ el.tag }}&gt; {{ el.id ? '#' + el.id : '' }} "{{
                      el.text | slice: 0 : 40
                    }}"
                  </span>
                  <p-button
                    icon="pi pi-times"
                    severity="danger"
                    [text]="true"
                    size="small"
                    (onClick)="removeElement(i)"
                  />
                </div>
              }
            </div>
          } @else {
            <p class="text-xs text-text-secondary">
              {{ 'FEEDBACK.NO_ELEMENTS' | translate }}
            </p>
          }
        </div>

        <!-- Screenshots -->
        <div>
          <div class="flex items-center justify-between mb-2">
            <label class="text-sm font-medium">{{
              'FEEDBACK.SCREENSHOTS' | translate
            }}</label>
            <div class="flex gap-2">
              <p-button
                [label]="'FEEDBACK.CAPTURE' | translate"
                icon="pi pi-camera"
                severity="secondary"
                size="small"
                (onClick)="captureScreenshot()"
                [loading]="screenshotService.capturing()"
              />
              <p-button
                [label]="'FEEDBACK.UPLOAD' | translate"
                icon="pi pi-upload"
                severity="secondary"
                size="small"
                (onClick)="fileInput.click()"
              />
              <input
                #fileInput
                type="file"
                accept="image/*"
                (change)="onFileUpload($event)"
                class="hidden"
              />
            </div>
          </div>

          @if (screenshotError()) {
            <p-message severity="error" [text]="screenshotError()" styleClass="mb-2" />
          }

          @if (screenshots().length > 0) {
            <!-- Screenshot tabs -->
            <div class="flex gap-2 mb-2">
              @for (ss of screenshots(); track $index; let i = $index) {
                <button
                  class="px-3 py-1 rounded text-xs border transition-colors"
                  [class.bg-accent]="activeScreenshotIndex() === i"
                  [class.text-brand]="activeScreenshotIndex() === i"
                  (click)="activeScreenshotIndex.set(i)"
                >
                  {{
                    ss.source === 'auto'
                      ? ('FEEDBACK.AUTO' | translate)
                      : ('FEEDBACK.UPLOAD' | translate)
                  }}
                  {{ i + 1 }}
                  <i
                    class="pi pi-times ms-1 cursor-pointer"
                    (click)="removeScreenshot(i); $event.stopPropagation()"
                  ></i>
                </button>
              }
            </div>

            <!-- Annotation editor -->
            <app-screenshot-editor
              [imageDataUrl]="screenshots()[activeScreenshotIndex()].data_url"
              (annotatedImage)="onAnnotated($event)"
            />
          } @else {
            <p class="text-xs text-text-secondary">
              {{ 'FEEDBACK.NO_SCREENSHOTS' | translate }}
            </p>
          }
        </div>

        <!-- Navigation -->
        <div class="nav-buttons flex justify-between">
          <p-button
            [label]="'COMMON.BACK' | translate"
            icon="pi pi-arrow-right"
            severity="secondary"
            (onClick)="currentStep.set(1)"
          />
          <div class="flex gap-2">
            <p-button
              [label]="'FEEDBACK.SKIP_AI' | translate"
              severity="secondary"
              (onClick)="currentStep.set(3)"
            />
            <p-button
              [label]="'FEEDBACK.GENERATE_AI' | translate"
              icon="pi pi-sparkles"
              (onClick)="generateReport()"
              [loading]="aiService.generating()"
            />
          </div>
        </div>

        @if (aiError()) {
          <p-message severity="error" [text]="aiError()" />
        }
      </div>
    }

    <!-- Step 3: AI Report + Save -->
    @if (currentStep() === 3) {
      <div class="space-y-4">
        @if (aiReport()) {
          <div class="bg-surface-100 dark:bg-surface-800 rounded-lg p-4">
            <div class="flex items-center justify-between mb-3">
              <div class="flex items-center gap-2">
                <i class="pi pi-sparkles text-accent"></i>
                <span class="text-sm font-bold">{{
                  'FEEDBACK.AI_REPORT' | translate
                }}</span>
                @if (aiProvider()) {
                  <p-tag [value]="aiProvider()!" size="small" />
                }
              </div>
              <p-button
                icon="pi pi-copy"
                severity="secondary"
                [text]="true"
                size="small"
                (onClick)="copyReport()"
                pTooltip="Copy"
              />
            </div>
            <div
              class="whitespace-pre-wrap text-sm leading-relaxed max-h-96 overflow-y-auto"
            >
              {{ aiReport() }}
            </div>
          </div>
        } @else {
          <p class="text-center text-text-secondary py-4">
            {{ 'FEEDBACK.NO_AI_REPORT' | translate }}
          </p>
        }

        <!-- Summary -->
        <div class="bg-surface-50 dark:bg-surface-900 rounded-lg p-4">
          <h4 class="text-sm font-bold mb-2">{{ 'FEEDBACK.SUMMARY' | translate }}</h4>
          <div class="grid grid-cols-2 gap-2 text-xs">
            <div>
              <strong>{{ 'FEEDBACK.TYPE' | translate }}:</strong> {{ feedbackType() }}
            </div>
            <div>
              <strong>{{ 'FEEDBACK.MODULE' | translate }}:</strong> {{ moduleName() }}
            </div>
            <div>
              <strong>{{ 'FEEDBACK.SCREEN' | translate }}:</strong> {{ screenName() }}
            </div>
            <div>
              <strong>{{ 'FEEDBACK.ELEMENTS' | translate }}:</strong>
              {{ targetElements().length }}
            </div>
            <div>
              <strong>{{ 'FEEDBACK.SCREENSHOTS_COUNT' | translate }}:</strong>
              {{ screenshots().length }}
            </div>
            @if (priority()) {
              <div>
                <strong>{{ 'FEEDBACK.PRIORITY' | translate }}:</strong>
                {{ priority() }}
              </div>
            }
          </div>
        </div>

        @if (submitSuccess()) {
          <p-message severity="success" text="تم إرسال التقرير بنجاح إلى نظام الدعم ✓" styleClass="mb-2" />
        }
        @if (submitError()) {
          <p-message severity="error" [text]="submitError()" styleClass="mb-2" />
        }

        <!-- Navigation -->
        <div class="nav-buttons flex justify-between">
          <p-button
            [label]="'COMMON.BACK' | translate"
            icon="pi pi-arrow-right"
            severity="secondary"
            (onClick)="currentStep.set(2)"
          />
          <div class="flex gap-2">
            <p-button
              [label]="'FEEDBACK.SAVE_REPORT' | translate"
              icon="pi pi-check"
              severity="secondary"
              (onClick)="saveReport()"
            />
            <p-button
              label="إرسال للدعم"
              icon="pi pi-send"
              (onClick)="submitToSupport()"
              [loading]="submitService.submitting()"
              [disabled]="submitSuccess()"
            />
          </div>
        </div>
      </div>
    }
  }
</p-dialog>
